Java 类android.content.ComponentName 实例源码

项目:ScreenOffTime    文件:MainActivity.java   
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);
        }
    }
项目:C500Companion    文件:C500Service.java   
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);
        }
    }
}
项目:CryptoVoice    文件:GcmIntentService.java   
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;
}
项目:ProgressManager    文件:a.java   
/**
 * 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;
    }
}
项目:ProgressManager    文件:a.java   
/**
 * 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;
    }
}
项目:StopApp    文件:SettingActivity.java   
/**
     * 切换桌面图标
     *
     * @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);
//            }
//        }
    }
项目:chromium-for-android-56-debug-video    文件:MediaNotificationManager.java   
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;
}
项目:ProgressManager    文件:a.java   
/**
 * 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);
}
项目:AppChooser    文件:ResolversFragment.java   
@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();
    }
}
项目:DizzyPassword    文件:MyApplication.java   
/**
 * 根据包名打开第三方应用
 *
 * @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();
    }
}
项目:LaunchEnr    文件:LauncherAppWidgetInfo.java   
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;
}
项目:ProgressManager    文件:a.java   
/**
 * 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);
}
项目:FirebasePost    文件:NotifactionUtil.java   
/**
 * 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;
}
项目:easyfilemanager    文件:DocumentsActivity.java   
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);
}
项目:PDialogs-Android    文件:InternetWarning.java   
@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();
    }
}
项目:lineagex86    文件:NotificationStation.java   
@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);
    }
}
项目:item-reaper    文件:ItemWidgetProvider.java   
@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);
    }
}
项目:TPlayer    文件:VJobSchedulerService.java   
@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;
}
项目:container    文件:VActivityManagerService.java   
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();
        }
    }
}
项目:PingWidget    文件:PingWidgetUpdateService.java   
@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);
}
项目:IFWManager    文件:StringFilter.java   
@Override
public String getValue(ComponentName resolvedComponent, Intent intent,
                       String resolvedType) {
    Uri data = intent.getData();
    if (data != null) {
        return data.getScheme();
    }
    return null;
}
项目:Android-AudioRecorder-App    文件:RecordFragment.java   
@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());
}
项目:popomusic    文件:MainActivty.java   
@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();
        }
    }
}
项目:Espresso    文件:AppWidgetProvider.java   
@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);
    }
}
项目:buildAPKsSamples    文件:Home.java   
/**
 * 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);
        }
    }
}
项目:VirtualHook    文件:VActivityManagerService.java   
@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);
    }
}
项目:AndroidBasicLibs    文件:PackageUtil.java   
/**
 * 启动应用
 */
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;
}
项目:TrainAppTFG    文件:ListarYConectarBluetooth.java   
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    BluetoothLeService.LocalBinder binder = (BluetoothLeService.LocalBinder) service;
    mService = binder.getService();
    Log.d("BIND", "mBound(true)");
    mBound = true;
}
项目:Android_AutoSignInTool    文件:Utils.java   
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!";
}
项目:FileDownloader-master    文件:NotificationSampleActivity.java   
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);

}
项目:VirtualHook    文件:VJobSchedulerService.java   
@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;
}
项目:ThunderMusic    文件:MediaAppWidgetProvider2x1_Light.java   
/**
 * 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);
}
项目:Hello-Music-droid    文件:MusicService.java   
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);
}
项目:LaunchEnr    文件:LoaderCursor.java   
/**
 * 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;
}
项目:Utils    文件:AppUtil.java   
/**
 * 判断当前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;
}
项目:ReplyMessage    文件:JumpPermissionManagement.java   
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);
}
项目:atlas    文件:BaseDelegateService.java   
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;
}
项目:MuslimMateAndroid    文件:PrayerWidget.java   
/**
 * 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);
    }
}
项目:GitHub    文件:NetUtils.java   
/**
 * 打开网络设置界面
 */
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);
}
项目:serviceconnector    文件:ActivityWithoutServiceConnector.java   
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
    mEchoService = IEchoService.Stub.asInterface(service);
    try {
        echoMessage("Test");
    } catch (RemoteException exception) {
    }
}