Java Code Examples for android.content.ComponentName

The following examples show how to use android.content.ComponentName. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may want to check out the right sidebar which shows the related API usage.
Example 1
Source Project: InviZible   Source File: MainActivity.java    License: GNU General Public License v3.0 6 votes vote down vote up
private void switchHotspot() {
    try {
        ApManager apManager = new ApManager(this);
        if (apManager.configApState()) {
            checkHotspotState();
        } else {
            Intent intent = new Intent(Intent.ACTION_MAIN, null);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);
            ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.TetherSettings");
            intent.setComponent(cn);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            this.startActivityForResult(intent, CODE_IS_AP_ON);
        }
    } catch (Exception e) {
        Log.e(LOG_TAG, "MainActivity onOptionsItemSelected exception " + e.getMessage() + " " + e.getCause());
    }
}
 
Example 2
Source Project: AndroidDemo   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            // TODO Auto-generated method stub
            Intent intent = new Intent();
            //设置广播的名字(设置Action)
            intent.setAction("com.example.broadcastcustom.myBroadCast");
            //携带数据
            intent.putExtra("data","Hello David");
            //Android8在静态广播的使用上做了一些限制
            //https://blog.csdn.net/yegshun/article/details/81232775
            intent.setComponent(new ComponentName("com.example.broadcastcustom","com.example.broadcastcustom.MyBroadcastReceiver"));
            //发送广播(无序广播)
            sendBroadcast(intent);
            Log.e("David","Broadcast sended !");
        }
    });

}
 
Example 3
/**
 * Do a {@link android.content.Context#startService(android.content.Intent)
 * Context.startService}, but holding a wake lock while the service starts.
 * This will modify the Intent to hold an extra identifying the wake lock;
 * when the service receives it in {@link android.app.Service#onStartCommand
 * Service.onStartCommand}, it should the Intent it receives there back to
 * {@link #completeWakefulIntent(android.content.Intent)} in order to release
 * the wake lock.
 *
 * @param context The Context in which it operate.
 * @param intent The Intent with which to start the service, as per
 * {@link android.content.Context#startService(android.content.Intent)
 * Context.startService}.
 */
public static ComponentName startWakefulService(Context context, Intent intent) {
    synchronized (mActiveWakeLocks) {
        int id = mNextId;
        mNextId++;
        if (mNextId <= 0) {
            mNextId = 1;
        }

        intent.putExtra(EXTRA_WAKE_LOCK_ID, id);
        ComponentName comp = context.startService(intent);
        if (comp == null) {
            return null;
        }

        PowerManager pm = (PowerManager)context.getSystemService(Context.POWER_SERVICE);
        PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "wake:" + comp.flattenToShortString());
        wl.setReferenceCounted(false);
        wl.acquire(60*1000);
        mActiveWakeLocks.put(id, wl);
        return comp;
    }
}
 
Example 4
Source Project: xpay   Source File: MainActivity.java    License: Apache License 2.0 6 votes vote down vote up
private boolean isEnabled()
{
    String str = getPackageName();
    String localObject = Settings.Secure.getString(getContentResolver(), "enabled_notification_listeners");
    if (!TextUtils.isEmpty(localObject))
    {
        String[] strArr = (localObject).split(":");
        int i = 0;
        while (i < strArr.length)
        {
            ComponentName localComponentName = ComponentName.unflattenFromString(strArr[i]);
            if ((localComponentName != null) && (TextUtils.equals(str, localComponentName.getPackageName())))
                return true;
            i += 1;
        }
    }
    return false;
}
 
Example 5
Source Project: protrip   Source File: NotificationUtils.java    License: MIT License 6 votes vote down vote up
/**
 * Method checks if the app is in background or not
 */
public static boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }

    return isInBackground;
}
 
Example 6
Source Project: DongWeather   Source File: WidgetProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    Log.d(TAG, "onReceive: ");
    if (TextUtils.equals(SKIP_COUNTY_WEATHER, intent.getAction())) {
        Bundle extras = intent.getExtras();
        int position = extras.getInt(ListViewService.INITENT_DATA);
        Log.d(TAG, "onReceive: position : " + position);
        Intent skipIntent = new Intent(context, WeatherActivity.class);
        skipIntent.putExtra("skipPosition", position);
        skipIntent.addFlags(FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(skipIntent);
        //AppWidgetManager.getInstance(context).updateAppWidget(mComponentName, mRemoteViews);
    }
    if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(intent.getAction())) {
        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        int[] appWidgetId = manager.getAppWidgetIds(new ComponentName(context, WidgetProvider.class));
        if (appWidgetId.length > 0) {
            manager.notifyAppWidgetViewDataChanged(appWidgetId[0], R.id.widget_listview);
        }
    }
}
 
