Java Code Examples for android.content.ComponentName

The following are top voted examples for showing how to use android.content.ComponentName. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: ScreenOffTime   File: MainActivity.java   View source code 6 votes vote down vote up
private void disableComponent() {
        PackageManager packageManager = getPackageManager();
        ComponentName componentName = new ComponentName(this, MainActivity.class);
//        packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
//                PackageManager.DONT_KILL_APP);
        int res = packageManager.getComponentEnabledSetting(componentName);
        if (res == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
                || res == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
            // 隐藏应用图标
            packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);
        } else {
            // 显示应用图标
            packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
                    PackageManager.DONT_KILL_APP);
        }
    }
 
Example 2
Project: C500Companion   File: C500Service.java   View source code 6 votes vote down vote up
public void openApplication(Context context, String packageName) {
    PackageInfo pi;
    try {
        pi = context.getPackageManager().getPackageInfo(packageName, 0);
    } catch (PackageManager.NameNotFoundException e) {
        pi = null;
        e.printStackTrace();
    }
    if (pi != null) {
        Intent resolveIntent = new Intent("android.intent.action.MAIN", null);
        resolveIntent.setPackage(pi.packageName);
        ResolveInfo ri = (ResolveInfo) context.getPackageManager().queryIntentActivities(resolveIntent, 0).iterator().next();
        if (ri != null) {
            packageName = ri.activityInfo.packageName;
            String className = ri.activityInfo.name;
            Intent intent = new Intent("android.intent.action.MAIN");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(new ComponentName(packageName, className));
            context.startActivity(intent);
        }
    }
}
 
Example 3
Project: CryptoVoice   File: GcmIntentService.java   View source code 6 votes vote down vote up
private 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 4
Project: ProgressManager   File: a.java   View source code 6 votes vote down vote up
/**
 * Obtain an {@link Intent} that will launch an explicit target activity specified by
 * this activity's logical parent. The logical parent is named in the application's manifest
 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
 * Activity subclasses may override this method to modify the Intent returned by
 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
 * the parent intent entirely.
 *
 * @return a new Intent targeting the defined parent of this activity or null if
 *         there is no valid parent.
 */
@Nullable
public Intent getParentActivityIntent() {
    final String parentName = mActivityInfo.parentActivityName;
    if (TextUtils.isEmpty(parentName)) {
        return null;
    }

    // If the parent itself has no parent, generate a main activity intent.
    final ComponentName target = new ComponentName(this, parentName);
    try {
        final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
        final String parentActivity = parentInfo.parentActivityName;
        final Intent parentIntent = parentActivity == null
                ? Intent.makeMainActivity(target)
                : new Intent().setComponent(target);
        return parentIntent;
    } catch (NameNotFoundException e) {
        Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
                "' in manifest");
        return null;
    }
}
 
Example 5
Project: ProgressManager   File: a.java   View source code 6 votes vote down vote up
/**
 * Obtain an {@link Intent} that will launch an explicit target activity specified by
 * this activity's logical parent. The logical parent is named in the application's manifest
 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
 * Activity subclasses may override this method to modify the Intent returned by
 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
 * the parent intent entirely.
 *
 * @return a new Intent targeting the defined parent of this activity or null if
 *         there is no valid parent.
 */
@Nullable
public Intent getParentActivityIntent() {
    final String parentName = mActivityInfo.parentActivityName;
    if (TextUtils.isEmpty(parentName)) {
        return null;
    }

    // If the parent itself has no parent, generate a main activity intent.
    final ComponentName target = new ComponentName(this, parentName);
    try {
        final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
        final String parentActivity = parentInfo.parentActivityName;
        final Intent parentIntent = parentActivity == null
                ? Intent.makeMainActivity(target)
                : new Intent().setComponent(target);
        return parentIntent;
    } catch (NameNotFoundException e) {
        Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
                "' in manifest");
        return null;
    }
}
 
