如何使getRunningAppProcesses()在Android L和更高版本中工作

时间:2016-03-24 08:05:24

标签: java android xml

我正在尝试开发一款适用于Android的应用,它只会显示一条Toast信息,上面写着" WhatsApp正在运行"当用户打开WhatsApp应用程序时。

我使用以下代码来完成工作,但它无法正常工作。有没有办法让它适用于所有设备,包括Android L和M

我搜索了很多天,但得不到合适的答案。

public void WhatsApp() {

        final String str = "";
        int whatsapplaunched = 0;
        int whatsappclosed =0;
        int whatsapplaunches = 1;

        ActivityManager am = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
        List<ActivityManager.RunningAppProcessInfo> runningAppProcessInfo = am.getRunningAppProcesses();

        for ( ActivityManager.RunningAppProcessInfo appProcess: runningAppProcessInfo ) {
            Log.d(appProcess.processName.toString(),"is running");
            if (appProcess.processName.equals("com.whatsapp")) {
                if (appProcess.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND){
                    if (whatsapplaunched == 0 ){
                        whatsapplaunched = 1;
                        Log.d(str,"WhatsApp has been launched");
                        Toast.makeText(getApplicationContext(), "WhatsApp is running", Toast.LENGTH_LONG).show();
                    } // Last If Ends
                    else if (whatsappclosed == 1){
                        whatsapplaunches++;
                        whatsappclosed = 0;
                        Log.d(String.valueOf(whatsapplaunches),"counter");
                    } // Else If Ends
                } // 2 IF Ends
                else {
                    whatsappclosed = 1;
                    Log.d(str,"WhatsApp has been closed");
                } // Else Ends
            } // Main If Ends
        } // For Ends
}

先谢谢

1 个答案:

答案 0 :(得分:0)

您可以尝试此代码

  ActivityManager manager=(ActivityManager)this.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningAppProcessInfo> processes=manager.getRunningAppProcesses();
    int i=0;
    for(ActivityManager.RunningAppProcessInfo process:processes)
    {
       if(process.processName.contains("com.whatsapp"))
                {
                   Toast.makeText(getBaseContext(), "Whatsapp running", Toast.LENGTH_SHORT).show();
                }
                break;
    }