【发布时间】:2019-11-16 05:09:13
【问题描述】:
我的应用反复从服务器加载数据。这些数据中有消息。
每当加载新消息时,都会在接口的回调方法 onMessagesReceived(int numOfMessages) 上调用 MainActivity。
该应用程序只有一个 Activity,每个屏幕都实现为 Fragment。片段的切换由专用的 Navigator 类管理。
我的问题是用户点击通知的处理。当用户点击通知时,应显示消息列表。
public class MainActivity extends AppCompatActivity implements MessageListener {
private static final int MESSAGE_NOTIFICATION_ID = 101010;
private static final String EXTRA_SHOW_MESSAGES = "SHOW_MESSAGES";
private Navigator mNavigator;
@Override
onMessagesReceived(int numOfMessages) {
Intent intent = new Intent(this, MainActivity.class);
testIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
testIntent.putExtra(EXTRA_SHOW_MESSAGES, true);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "testChannel")
.setSmallIcon(R.drawable.ic_message_notification)
.setContentTitle("New messages!")
.setContentText("You got " + numOfMessages + " new messages")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.setContentIntent(pendingIntent);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(MESSAGE_NOTIFICATION_ID, builder.build());
}
@Override
protected void onResume() {
super.onResume();
Bundle extras = getIntent().getExtras();
if (extras != null && extras.containsKey(EXTRA_SHOW_MESSAGES)) {
if (extras.getBoolean(EXTRA_SHOW_MESSAGES)) {
mNavigator.openMessageList();
}
}
}
}
此时,MainActivity 显示,当应用程序处于后台时,但在 onResume 中,Bundle 返回为 null。
当应用程序在前台时,什么都不会发生。
我想实现点击Notification:
- 当用户在应用程序内时,应该打开 MessageList Fragment
- 当用户不在应用内时,应在打开MessageList Fragment之前启动
有人可以给我一个提示,如何从这里开始?也许在这里使用 Intents 不是正确的解决方案?
【问题讨论】:
标签: android android-intent notifications android-pendingintent