Example 6
Project: StopApp   File: SettingActivity.java   View source code 6 votes vote down vote up
/**
     * 切换桌面图标
     *
     * @param componentDisabledName
     * @param componentEnabledName
     */
    private void setComponentEnabled(ComponentName componentDisabledName
            , ComponentName componentEnabledName) {
        PackageManager pm = getPackageManager();
        pm.setComponentEnabledSetting(componentDisabledName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(componentEnabledName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
        snackBarShow(mCoordinatorLayout, getString(R.string.launcher_icon_had_change));
        // Find launcher and kill it (restart launcher)
        // MIUI8 Android6.0.6:android.content.pm.PackageManager$NameNotFoundException
//        ActivityManager am = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
//        Intent i = new Intent(Intent.ACTION_MAIN);
//        i.addCategory(Intent.CATEGORY_HOME);
//        i.addCategory(Intent.CATEGORY_DEFAULT);
//        List<ResolveInfo> resolves = pm.queryIntentActivities(i, 0);
//        for (ResolveInfo res : resolves) {
//            if (res.activityInfo != null) {
//                am.killBackgroundProcesses(res.activityInfo.packageName);
//            }
//        }
    }
 
Example 7
Project: chromium-for-android-56-debug-video   File: MediaNotificationManager.java   View source code 6 votes vote down vote up
private MediaSessionCompat createMediaSession() {
    MediaSessionCompat mediaSession = new MediaSessionCompat(
            mContext,
            mContext.getString(R.string.app_name),
            new ComponentName(mContext.getPackageName(),
                    getButtonReceiverClassName()),
            null);
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
            | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(mMediaSessionCallback);

    // TODO(mlamouri): the following code is to work around a bug that hopefully
    // MediaSessionCompat will handle directly. see b/24051980.
    try {
        mediaSession.setActive(true);
    } catch (NullPointerException e) {
        // Some versions of KitKat do not support AudioManager.registerMediaButtonIntent
        // with a PendingIntent. They will throw a NullPointerException, in which case
        // they should be able to activate a MediaSessionCompat with only transport
        // controls.
        mediaSession.setActive(false);
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mediaSession.setActive(true);
    }
    return mediaSession;
}
 
Example 8
Project: ProgressManager   File: a.java   View source code 6 votes vote down vote up
/**
 * Dismiss the Keyboard Shortcuts screen.
 */
public final void dismissKeyboardShortcutsHelper() {
    Intent intent = new Intent(Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS);
    intent.setComponent(new ComponentName(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME,
            KEYBOARD_SHORTCUTS_RECEIVER_CLASS_NAME));
    sendBroadcast(intent);
}
 
Example 9
Project: AppChooser   File: ResolversFragment.java   View source code 6 votes vote down vote up
@Override
public void showFileContent(ActivityInfo activityInfo, File file,
                            int requestCode) throws AppChooserException {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setComponent(new ComponentName(activityInfo.getPkg(), activityInfo.getCls()));
    intent.setDataAndType(Uri.fromFile(file), activityInfo.getMimeType());
    ComponentName componentName = intent.resolveActivity(getActivity().getPackageManager());
    if (componentName != null) {
        try {
            if (requestCode == ResolversConsts.DEFAULT_REQUEST_CODE) {
                getActivity().startActivity(intent);
            } else {
                getActivity().startActivityForResult(intent, requestCode);
            }
        } catch (ActivityNotFoundException e) {
            throw new AppChooserException(e);
        }
    } else {
        throw new AppChooserException();
    }
}
 
Example 10
Project: DizzyPassword   File: MyApplication.java   View source code 6 votes vote down vote up
/**
 * 根据包名打开第三方应用
 *
 * @param context
 * @param packageName
 * @throws PackageManager.NameNotFoundException
 */
public static void openAppByPackageName(Context context, String packageName) throws PackageManager.NameNotFoundException {
    PackageInfo pi;
    try {
        pi = MyApplication.getContext().getPackageManager().getPackageInfo(packageName, 0);
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.setPackage(pi.packageName);
        PackageManager pManager = MyApplication.getContext().getPackageManager();
        List<ResolveInfo> apps = pManager.queryIntentActivities(resolveIntent, 0);
        ResolveInfo ri = apps.iterator().next();
        if (ri != null) {
            packageName = ri.activityInfo.packageName;
            String className = ri.activityInfo.name;
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);//重点是加这个
            ComponentName cn = new ComponentName(packageName, className);
            intent.setComponent(cn);
            context.startActivity(intent);
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
}
 
Example 11
Project: LaunchEnr   File: LauncherAppWidgetInfo.java   View source code 6 votes vote down vote up
public LauncherAppWidgetInfo(int appWidgetId, ComponentName providerName) {
    if (appWidgetId == CUSTOM_WIDGET_ID) {
        itemType = LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
    } else {
        itemType = LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET;
    }

    this.appWidgetId = appWidgetId;
    this.providerName = providerName;

    // Since the widget isn't instantiated yet, we don't know these values. Set them to -1
    // to indicate that they should be calculated based on the layout and minWidth/minHeight
    spanX = -1;
    spanY = -1;
    // We only support app widgets on current user.
    user = Process.myUserHandle();
    restoreStatus = RESTORE_COMPLETED;
}
 
Example 12
Project: ProgressManager   File: a.java   View source code 6 votes vote down vote up
/**
 * Request the Keyboard Shortcuts screen to show up. This will trigger
 * {@link #onProvideKeyboardShortcuts} to retrieve the shortcuts for the foreground activity.
 */
public final void requestShowKeyboardShortcuts() {
    Intent intent = new Intent(Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS);
    intent.setComponent(new ComponentName(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME,
            KEYBOARD_SHORTCUTS_RECEIVER_CLASS_NAME));
    sendBroadcast(intent);
}
 
Example 13
Project: FirebasePost   File: NotifactionUtil.java   View source code 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 14
Project: easyfilemanager   File: DocumentsActivity.java   View source code 5 votes vote down vote up
public void onAppPicked(ResolveInfo info) {
    final Intent intent = new Intent(getIntent());
    intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_FORWARD_RESULT);
    intent.setComponent(new ComponentName(
            info.activityInfo.applicationInfo.packageName, info.activityInfo.name));
    startActivityForResult(intent, CODE_FORWARD);
}
 
Example 15
Project: PDialogs-Android   File: InternetWarning.java   View source code 5 votes vote down vote up
@Override
public void onClick(View view) {
    int i = view.getId();
    if (i == R.id.gprsACBtn) {
        context.startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS)
                .addCategory(Intent.ACTION_MAIN)
                .setComponent(new ComponentName("com.android.settings"
                        , "com.android.settings.Settings$DataUsageSummaryActivity"))
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        dismiss();
    } else if (i == R.id.wifiACBtn) {
        context.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
        dismiss();
    }
}
 
Example 16
Project: lineagex86   File: NotificationStation.java   View source code 5 votes vote down vote up
@Override
public void onAttach(Activity activity) {
    logd("onAttach(%s)", activity.getClass().getSimpleName());
    super.onAttach(activity);
    mContext = activity;
    mPm = mContext.getPackageManager();
    mNoMan = INotificationManager.Stub.asInterface(
            ServiceManager.getService(Context.NOTIFICATION_SERVICE));
    try {
        mListener.registerAsSystemService(mContext, new ComponentName(mContext.getPackageName(),
                this.getClass().getCanonicalName()), ActivityManager.getCurrentUser());
    } catch (RemoteException e) {
        Log.e(TAG, "Cannot register listener", e);
    }
}
 
Example 17
Project: item-reaper   File: ItemWidgetProvider.java   View source code 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    if (intent.getAction().equals(ACTION_DATA_UPDATED)) {
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        int[] appWidgetIds = appWidgetManager.getAppWidgetIds(
                new ComponentName(context, getClass()));
        appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list);
    }
}
 
