Android Intent Extras Sticking Around

2019-08-20 05:52发布

Heelo , I am having an activity that opens a gridLayout upon button click.This gridLayout sends some intent extras when returning back to mainactivity.This works fine i receive the extras My issue is that if i click the home button or app goes to onPause() and returns back this intent extras are sent again with it. How can i remove them?

   try {
        name = getIntent().getExtras().getString("name");

        contact = getIntent().getExtras().getString("contact");
        tv.setText(name);
        file = getIntent().getExtras().getString("file");
        Boolean fromgrid = getIntent().getExtras().getBoolean("fromgrid");
        getIntent().removeExtra("file");
        Log.w("chat2file", file + fromgrid);

    } catch (NullPointerException e) {
        e.printStackTrace();
        file = null;
    }



@Override
protected void onPause() {

    super.onPause();
    file = null;
    SharedPreferences.Editor edit = sp.edit();
    edit.putString("runservice", "yes");
    edit.commit();
    getIntent().removeExtra("file");
    runthread = false;

}

In gridview

            i.putExtra("file", imageUrls[position]);
            i.putExtra("name", name);
            i.putExtra("contact", contact);
            i.putExtra("fromgrid", true);
            //i.setAction("actionstring" + System.currentTimeMillis());

            startActivity(i);

1条回答
时光不老,我们不散
2楼-- · 2019-08-20 06:26

Whenever possible, call Intent.removeExtra(String), where String is the key, such as "file", "name", etc.

Also, calling getIntent() returns the intent that started your activity. This may not be what you are looking for...if the intent with the extras is sent via BroadcastReceiver, you want to specify THAT intent. Be careful which intents you are removing extras from.

查看更多
登录 后发表回答