Starting app only if its not currently running

后端 未结 11 1686
我寻月下人不归
我寻月下人不归 2020-12-02 23:07

I am sending push notification to users which when clicking on it opens the app.

My problem is that when the app is already open, clicking on the notification start

11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-02 23:35

    String appPackageName = "";
    
    private void isApplicationInForeground() throws Exception {
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            final List processInfos = am
                    .getRunningAppProcesses();
            ActivityManager.RunningAppProcessInfo processInfo = processInfos
                    .get(0);
            // for (ActivityManager.RunningAppProcessInfo processInfo : processInfos) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                // getting process at 0th index means our application is on top on all apps or currently open 
                appPackageName = (Arrays.asList(processInfo.pkgList).get(0));
            }
            // }
        }
        else {
            List taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = null;
            componentInfo = taskInfo.get(0).topActivity;
            appPackageName = componentInfo.getPackageName();
        }
    }
    
    private void notifyMessage(String text) {
        if (appPackageName.contains("com.example.test")) {
            // do not notify
        }
        else {          
            // create notification and notify user  
        }
    }
    

提交回复
热议问题