Example 18
Project: TPlayer   File: VJobSchedulerService.java   View source code 5 votes vote down vote up
@Override
public List<JobInfo> getAllPendingJobs() throws RemoteException {
    int vuid = VBinder.getCallingUid();
    List<JobInfo> jobs = mScheduler.getAllPendingJobs();
    synchronized (mJobStore) {
        Iterator<JobInfo> iterator = jobs.listIterator();
        while (iterator.hasNext()) {
            JobInfo job = iterator.next();
            if (!VASettings.STUB_JOB.equals(job.getService().getClassName())) {
                // Schedule by Host, invisible in VA.
                iterator.remove();
                continue;
            }
            Map.Entry<JobId, JobConfig> jobEntry = findJobByVirtualJobId(job.getId());
            if (jobEntry == null) {
                iterator.remove();
                continue;
            }
            JobId jobId = jobEntry.getKey();
            JobConfig config = jobEntry.getValue();
            if (jobId.vuid != vuid) {
                iterator.remove();
                continue;
            }
            mirror.android.app.job.JobInfo.jobId.set(job, jobId.clientJobId);
            mirror.android.app.job.JobInfo.service.set(job, new ComponentName(jobId.packageName, config.serviceName));
        }
    }
    return jobs;
}
 
Example 19
Project: container   File: VActivityManagerService.java   View source code 5 votes vote down vote up
private void performScheduleReceiver(IVClient client, int vuid, ActivityInfo info, Intent intent,
                                     PendingResultData result) {

    ComponentName componentName = ComponentUtils.toComponentName(info);
    BroadcastSystem.get().broadcastSent(vuid, info, result);
    try {
        client.scheduleReceiver(componentName, intent, result);
    } catch (Throwable e) {
        if (result != null) {
            result.finish();
        }
    }
}
 
