Starting app only if its not currently running

后端 未结 11 1718
我寻月下人不归
我寻月下人不归 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:33

    first of all set a default Task android:taskAffinity="com.example.testp.yourPreferredName" in your Application element in the Manifest file. Maintain your android:launchMode="singleTask" on your SplashActivity. Now since your SplashActivity is your main entry add this code to both onResume(), onNewIntent() and onCreate() (on a second thought onResume() is not recomended) -follow the comments in the code

    //Note these following lines of code will work like magic only if its UPVOTED.
    //so upvote before you try it.-or it will crash with SecurityException
    ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
    
    List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1000);    
        for(int i =0; i< taskInfo.size(); i++){
            String PackageName = taskInfo.get(i).baseActivity.getPackageName();
            if(PackageName.equals("packagename.appname")){// suppose stackoverflow.answerer.Elltz
                //if the current runing actiivity is not the splash activity. it will be 1
                //only if this is the first time your  is be called as a task
                if(taskInfo.get(i).numActivities >1){
                    //other activities are running, so kill this splash dead!! reload!!                 
                    finish();
                    // i am dying in onCreate..(the user didnt see nothing, that's the good part)
                    //about this code. its a silent assassin
                }
                //Operation kill the Splash is done so retreat to base.
                break;
            }
        }
    

    This code will not work on api 21+; to make it work you need to use AppTask, this will save you extra lines of code as you will not be in a Loop to find your Task.

    Hope it helps

提交回复
热议问题