【问题标题】:ActivityManager.getRunningTasks is deprecated androidActivityManager.getRunningTasks 已弃用 android
【发布时间】:2015-09-18 07:33:24
【问题描述】:

我正在处理 android 中的推送通知,我正在使用以下方法显示通知,但问题是现在 ActivityManager.getRunningTasks(1);正在被弃用。从一个stackoverflow问题我读到:“你可以使用getAppTasks()返回一个List<AppTask>,在那里你可以获得RecentTaskInfogetTaskInfo”但我不知道如何使用它。请在这方面帮助我。

private void postNotification(Context ctx, Intent intent) {
        try {
            if (intent == null) {
                Log.d(TAG, "Receiver intent null");
            } else {
                String action = intent.getAction();
                if (action.equals("com.ziza.cy.UPDATE_STATUS")) {

                    JSONObject json = new JSONObject(intent.getExtras()
                            .getString("com.parse.Data"));

                    String type = json.getString("type");

                    if (type.equals("AlertNotification")) {

                        String msg = json.getString("header");
                        String title = "ncy";

                        ActivityManager am = (ActivityManager) ctx
                                .getSystemService(Context.ACTIVITY_SERVICE);
                        List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
                        ComponentName componentInfo = taskInfo.get(0).topActivity;

                        // don't show notification if app is in foreground
                        if (componentInfo.getPackageName().equalsIgnoreCase(
                                ctx.getPackageName())) {

                            // send broadcast receiver
                            Intent intentBroad = new Intent();
                            intentBroad.setAction(Constants.sNOTIFICATION);
                            intentBroad.putExtra("msg", msg);
                            intentBroad.putExtra("title", title
                                    + " "
                                    + taskInfo.get(0).topActivity.getClass()
                                            .getSimpleName());
                            ctx.sendBroadcast(intentBroad);
                        } else {
                            // Activity Not Running
                            // Generate Notification

                            Intent intnt = new Intent(ctx, LogInActivity.class);
                            PendingIntent contentIntent = PendingIntent
                                    .getActivity(ctx, 0, intnt, 0);
                            intnt.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                                    | Intent.FLAG_ACTIVITY_NEW_TASK);

                            NotificationCompat.Builder builder = new NotificationCompat.Builder(
                                    ctx)
                                    .setContentTitle(title)
                                    .setContentText(msg)
                                    .setTicker(msg)
                                    .setSound(
                                            RingtoneManager
                                                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                                    .setStyle(
                                            new NotificationCompat.BigTextStyle()
                                                    .bigText(msg))
                                    .setAutoCancel(true)
                                    .setSmallIcon(R.drawable.iconed)
                                    .setOnlyAlertOnce(true)
                                    .setDefaults(Notification.DEFAULT_VIBRATE);

                            Uri alarmSound = RingtoneManager
                                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
                            builder.setSound(alarmSound);
                            builder.setContentIntent(contentIntent);
                            NotificationManager notificationManager = (NotificationManager) ctx
                                    .getSystemService(Context.NOTIFICATION_SERVICE);

                            notificationManager.notify(0, builder.build());

                        }
                    }
                }
            }

        } catch (JSONException e) {
            Log.d(TAG, "JSONException: " + e.getMessage());
        }
    }

【问题讨论】:

    标签: android push-notification deprecated activity-manager


    【解决方案1】:

    这应该可以帮助您入门

    ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.AppTask> tasks = activityManager.getAppTasks();
    
    for (ActivityManager.AppTask task : tasks) {
        Log.d(TAG, "stackId: " + task.getTaskInfo().stackId);
    }
    

    【讨论】:

    • 感谢您在这里的回答。你能根据我的以下条件解释一下吗,我想像以下条件一样嵌入它:ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE); List taskInfo = am.getRunningTasks(1); ComponentName componentInfo = taskInfo.get(0).topActivity;
    • 这只返回我的活动任务
    【解决方案2】:

    你想要这个吗:

    /***
     * Checking Whether any Activity of Application is running or not
     * @param context
     * @return
     */
    public static boolean isForeground(Context context) {
    
        // Get the Activity Manager
        ActivityManager manager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    
        // Get a list of running tasks, we are only interested in the last one,
        // the top most so we give a 1 as parameter so we only get the topmost.
        List<ActivityManager.RunningAppProcessInfo> task = manager.getRunningAppProcesses();
    
        // Get the info we need for comparison.
        ComponentName componentInfo = task.get(0).importanceReasonComponent;
    
        // Check if it matches our package name.
        if(componentInfo.getPackageName().equals(context.getPackageName()))
            return true;
    
        // If not then our app is not on the foreground.
        return false;
    }
    

    【讨论】:

    • getRunningAppProcesses();仅返回一个正在运行的应用程序,它不显示所有后台应用程序。我正在使用 android lollipop 及以上版本
    【解决方案3】:

    这应该适用于 Lollipop 之前的设备以及 Lollipop 设备

    public static boolean isBackgroundRunning(Context context) {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            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())) {
                            //If your app is the process in foreground, then it's not in running in background
                            return false;
                        }
                    }
                }
            }
    
    
            return true;
        }
    

    编辑:如果应用程序在后台,它应该返回 true,而不是相反

    【讨论】:

    • Manifest 是否需要添加权限?喜欢android.permission.GET_TASKSandroid.permission.REAL_GET_TASKS
    • 谢谢它在没有添加任何权限的情况下工作
    【解决方案4】:

    在 Kotlin 中

    fun isAppRunning(context: Context): Boolean {
      val activityManager = context.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
      return activityManager.appTasks
        .filter { it.taskInfo != null }
        .filter { it.taskInfo.baseActivity != null }
        .any { it.taskInfo.baseActivity.packageName == context.packageName }
    }
    

    【讨论】:

      【解决方案5】:
         val cn: ComponentName
          val am = applicationContext.getSystemService(Context.ACTIVITY_SERVICE) as ActivityManager
          cn = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
              am.appTasks[0].taskInfo.topActivity
          } else {
              am.getRunningTasks(1)[0].topActivity
          }
      

      这对我有用

      【讨论】:

        【解决方案6】:
        ActivityManager activityManager = (ActivityManager)this.getSystemService(ACTIVITY_SERVICE);
        assert activityManager != null;
        List<ActivityManager.AppTask> tasks = activityManager.getAppTasks();
        String topClassName = tasks.get(0).getTaskInfo().topActivity.getClassName();
        

        【讨论】:

          猜你喜欢
          • 2012-12-25
          • 2021-08-31
          • 2018-02-11
          • 2018-03-10
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多