Example 20
Project: PingWidget   File: PingWidgetUpdateService.java   View source code 5 votes vote down vote up
@Override
public void onConfigurationChanged(Configuration newConfig) {
    Log.d(TAG, "onConfigurationChanged() " + newConfig.toString());

    //Called when screen is rotated, phone charging state changes
    //The widget gets reset, so we need to reconfigure some things

    //Get AppWidgetManager
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());

    // Get all widget ids
    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(getApplication(), PingWidgetProvider.class));

    for (int widgetId : allWidgetIds) {

        //Get widget data
        PingWidgetData data = SharedPreferencesHelper.readPingWidgetData(getApplicationContext(), widgetId);
        if(data != null) {

            //Get RemoteViews
            RemoteViews views = RemoteViewsUtil.getRemoteViews(getApplicationContext(), data.getWidgetLayoutType());

            //Update widget views
            RemoteViewsUtil.initWidgetViews(getApplicationContext(), views, data);

            //Register an Intent so that onClicks on the widget are received by PingWidgetProvider.onReceive()
            //Create an Intent, set PING_WIDGET_TOGGLE action to it, put EXTRA_APPWIDGET_ID as extra
            Util.registerWidgetStartPauseOnClickListener(getApplication(), widgetId, views);
            Util.registerWidgetReconfigureClickListener(getApplication(), widgetId, views);

            //Update the widget
            appWidgetManager.updateAppWidget(widgetId, views);
        }

    }
    super.onConfigurationChanged(newConfig);
}
 
Example 21
Project: IFWManager   File: StringFilter.java   View source code 5 votes vote down vote up
@Override
public String getValue(ComponentName resolvedComponent, Intent intent,
                       String resolvedType) {
    Uri data = intent.getData();
    if (data != null) {
        return data.getScheme();
    }
    return null;
}
 
Example 22
Project: Android-AudioRecorder-App   File: RecordFragment.java   View source code 5 votes vote down vote up
@Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
  mIsServiceBound = true;
  mAudioRecordService =
      ((AudioRecordService.ServiceBinder) iBinder).getService();
  Log.i("Tesing", " " + mAudioRecordService.isRecording() + " recording");
  audioRecordPresenter.onServiceStatusAvailable(mAudioRecordService.isRecording(),
      mAudioRecordService.isPaused());
}
 
