Clearing intent

2020-01-25 13:29发布

My Android app is getting called by an intent that is passing information (pendingintent in statusbar).

When I hit the home button and reopen my app by holding the home button it calls the intent again and the same extras are still there.

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
      super.onSaveInstanceState(savedInstanceState);
    }
    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
      super.onRestoreInstanceState(savedInstanceState);
    }

this is the code that doesn't run like its supposed to

    String imgUrl;
    Bundle extras = this.getIntent().getExtras();


    if(extras != null){
        imgUrl = extras.getString("imgUrl");
        if( !imgUrl.equals(textView01.getText().toString()) ){

            imageView.setImageDrawable( getImageFromUrl( imgUrl ) );
            layout1.setVisibility(0);
            textView01.setText(imgUrl);//textview to hold the url

        }

    }

And my intent:

public void showNotification(String ticker, String title, String message, 
    String imgUrl){
    String ns = Context.NOTIFICATION_SERVICE;
    NotificationManager mNotificationManager = 
        (NotificationManager) getSystemService(ns);
    int icon = R.drawable.icon;        // icon from resources
    long when = System.currentTimeMillis();         // notification time
    CharSequence tickerText = ticker;              // ticker-text

    //make intent
    Intent notificationIntent = new Intent(this, activity.class);
    notificationIntent.putExtra("imgUrl", imgUrl);
    notificationIntent.setFlags(
        PendingIntent.FLAG_UPDATE_CURRENT | 
        PendingIntent.FLAG_ONE_SHOT);
    PendingIntent contentIntent = 
        PendingIntent.getActivity(this, 0, 
        notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT | 
        PendingIntent.FLAG_ONE_SHOT);

    //make notification
    Notification notification = new Notification(icon, tickerText, when);
    notification.setLatestEventInfo(this, title, message, contentIntent);
    //flags
    notification.flags = Notification.FLAG_SHOW_LIGHTS | 
        Notification.FLAG_ONGOING_EVENT | 
        Notification.FLAG_ONLY_ALERT_ONCE | 
        Notification.FLAG_AUTO_CANCEL;
    //sounds
    notification.defaults |= Notification.DEFAULT_SOUND;
    //notify
    mNotificationManager.notify(1, notification);
}

Is there any way to clear the intent or check whether it has been used before?

19条回答
\"骚年 ilove
2楼-- · 2020-01-25 14:07

This will hopefully help everyone. So first we get the intent

//globally
Intent myIntent;

Place this somewhere onCreate

myIntent = getIntent();
String data = myIntent.getStringExtra("yourdata");
//Your process here

Now lets set this so everytime our app gets destroyed or exited we will remove the data

@Override
protected void onDestroy() {
    //TODO: Clear intents
    super.onDestroy();
    myIntent.removeExtra("data");
}
@Override
protected void onBackPressed() {
    //TODO: Clear intents
    super.onBackPressed();
    myIntent.removeExtra("data");
}

You get the idea, if this is not enough just find more 'on' callbacks

查看更多
神经病院院长
3楼-- · 2020-01-25 14:07

While the Intent.removeExtra("key") will remove one specific key from the extras, there is also the method Intent.replaceExtras(Bundle), which can be used to delete the whole extras from the Intent, if null is passed as a parameter.

From the docs:

Completely replace the extras in the Intent with the given Bundle of extras.

Parameters
extras The new set of extras in the Intent, or null to erase all extras.

Because the putXXX() methods initialize the extras with a fresh Bundle if its null, this is no problem.

查看更多
淡お忘
4楼-- · 2020-01-25 14:09

Make sure that you are using PendingIntent.FLAG_UPDATE_CURRENT flag for PendingIntent.

PendingIntent pendingIntent = PendingIntent.getActivity(this, 100, mPutIntent, PendingIntent.FLAG_UPDATE_CURRENT);

Where mPutIntent is your Intent.

Hope this will help you.

查看更多
家丑人穷心不美
5楼-- · 2020-01-25 14:09

I couldn't find a way to remove Intent Extra. None of the answers about removing extra from intent works if you enable "Do Not Keep Activities" from Developer Options (That way you can destroy Activity and come back to test if Extras are still there).

As a solution to the problem, i stored boolean value in SharedPreferences after Intent Extras are processed. When same Intent is redelivered to the Activity, i check the SharedPreference value and decide to process the Intent Extra. In case you send another new Intent Extra to same Activity, you make SharedPreference value false and Activity will process it. Example:

// Start Activity with Intent Extras
Intent intent = new Intent(context, MyActivity.class);
intent.putExtra("someData", "my Data");
// Set data as not processed
context.getSharedPreferences(BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE).edit().putBoolean("myActivityExtraProccessed", false).commit();
context.startActivity(intent);

...

public class MyActivity{

    ...
    public void someMethod(){
        boolean isExtrasProcessed = context.getSharedPreferences(BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE).getBoolean("myActivityExtraProccessed", false);  
         if (!isExtrasProcessed) {
              // Use Extras

              //Set data as processed
              context.getSharedPreferences(BuildConfig.APPLICATION_ID, Context.MODE_PRIVATE).edit().putBoolean("myActivityExtraProccessed", true).commit();
         }
    }

}
查看更多
爷的心禁止访问
6楼-- · 2020-01-25 14:10

Clearing an intent object:

intent.replaceExtras(new Bundle());
intent.setAction("");
intent.setData(null);
intent.setFlags(0);
查看更多
男人必须洒脱
7楼-- · 2020-01-25 14:10

The straight forward way is to avoid calling getIntent() from methods other than onCreate(). But this will cause problem during next launch if the user left our Activity by tapping the Home button. I think this problem don't have a fully functional solution.

查看更多
登录 后发表回答