我正在尝试通过通知和事件 onCreate
运行一个 Activity 我想“重定向”。为此在 Intent
类中添加有关信息的想法。一个重要的特性是生成通知的类是通过服务执行的。我从 android.app.Application
类提供的 getApplicationContext
方法中检索上下文。每当我调用方法 getExtras()
时都会返回 null
。我做错了什么?
public class OXAppUpdateHandler {
private void addNotification(Context context, int iconID,
CharSequence tickerText, CharSequence title, CharSequence content) {
CharSequence notificationTicket = tickerText;
CharSequence notificationTitle = title;
CharSequence notificationContent = content;
long when = System.currentTimeMillis();
Intent intent = new Intent(context, MainActivity_.class);
intent.setFlags(
Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
intent.putExtra(OPEN_UPDATE_ACTIVITY_KEY, 1);
PendingIntent pendingIntent =
PendingIntent.getActivity(context, 0, intent, 0);
NotificationManager notificationManager =
(NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
Notification notification =
new Notification(iconID, notificationTicket, when);
notification.setLatestEventInfo(context, notificationTitle,
notificationContent, pendingIntent);
notificationManager.notify(NOTIFICATION_ID, notification);
}
public static boolean isUpdateStart(Intent intent) {
Bundle bundle = intent.getExtras();
boolean result = bundle != null &&
bundle.containsKey(OPEN_UPDATE_ACTIVITY_KEY);
if (result) {
bundle.remove(OPEN_UPDATE_ACTIVITY_KEY);
}
return result;
}
}
@EActivity(R.layout.activity_main)
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (OXAppUpdateHandler.isUpdateStart(getIntent())) {
startActivity(new Intent(this, UpdateActivity_.class));
}
}
}
最佳答案
我将 body 探出窗外,猜测您的问题出在这里:
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
您正在将 intent
传递给 getActivity()
并期望您将返回一个与您的 Intent匹配的
并包括您的附加功能。不幸的是,如果系统中已经存在与您的PendingIntent
Intent
匹配的PendingIntent
(没有考虑您的Intent
extras) 然后 getActivity()
将返回给你 PendingIntent
。
要查看这是否是问题所在,请尝试以下操作:
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
这表示如果系统中某处已经有一个 PendingIntent
与您的 Intent
相匹配,它应该用您的 intent
参数。
关于android - Intent.getExtras() 总是返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14338579/