Example 7
Source Project: android-kiosk-example   Source File: MainActivity.java    License: MIT License 6 votes vote down vote up
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    ButterKnife.bind(this);

    ComponentName deviceAdmin = new ComponentName(this, AdminReceiver.class);
    mDpm = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
    if (!mDpm.isAdminActive(deviceAdmin)) {
        Toast.makeText(this, getString(R.string.not_device_admin), Toast.LENGTH_SHORT).show();
    }

    if (mDpm.isDeviceOwnerApp(getPackageName())) {
        mDpm.setLockTaskPackages(deviceAdmin, new String[]{getPackageName()});
    } else {
        Toast.makeText(this, getString(R.string.not_device_owner), Toast.LENGTH_SHORT).show();
    }

    mDecorView = getWindow().getDecorView();

    mWebView.loadUrl("http://www.vicarasolutions.com/");
}
 
Example 8
Source Project: AndroidComponentPlugin   Source File: ActivityManager.java    License: Apache License 2.0 6 votes vote down vote up
public void writeToParcel(Parcel dest, int flags) {
    dest.writeInt(id);
    dest.writeInt(stackId);
    ComponentName.writeToParcel(baseActivity, dest);
    ComponentName.writeToParcel(topActivity, dest);
    if (thumbnail != null) {
        dest.writeInt(1);
        thumbnail.writeToParcel(dest, 0);
    } else {
        dest.writeInt(0);
    }
    TextUtils.writeToParcel(description, dest,
            Parcelable.PARCELABLE_WRITE_RETURN_VALUE);
    dest.writeInt(numActivities);
    dest.writeInt(numRunning);
    dest.writeInt(supportsSplitScreenMultiWindow ? 1 : 0);
    dest.writeInt(resizeMode);
}
 
Example 9
Source Project: LaunchTime   Source File: QuickRow.java    License: GNU General Public License v3.0 6 votes vote down vote up
public void repopulate() {
    final List<ComponentName> quickRowOrder = db().getAppCategoryOrder(QUICK_ROW_CAT);

    mQuickRow.postDelayed(new Runnable() {
        @Override
        public void run() {
            mQuickRow.removeAllViews();
            for (ComponentName actvname : quickRowOrder) {
                AppLauncher app = db().getApp(actvname);
                if (!appAlreadyHere(app)) {
                    ViewGroup item = mMainActivity.getLauncherView(app, true);
                    if (item != null) {
                        GridLayout.LayoutParams lp = new GridLayout.LayoutParams();
                        lp.columnSpec = GridLayout.spec(GridLayout.UNDEFINED, GridLayout.TOP);
                        mQuickRow.addView(item, lp);
                    }
                }
            }

        }
    }, 400);

}
 