Example 23
Project: popomusic   File: MainActivty.java   View source code 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
    mServiceMessenger = new Messenger(iBinder);
    //连接到服务
    if (null != mServiceMessenger) {
        Message msgToService = Message.obtain();
        msgToService.replyTo = mMessengerClient;
        msgToService.what = Constant.MAIN_ACTIVITY;
        try {
            mServiceMessenger.send(msgToService);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
 
Example 24
Project: Espresso   File: AppWidgetProvider.java   View source code 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    String action = intent.getAction();
    if (REFRESH_ACTION.equals(action)) {
        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        ComponentName name = new ComponentName(context, AppWidgetProvider.class);
        manager.notifyAppWidgetViewDataChanged(manager.getAppWidgetIds(name), R.id.listViewWidget);
    }
}
 
Example 25
Project: buildAPKsSamples   File: Home.java   View source code 5 votes vote down vote up
/**
 * Loads the list of installed applications in mApplications.
 */
private void loadApplications(boolean isLaunching) {
    if (isLaunching && mApplications != null) {
        return;
    }

    PackageManager manager = getPackageManager();

    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    final List<ResolveInfo> apps = manager.queryIntentActivities(mainIntent, 0);
    Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));

    if (apps != null) {
        final int count = apps.size();

        if (mApplications == null) {
            mApplications = new ArrayList<ApplicationInfo>(count);
        }
        mApplications.clear();

        for (int i = 0; i < count; i++) {
            ApplicationInfo application = new ApplicationInfo();
            ResolveInfo info = apps.get(i);

            application.title = info.loadLabel(manager);
            application.setActivity(new ComponentName(
                    info.activityInfo.applicationInfo.packageName,
                    info.activityInfo.name),
                    Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            application.icon = info.activityInfo.loadIcon(manager);

            mApplications.add(application);
        }
    }
}
 
Example 26
Project: VirtualHook   File: VActivityManagerService.java   View source code 5 votes vote down vote up
@Override
public void onActivityCreated(ComponentName component, ComponentName caller, IBinder token, Intent intent, String affinity, int taskId, int launchMode, int flags) {
    int pid = Binder.getCallingPid();
    ProcessRecord targetApp = findProcessLocked(pid);
    if (targetApp != null) {
        mMainStack.onActivityCreated(targetApp, component, caller, token, intent, affinity, taskId, launchMode, flags);
    }
}
 
Example 27
Project: AndroidBasicLibs   File: PackageUtil.java   View source code 5 votes vote down vote up
/**
 * 启动应用
 */
public static boolean startAppByPackageName(Context context, String packageName, Map<String, String> param) {
    PackageInfo pi = null;
    try {
        pi = context.getPackageManager().getPackageInfo(packageName, 0);
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
            resolveIntent.setPackage(pi.packageName);
        }

        List<ResolveInfo> apps = context.getPackageManager().queryIntentActivities(resolveIntent, 0);

        ResolveInfo ri = apps.iterator().next();
        if (ri != null) {
            String packageName1 = ri.activityInfo.packageName;
            String className = ri.activityInfo.name;

            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            ComponentName cn = new ComponentName(packageName1, className);

            intent.setComponent(cn);
            if (param != null) {
                for (Map.Entry<String, String> en : param.entrySet()) {
                    intent.putExtra(en.getKey(), en.getValue());
                }
            }
            context.startActivity(intent);
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
        ViseLog.e("启动失败");
    }
    return false;
}
 
Example 28
Project: TrainAppTFG   File: ListarYConectarBluetooth.java   View source code 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    BluetoothLeService.LocalBinder binder = (BluetoothLeService.LocalBinder) service;
    mService = binder.getService();
    Log.d("BIND", "mBound(true)");
    mBound = true;
}
 
Example 29
Project: Android_AutoSignInTool   File: Utils.java   View source code 5 votes vote down vote up
public static String getTopApp(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // 5.0及之后的方法
        UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        if (usm != null) {
            long now = System.currentTimeMillis();
            // 获取40秒之内的应用程序使用状态
            List<UsageStats> stats = usm.queryUsageStats(UsageStatsManager.INTERVAL_BEST, now - 40 * 1000, now);
            String topActivity = "";
            // 获取最新运行的程序
            if ((stats != null) && (!stats.isEmpty())) {
                int j = 0;
                for (int i = 0; i < stats.size(); i++) {
                    if (stats.get(i).getLastTimeUsed() > stats.get(j).getLastTimeUsed()) {
                        j = i;
                    }
                }
                topActivity = stats.get(j).getPackageName();
                return topActivity;
            }
        }
    } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){ // 5.0之前的方法
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = activityManager.getRunningTasks(1).get(0).topActivity;
        return cn.getPackageName();
    }
    return "Not found!";
}
 
