• Background: For background downloads, the download progress must be displayed in the notification bar
  • Some time did not write native, according to the official website of the example to write, but click the notification bar to jump toActivityIt was rebuilt, causing the App to crash.

Website address: developer. The android. Google. Cn/training/no…

Sample code:

    // Create an Intent for the activity you want to start
    val resultIntent = Intent(this, ResultActivity::class.java)
    // Create the TaskStackBuilder
    val resultPendingIntent: PendingIntent? = TaskStackBuilder.create(this).run {
        // Add the intent, which inflates the back stack
        addNextIntentWithParentStack(resultIntent)
        // Get the PendingIntent containing the entire back stack
        getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
    }
Copy the code

TaskStackBuilder creates PendingIntent by adding a rebuild Activity stack to the first Intent. Problem code:

    public PendingIntent getPendingIntent(int requestCode, int flags, Bundle options) {
        if (mIntents.isEmpty()) {
            throw new IllegalStateException(
                    "No intents added to TaskStackBuilder; cannot getPendingIntent");
        }
        return PendingIntent.getActivities(mSourceContext, requestCode, getIntents(),                  flags,options);
    }
    
    @NonNull
    public Intent[] getIntents() {
        Intent[] intents = new Intent[mIntents.size()];
        if (intents.length == 0) return intents;
        intents[0] = new Intent(mIntents.get(0)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK 
                Intent.FLAG_ACTIVITY_CLEAR_TASK |
                Intent.FLAG_ACTIVITY_TASK_ON_HOME);
        for (int i = 1; i < intents.length; i++) {
            intents[i] = new Intent(mIntents.get(i));
        }
        return intents;
    }
Copy the code

Solution: deprecated TaskStackBuilder convert PendingIntent. GetActivity

  val resultIntent = Intent(this, ResultActivity::class.java)
  resultIntent.addFlags(FLAG_ACTIVITY_SINGLE_TOP)
  val resultPendingIntent = PendingIntent.getActivity(this.0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT)

Copy the code