Example 10
private void startColorSnifferApp() {
    //check app android compat currently colorSniffer api=19 and this app api=14
    try {
        Intent intent = new Intent("android.intent.action.MAIN");
        //is this correct call Rui Zhao?
        intent.setComponent(new ComponentName("ryey.colorsniffer", "ryey.colorsniffer.FormActivity"));
        //currently default color is only provided by Theme:
        //Is it required to send default colors of apps : YES
        // is it required/ to send theme related data for better experience : ask for color sniffer developer
        // 2121= dummy value
        intent.putExtra(LauncherActivity.DEFAULT_COLOR_FOR_APPS, 2121);
        launcherActivity.startActivityForResult(intent, LauncherActivity.COLOR_SNIFFER_REQUEST);
        // for activity result see LauncherActivity line 509
        cancel();
    } catch (ActivityNotFoundException e) {
        //this will never happen because this option is only shown after app is installed
        Uri uri = Uri.parse("market://details?id=ryey.colorsniffer");
        Intent i = new Intent(Intent.ACTION_VIEW, uri);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}
 
Example 11
public void onServiceConnected(ComponentName className,
        IBinder service) {
    // This is called when the connection with the service has been
    // established, giving us the service object we can use to
    // interact with the service.  We are communicating with our
    // service through an IDL interface, so get a client-side
    // representation of that from the raw service object.
    mService = new Messenger(service);
    mCallbackText.setText("Attached.");

    // We want to monitor the service for as long as we are
    // connected to it.
    try {
        Message msg = Message.obtain(null,
                MessengerService.MSG_REGISTER_CLIENT);
        msg.replyTo = mMessenger;
        mService.send(msg);
        
        // Give it some value as an example.
        msg = Message.obtain(null,
                MessengerService.MSG_SET_VALUE, this.hashCode(), 0);
        mService.send(msg);
    } catch (RemoteException e) {
        // In this case the service has crashed before we could even
        // do anything with it; we can count on soon being
        // disconnected (and then reconnected if it can be restarted)
        // so there is no need to do anything here.
    }
    
    // As part of the sample, tell the user what happened.
    Toast.makeText(Binding.this, R.string.remote_service_connected,
            Toast.LENGTH_SHORT).show();
}
 
Example 12
Source Project: LaunchTime   Source File: MainActivity.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void addWidget(AppWidgetHostView appwid) {
        if (mChildLock) return;

        ComponentName cn = appwid.getAppWidgetInfo().provider;
        String actvname = cn.getClassName();
        String pkgname = cn.getPackageName();

        String catId = db().getAppCategory(cn);
        if (mActionCategory==null) mActionCategory = mCategory;
        if (catId == null || catId.equals(mActionCategory)) {

            //Log.d(TAG, actvname + " " + pkgname);

            mWidgetHelper.saveLoadedWidget(cn,appwid);
//            mLoadedWidgets.put(actvname, appwid);
//            mPrefs.edit().putInt(actvname, appwid.getAppWidgetId()).apply();
            AppLauncher.removeAppLauncher(cn);
            AppLauncher app = AppLauncher.createAppLauncher(actvname, pkgname, pkgname, mActionCategory, true);

            db().addApp(app);
            db().addAppCategoryOrder(mActionCategory, app.getComponentName());
        } else {
            Toast.makeText(this, getString(R.string.widget_alreay,db().getCategoryDisplay(catId)), Toast.LENGTH_LONG).show();
        }


    }
 
Example 13
Source Project: Android-UtilCode   Source File: ActivityUtils.java    License: Apache License 2.0 5 votes vote down vote up
private static void startActivity(Context context, Bundle extras, String pkg, String cls, Bundle options) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    if (extras != null) intent.putExtras(extras);
    intent.setComponent(new ComponentName(pkg, cls));
    if (!(context instanceof Activity)) {
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    }
    if (options == null || Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
        context.startActivity(intent);
    } else {
        context.startActivity(intent, options);
    }
}
 
Example 14
Source Project: Aria   Source File: AndroidUtils.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 打开一个隐藏了图标的APP
 */
public static void openAppWithAction(Context context, String packageName, String activity) {
  ComponentName componentName = new ComponentName(packageName, activity);
  try {
    Intent intent = new Intent();
    intent.setComponent(componentName);
    context.startActivity(intent);
  } catch (Exception e) {
    FL.e(TAG, "没有找到应用程序:packageName:" + packageName + "  activity:" + activity);
  }
}
 
Example 15
Source Project: TurboLauncher   Source File: LauncherProvider.java    License: Apache License 2.0 5 votes vote down vote up
private ComponentName getSearchWidgetProvider() {
    SearchManager searchManager =
            (SearchManager) mContext.getSystemService(Context.SEARCH_SERVICE);
    ComponentName searchComponent = searchManager.getGlobalSearchActivity();
    if (searchComponent == null) return null;
    return getProviderInPackage(searchComponent.getPackageName());
}
 
Example 16
Source Project: RxTools-master   Source File: RxIntentTool.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 获取其他应用的Intent
 *
 * @param packageName 包名
 * @param className   全类名
 * @return 意图
 */