Example 30
Project: FileDownloader-master   File: NotificationSampleActivity.java   View source code 5 votes vote down vote up
private NotificationItem(int id, String title, String desc) {
    super(id, title, desc);
    Intent[] intents = new Intent[2];
    intents[0] = Intent.makeMainActivity(new ComponentName(DemoApplication.CONTEXT,
            MainActivity.class));
    intents[1] = new Intent(DemoApplication.CONTEXT, NotificationSampleActivity.class);

    this.pendingIntent = PendingIntent.getActivities(DemoApplication.CONTEXT, 0, intents,
            PendingIntent.FLAG_UPDATE_CURRENT);

    builder = new NotificationCompat.
            Builder(FileDownloadHelper.getAppContext());

    builder.setDefaults(Notification.DEFAULT_LIGHTS)
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_MIN)
            .setContentTitle(getTitle())
            .setContentText(desc)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.mipmap.ic_launcher);

}
 
Example 31
Project: VirtualHook   File: VJobSchedulerService.java   View source code 5 votes vote down vote up
@Override
public List<JobInfo> getAllPendingJobs() throws RemoteException {
    int vuid = VBinder.getCallingUid();
    List<JobInfo> jobs = mScheduler.getAllPendingJobs();
    synchronized (mJobStore) {
        Iterator<JobInfo> iterator = jobs.listIterator();
        while (iterator.hasNext()) {
            JobInfo job = iterator.next();
            if (!StubManifest.STUB_JOB.equals(job.getService().getClassName())) {
                // Schedule by Host, invisible in VA.
                iterator.remove();
                continue;
            }
            Map.Entry<JobId, JobConfig> jobEntry = findJobByVirtualJobId(job.getId());
            if (jobEntry == null) {
                iterator.remove();
                continue;
            }
            JobId jobId = jobEntry.getKey();
            JobConfig config = jobEntry.getValue();
            if (jobId.vuid != vuid) {
                iterator.remove();
                continue;
            }
            mirror.android.app.job.JobInfo.jobId.set(job, jobId.clientJobId);
            mirror.android.app.job.JobInfo.service.set(job, new ComponentName(jobId.packageName, config.serviceName));
        }
    }
    return jobs;
}
 
Example 32
Project: ThunderMusic   File: MediaAppWidgetProvider2x1_Light.java   View source code 5 votes vote down vote up
/**
 * Check against {@link AppWidgetManager} if there are any instances of this
 * widget.
 */
private boolean hasInstances(Context context) {
    AppWidgetManager appWidgetManager = AppWidgetManager
            .getInstance(context);
    int[] appWidgetIds = appWidgetManager
            .getAppWidgetIds(new ComponentName(context, this.getClass()));
    return (appWidgetIds.length > 0);
}
 
Example 33
Project: Hello-Music-droid   File: MusicService.java   View source code 5 votes vote down vote up
private final PendingIntent retrievePlaybackAction(final String action) {
    final ComponentName serviceName = new ComponentName(this, MusicService.class);
    Intent intent = new Intent(action);
    intent.setComponent(serviceName);

    return PendingIntent.getService(this, 0, intent, 0);
}
 
Example 34
Project: LaunchEnr   File: LoaderCursor.java   View source code 5 votes vote down vote up
/**
 * Make an ShortcutInfo object for a shortcut that is an application.
 */
