【问题标题】:onNewIntent not called on restartonNewIntent 未在重新启动时调用
【发布时间】:2014-02-06 05:04:51
【问题描述】:

我有一个闹钟应用,它使用闹钟管理器和广播接收器。 该应用程序是一个单一的活动和 4 个片段。当警报响起时,onReceive 方法会向主活动发送一个意图,主活动在 onNewIntent 方法中接收此意图,然后移动到正确的片段。一切正常,除非在应用程序关闭后警报响起。

一旦我销毁应用程序,警报仍然会响起,并且广播接收器的意图会触发,但 onNewIntent 方法确实会捕获意图并将应用程序移动到正确的片段。

这是移动到主要活动的广播接收器类中的 Intent

Intent alarmIntent = new Intent( context, ClockActivity.class );
                alarmIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);
                alarmIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
                alarmIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                alarmIntent.putExtra("Alarm Name", receivedAlarm.getmName());
                context.startActivity(alarmIntent);

这是我的主要活动中的 onNewIntent 方法,在应用关闭时调用警报时不会调用该方法。

    @Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);

    PhraseFragment phraseFragment = new PhraseFragment();

    String activeName = intent.getStringExtra("Alarm Name");

    Bundle args = new Bundle();
    args.putString("activeName", activeName);
    phraseFragment.setArguments(args);

    getFragmentManager().beginTransaction()
            .replace(R.id.container, phraseFragment)
            .addToBackStack("phrase")
            .commit();

}

【问题讨论】:

标签: android-intent broadcastreceiver alarmmanager android-alarms onnewintent


【解决方案1】:

这有点晚了,但也许这可以帮助某人。

正如我所见,在后台打开活动时会调用 onNewIntent。当您向不在后台运行的 Activity 发送 Intent 时,您可以通过 onResume() 上的 getIntent 检索它。

我会将您的代码更改为以下内容。

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

    Intent intent = getIntent();
    String activeName = intent.getStringExtra("Alarm Name");

    if (activeName != null){
        PhraseFragment phraseFragment = new PhraseFragment();

        Bundle args = new Bundle();
        args.putString("activeName", activeName);
        phraseFragment.setArguments(args);

        getFragmentManager().beginTransaction()
                .replace(R.id.container, phraseFragment)
               .addToBackStack("phrase")
               .commit();
     }
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    setIntent(intent);
}

在这种情况下,您需要检查您在 onResume() 中收到的意图是否包含您需要的数据。

请注意,我在文档中没有找到对此的任何引用。这只是我通过实验得出的结论。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 2013-12-01
    相关资源
    最近更新 更多