public static Intent getComponentNameIntent(String packageName, String className, Bundle bundle) {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    if (bundle != null) intent.putExtras(bundle);
    ComponentName cn = new ComponentName(packageName, className);
    intent.setComponent(cn);
    return intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
 
Example 17
@Override
public void setComponentEnabledSetting(ComponentName componentName,
                                       int newState, int flags) {
    try {
        mPM.setComponentEnabledSetting(componentName, newState, flags, mContext.getUserId());
    } catch (RemoteException e) {
        throw e.rethrowFromSystemServer();
    }
}
 
Example 18
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
		int[] appWidgetIds) {

	// Get all ids
	ComponentName thisWidget = new ComponentName(context,
			MyWidgetProviderSimple.class);
	int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget);

	for (int widgetId : allWidgetIds) {
		// Create some random data
		int number = (new Random().nextInt(100));

		RemoteViews remoteViews = new RemoteViews(context.getPackageName(),
				R.layout.widgetsimple_layout);
		Log.w("WidgetExample", String.valueOf(number));
		// Set the text to the view with the id R.id.update
		// instead of -1
		remoteViews.setTextViewText(R.id.update, String.valueOf(number));

		// Register an onClickListener
		Intent intent = new Intent(context, MyWidgetProviderSimple.class);

		intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
		intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, allWidgetIds);

		PendingIntent pendingIntent = PendingIntent.getBroadcast(context,
				0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
		remoteViews.setOnClickPendingIntent(R.id.update, pendingIntent);
		appWidgetManager.updateAppWidget(widgetId, remoteViews);
	}
}
 