public ShortcutInfo getAppShortcutInfo(
        Intent intent, boolean allowMissingTarget, boolean useLowResIcon) {
    if (user == null) {
        return null;
    }

    ComponentName componentName = intent.getComponent();
    if (componentName == null) {
        return null;
    }

    Intent newIntent = new Intent(Intent.ACTION_MAIN, null);
    newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    newIntent.setComponent(componentName);
    LauncherActivityInfo lai = LauncherAppsCompat.getInstance(mContext)
            .resolveActivity(newIntent, user);
    if ((lai == null) && !allowMissingTarget) {
        return null;
    }

    final ShortcutInfo info = new ShortcutInfo();
    info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
    info.user = user;
    info.intent = newIntent;

    mIconCache.getTitleAndIcon(info, lai, useLowResIcon);
    if (mIconCache.isDefaultIcon(info.iconBitmap, user)) {
        Bitmap icon = loadIcon(info);
        info.iconBitmap = icon != null ? icon : info.iconBitmap;
    }

    if (lai != null && PackageManagerHelper.isAppSuspended(lai.getApplicationInfo())) {
        info.isDisabled = ShortcutInfo.FLAG_DISABLED_SUSPENDED;
    }

    // from the db
    if (TextUtils.isEmpty(info.title)) {
        info.title = getTitle();
    }

    // fall back to the class name of the activity
    if (info.title == null) {
        info.title = componentName.getClassName();
    }

    info.contentDescription = mUserManager.getBadgedLabelForUser(info.title, info.user);
    return info;
}
 
Example 35
Project: Utils   File: AppUtil.java   View source code 5 votes vote down vote up
/**
 * 判断当前App处于前台还是后台
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.GET_TASKS"/>}</p>
 * <p>并且必须是系统应用该方法才有效</p>
 *
 * @param context 上下文
 * @return {@code true}: 后台<br>{@code false}: 前台
 */
public static boolean isAppBackground(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    @SuppressWarnings("deprecation")
    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
        }
    }
    return false;
}
 
Example 36
Project: ReplyMessage   File: JumpPermissionManagement.java   View source code 5 votes vote down vote up
public static void LG(Activity activity) {
    Intent intent = new Intent("android.intent.action.MAIN");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
    ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings$AccessLockSummaryActivity");
    intent.setComponent(comp);
    activity.startActivity(intent);
}
 
Example 37
Project: atlas   File: BaseDelegateService.java   View source code 5 votes vote down vote up
private AdditionalServiceRecord retriveServiceByComponent(ComponentName component){
    Iterator iter = mActivateServices.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<AdditionalServiceRecord,Service> entry = (Map.Entry<AdditionalServiceRecord,Service>) iter.next();
        AdditionalServiceRecord tmpRecord = entry.getKey();
        if(tmpRecord.component.equals(component)){
            //service has created
            return tmpRecord;
        }
    }
    return null;
}
 
Example 38
Project: MuslimMateAndroid   File: PrayerWidget.java   View source code 5 votes vote down vote up
/**
 * Receive broadcast for refresh
 *
 * @param context Application context
 * @param intent  Intent to do something
 */
@Override
public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();
    if (action.equals(PRAYER_CHANGE) || action.equals(Intent.ACTION_DATE_CHANGED)) {
        AppWidgetManager gm = AppWidgetManager.getInstance(context);
        int[] ids = gm.getAppWidgetIds(new ComponentName(context, PrayerWidget.class));
        this.onUpdate(context, gm, ids);
    } else {
        super.onReceive(context, intent);
    }
}
 
Example 39
Project: GitHub   File: NetUtils.java   View source code 5 votes vote down vote up
/**
 * 打开网络设置界面
 */
public static void openSetting(Activity activity, int requestCode) {
    Intent intent = new Intent("/");
    ComponentName cm = new ComponentName("com.android.settings",
            "com.android.settings.WirelessSettings");
    intent.setComponent(cm);
    intent.setAction(Intent.ACTION_VIEW);
    activity.startActivityForResult(intent, requestCode);
}
 
Example 40
Project: serviceconnector   File: ActivityWithoutServiceConnector.java   View source code 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
    mEchoService = IEchoService.Stub.asInterface(service);
    try {
        echoMessage("Test");
    } catch (RemoteException exception) {
    }
}