【问题标题】:Activity isn't picking up new intent活动没有获得新的意图
【发布时间】:2011-04-11 22:39:22
【问题描述】:

由于各种原因,我的应用在通知栏中创建了条目。当用户点击通知时,我想显示一个自定义活动,以某种格式呈现条目。

Intent intent = new Intent(applicationContext, TextMessageViewerActivity.class);
intent.putExtra("text_message", someText);
PendingIntent contentIntent = PendingIntent.getActivity(applicationContext, 0, intent, 0);
// now create a notification and post it. no fancy flags

这一切都归结为通过 Intent extra 发送一个字符串,并在我的 Activity 中显示它。发生的情况是,传递给我的 Activity 的第一个 Intent 以某种方式“卡住”,并且传递给它的所有进一步 Intent 仅显示第一个 Intent 的额外内容。

public class TextMessageViewerActivity extends Activity
{
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.text_viewer);
    }

    @Override
    public void onResume()
    {
        super.onResume();

        Intent startingIntent = getIntent();
        String message = startingIntent.getStringExtra("text_message");
        String displayMessage = message != null ? message : "No message found";

        ((TextView)findViewById(R.id.text_viewer_text_id)).setText(displayMessage);
    }
}

我对 Android Activity 生命周期有哪些不了解的地方?

【问题讨论】:

    标签: android


    【解决方案1】:

    我今天学到了一些新东西:PendingIntent.getActivity 可能会为给定的Activity 返回相同的PendingIntent。要为每个要发送的唯一 Intent 创建唯一的 PendingIntent,您必须在创建时指定 PendingIntent.FLAG_ONE_SHOT 标志。

    例如,我上面代码中的 PendingIntent 创建行应该是:

    PendingIntent contentIntent = PendingIntent.getActivity(applicationContext, 0, intent, PendingIntent.FLAG_ONE_SHOT);
    

    【讨论】:

      【解决方案2】:

      我认为您需要使用onNewIntent() 函数。它改变了你的 Activity 看到的意图。用法:

      /**
        * onResume is called immediately after this.
        */
      @Override
      protected void onNewIntent(Intent intent) {
          setIntent(intent);
          resolveIntent(intent);
      }
      

      这里resolveIntent 用于实际处理新传入的intent。查看文档here

      【讨论】:

      • 这实际上是我一开始的想法,但是除非您为您的活动指定“singleTop”,否则不会调用 onNewIntent。不过,这是直观的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多