Example 19
Source Project: OpenYOLO-Android   Source File: CredentialClient.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Provides an Activity intent to save the provided credential.
 *
 * Launch the returned intent via
 * {@link android.app.Activity#startActivityForResult(Intent, int)} and extract the result via
 * {@link #getCredentialSaveResult(Intent)} using the Intent data received in the associated
 * {@link android.app.Activity#onActivityResult(int, int, Intent)} callback.
 *
 * <pre>{@code
 * CredentialClient client = CredentialClient.getInstance(getContext());
 * Credential credential = <Valid Credential>;
 * // ...
 *
 * CredentialSaveRequest request  = CredentialSaveRequest.fromCredential(credential);
 * Intent saveCredentialIntent = client.getSaveIntent(request);
 * startActivityForResult(saveCredentialIntent, RC_SAVE_CREDENTIAL);
 *
 * // ...
 * @Override
 * public void onActivityResult(int requestCode, int resultCode, Intent data) {
 *     super.onActivityResult(requestCode, resultCode, data);
 *     if (RC_SAVE_CREDENTIAL == requestCode) {
 *        CredentialSaveResult result = client.getCredentialSaveResult(data);
 *        // handle result ...
 *     }
 * }
 * }</pre>
 *
 * @see #getCredentialSaveResult(Intent)
 */
@NonNull
public Intent getSaveIntent(final CredentialSaveRequest saveRequest) {
    List<ComponentName> saveProviders =
            ProviderResolver.findProviders(mApplicationContext, SAVE_CREDENTIAL_ACTION);

    if (saveProviders.isEmpty()) {
        ActivityResult result = ActivityResult.of(
                CredentialSaveResult.CODE_NO_PROVIDER_AVAILABLE,
                CredentialSaveResult.NO_PROVIDER_AVAILABLE.toResultDataIntent());

        return FinishWithResultActivity.createIntent(mApplicationContext, result);
    }

    byte[] encodedSaveRequest = saveRequest.toProtocolBuffer().toByteArray();

    // if there is a preferred provider, directly invoke it.
    ComponentName preferredSaveActivity = getPreferredProvider(saveProviders);
    if (preferredSaveActivity != null) {
        return createSaveIntent(
                preferredSaveActivity,
                encodedSaveRequest);
    }

    // otherwise, display a picker for all the providers.
    ArrayList<Intent> saveIntents = new ArrayList<>(saveProviders.size());
    for (ComponentName providerActivity : saveProviders) {
        saveIntents.add(createSaveIntent(
                providerActivity,
                encodedSaveRequest));
    }

    return ProviderPickerActivity.createSaveIntent(mApplicationContext, saveIntents);
}
 
Example 20
Source Project: CSipSimple   Source File: MenuBuilder.java    License: GNU General Public License v3.0 5 votes vote down vote up
public int addIntentOptions(int group, int id, int categoryOrder, ComponentName caller,
        Intent[] specifics, Intent intent, int flags, MenuItem[] outSpecificItems) {
    PackageManager pm = mContext.getPackageManager();
    final List<ResolveInfo> lri =
            pm.queryIntentActivityOptions(caller, specifics, intent, 0);
    final int N = lri != null ? lri.size() : 0;

    if ((flags & FLAG_APPEND_TO_GROUP) == 0) {
        removeGroup(group);
    }

    for (int i=0; i<N; i++) {
        final ResolveInfo ri = lri.get(i);
        Intent rintent = new Intent(
            ri.specificIndex < 0 ? intent : specifics[ri.specificIndex]);
        rintent.setComponent(new ComponentName(
                ri.activityInfo.applicationInfo.packageName,
                ri.activityInfo.name));
        final MenuItem item = add(group, id, categoryOrder, ri.loadLabel(pm))
                .setIcon(ri.loadIcon(pm))
                .setIntent(rintent);
        if (outSpecificItems != null && ri.specificIndex >= 0) {
            outSpecificItems[ri.specificIndex] = item;
        }
    }

    return N;
}
 
Example 21
private void fixStubName(ComponentName componentName) {
    if(componentName == null) {
        return;
    }
    if (PluginStubBinding.isStub(componentName.getClassName())) {
        //通过stub查询其绑定的插件组件名称,如果是Activity,只支持非Standard模式的
        //因为standard模式是1对多的关系,1个stub对应多个插件Activity,通过stub查绑定关系是是查不出来的,这种情况需要通过lifecycle来记录
        //其他模式的可以通过这种方法查出来
        String realClassName = PluginStubBinding.getBindedPluginClassName(componentName.getClassName(), StubMappingProcessor.TYPE_ACTIVITY);
        if (realClassName != null) {
            new HackComponentName(componentName).setClassName(realClassName);
        }
    }
}
 
Example 22
@Override
public void onServiceDisconnected(ComponentName serviceName) {
  logger.fine("onServiceDisconnected: %s", serviceClass);
  synchronized (lock) {
    serviceInstance = null;
  }
}
 
Example 23
Source Project: BaseProject   Source File: PackageManagerUtil.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * 判断某个指定的包名的app是否在前台
 * 判断依据为:在top(前台)
 * @deprecated  在Android 5.1之后是判断不出来的
 * @param context
 * @param classPackageName app 包名
 * @return true:在前台; false: 在非前台
 */
@Deprecated
public static boolean isAppActivitysForeground(Context context, String classPackageName) {
    ComponentName[] topAndBaseActivities = getAppTopAndBaseActivitys(context);
    if (topAndBaseActivities != null && topAndBaseActivities.length > 0) {
        ComponentName topComponentName = topAndBaseActivities[0];
        if (topComponentName != null) {
            String topAppPackageName = topComponentName.getPackageName();
            if (classPackageName.equals(topAppPackageName)) {//在前台
                return true;
            }
        }
    }
    return false;
}
 
Example 24
Source Project: MediaSDK   Source File: Util.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Calls {@link Context#startForegroundService(Intent)} if {@link #SDK_INT} is 26 or higher, or
 * {@link Context#startService(Intent)} otherwise.
 *
 * @param context The context to call.
 * @param intent The intent to pass to the called method.
 * @return The result of the called method.
 */
@Nullable
public static ComponentName startForegroundService(Context context, Intent intent) {
  if (Util.SDK_INT >= 26) {
    return context.startForegroundService(intent);
  } else {
    return context.startService(intent);
  }
}
 
Example 25
Source Project: android-performance   Source File: MainActivity.java    License: MIT License 5 votes vote down vote up
/**
 * 演示JobScheduler的使用
 */
private void startJobScheduler() {
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
        JobInfo.Builder builder = new JobInfo.Builder(1, new ComponentName(getPackageName(), JobSchedulerService.class.getName()));
        builder.setRequiresCharging(true)
                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED);
        jobScheduler.schedule(builder.build());
    }
}
 
Example 26
Source Project: Trebuchet   Source File: Workspace.java    License: GNU General Public License v3.0 5 votes vote down vote up
void updateUnvailableItemsInCellLayout(CellLayout parent, ArrayList<String> packages) {
    final HashSet<String> packageNames = new HashSet<String>();
    packageNames.addAll(packages);

    ViewGroup layout = parent.getShortcutsAndWidgets();
    int childCount = layout.getChildCount();
    for (int i = 0; i < childCount; ++i) {
        View view = layout.getChildAt(i);
        if (view instanceof BubbleTextView) {
            ItemInfo info = (ItemInfo) view.getTag();
            if (info instanceof ShortcutInfo) {
                Intent intent = info.getIntent();
                ComponentName cn = intent != null ? intent.getComponent() : null;
                if (cn != null && packageNames.contains(cn.getPackageName())) {
                    ShortcutInfo shortcut = (ShortcutInfo) info;
                    if (shortcut.isDisabled == 0) {
                        shortcut.isDisabled = 1;
                        ((BubbleTextView) view)
                                .applyFromShortcutInfo(shortcut, mIconCache, true);
                    }
                }
            }
        } else if (view instanceof FolderIcon) {
            final Folder folder = ((FolderIcon)view).getFolder();
            final FolderPagedView folderPagedView = (FolderPagedView)folder.getContent();
            final int N = folderPagedView.getItemCount();
            for (int page = 0; page < N; page++) {
                final CellLayout cellLayout = folderPagedView.getPageAt(page);
                if (cellLayout != null) {
                    updateUnvailableItemsInCellLayout(cellLayout, packages);
                }
            }
            folder.invalidate();
        }
    }
}
 
Example 27
Source Project: openinwa   Source File: MainFragment.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void openInWhatsapp() {
    try {
        Intent intent = new Intent("android.intent.action.MAIN");
        intent.setComponent(new ComponentName("com.whatsapp", "com.whatsapp.Conversation"));
        intent.putExtra("jid", getNumber(true) + "@s.whatsapp.net");
        intent.putExtra("displayname", "+" + getNumber(true));
        startActivity(Intent.parseUri("whatsapp://send/?" + getNumber(false), 0));
    } catch (URISyntaxException ignore) {
        ignore.printStackTrace();
    } catch (ActivityNotFoundException e) {
        Snackbar.make(this.getView(), R.string.label_error_whatsapp_not_installed, Snackbar.LENGTH_LONG).show();
    }
}
 
Example 28
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
    this.binder = (MainService.MainBinder) iBinder;

    try {
        generateQR();
    } catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(this, e.getMessage(), Toast.LENGTH_LONG).show();
        finish();
    }
}
 
Example 29
@Override
public List<ChooserTarget> onGetChooserTargets(ComponentName targetActivityName, IntentFilter matchedFilter) {
    final ArrayList<ChooserTarget> chooserTargets = new ArrayList<>();
    if (!EventReceiver.hasEnabledAccounts(this)) {
        return chooserTargets;
    }
    final Intent intent = new Intent(this, XmppConnectionService.class);
    intent.setAction("contact_chooser");
    Compatibility.startService(this, intent);
    bindService(intent, this, Context.BIND_AUTO_CREATE);
    try {
        waitForService();
        final ArrayList<Conversation> conversations = new ArrayList<>();
        if (!mXmppConnectionService.areMessagesInitialized()) {
            return chooserTargets;
        }

        mXmppConnectionService.populateWithOrderedConversations(conversations, textOnly(matchedFilter));
        final ComponentName componentName = new ComponentName(this, ConversationsActivity.class);
        final int pixel = AvatarService.getSystemUiAvatarSize(this);
        for (Conversation conversation : conversations) {
            if (conversation.sentMessagesCount() == 0) {
                continue;
            }
            final String name = conversation.getName().toString();
            final Icon icon = Icon.createWithBitmap(mXmppConnectionService.getAvatarService().get(conversation, pixel));
            final float score = 1 - (1.0f / MAX_TARGETS) * chooserTargets.size();
            final Bundle extras = new Bundle();
            extras.putString(ConversationsActivity.EXTRA_CONVERSATION, conversation.getUuid());
            chooserTargets.add(new ChooserTarget(name, icon, score, componentName, extras));
            if (chooserTargets.size() >= MAX_TARGETS) {
                break;
            }
        }
    } catch (InterruptedException e) {
    }
    unbindService(this);
    return chooserTargets;
}
 
Example 30
Source Project: AndroidComponentPlugin   Source File: ContextImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public boolean startInstrumentation(ComponentName className,
        String profileFile, Bundle arguments) {
    try {
        if (arguments != null) {
            arguments.setAllowFds(false);
        }
        return ActivityManagerNative.getDefault().startInstrumentation(
                className, profileFile, 0, arguments, null, null, getUserId(),
                null /* ABI override */);
    } catch (RemoteException e) {
        // System has crashed, nothing we can do.
    }
    return false;
}