How to bring a background task to the front below honeycomb?

前端 未结 2 1781
心在旅途
心在旅途 2020-11-30 14:22

in my applications root activity, I have a customized tab bar, containing three tabs to switch between three screens implemented using ViewFlipper.

What I now want

2条回答
  •  死守一世寂寞
    2020-11-30 15:12

    In versions honeycomb and up, you can use MoveTaskToFront like so

    //Bring Task to front with Android >= Honeycomb
    if (Build.VERSION.SDK_INT >= 11) {
        ActivityManager am = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
        List rt = am.getRunningTasks(Integer.MAX_VALUE);
    
        for (int i = 0; i < rt.size(); i++) 
        {
               // bring to front
               if (rt.get(i).baseActivity.toShortString().indexOf("yourproject") > -1) {                     
                  am.moveTaskToFront(rt.get(i).id, ActivityManager.MOVE_TASK_WITH_HOME);
               }
        }
    }
    

    Make sure your Project Compiles with Android v.11 or up sothat this line doesn't break with compile:

    am.moveTaskToFront(rt.get(i).id, ActivityManager.MOVE_TASK_WITH_HOME);

    For older Android versions you can use the following to move the task to the front:

    Intent intent = new Intent(this, YourClass.class);//The class you want to show
    startActivity(intent);
    

    In the android manifest add the following

    
    
    
    
    
    
    
    
    
    

    And then lastly, Make sure when you push the task to back by overriding the onBackPressed(), DO NOT USE moveTaskToBack(), It will result in your task not ending up visible to the user. Rather use the following: This will simulate a home button press which will effectively hide your application and show the home screen

    @Override
    public void onBackPressed() {
        Utils.showToast(this, "Your application is running in the background");
        /*Simulate Home Button Press*/
        Intent startMain = new Intent(Intent.ACTION_MAIN);
        startMain.addCategory(Intent.CATEGORY_HOME);
        startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(startMain);
    }
    

    And there you go, I hope this works for you and helps a few people with this problem.

提交回复
热议问题