如果从通知中打开,我正试图让我的活动做一些事情。在我的BroadcastReceiver中,我有这个:
Bundle extras = intent.getExtras();
Intent startServiceIntent = new Intent(context, MainActivity.class);
startServiceIntent.putExtra("fromNotification", true);
startServiceIntent.putExtras(extras);
context.startService(startServiceIntent);
...
PendingIntent myIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0);
在我的主要活动中,我试着称之为:
Bundle extras = getIntent().getExtras();
if(extras != null) {
if(extras.getBoolean("fromNotification")) {
Toast.makeText(this, "from notification", Toast.LENGTH_LONG).show();
}
} else {
Toast.makeText(this, "extras = " + extras, Toast.LENGTH_LONG).show();
}
问题是else
语句总是触发,说extras
为空。
我在这里缺少什么?
更新:
BroadcastReceiver
Intent startServiceIntent = new Intent(context, MainActivity.class);
startServiceIntent.putExtra("fromNotification", true);
context.startService(startServiceIntent);
MainActivity
boolean fromNotification = getIntent().getBooleanExtra("fromNotification", false);
if (fromNotification) {
Toast.makeText(this, "from notification", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(this, fromNotification + " elsewhere", Toast.LENGTH_LONG).show();
}
答案 0 :(得分:0)
您可以根据自己的意图设置操作并为其注册接收器,以便在启动时,您的广播接收器(显然)会收到该消息并确认它是正确的,您可以这样检查:
if(receivedIntent.getAction().equals("yourAction"))//do sth
要为您的意图添加操作,请使用以下代码:
PendingIntent myIntent = PendingIntent.getActivity(context, 1000, new Intent(context, MainActivity.class).setAction("yourAction"), 0);
你也想用1000代替请求代码而不是0,因为在android 4.3中很多用户都遇到了打开通知的问题......所以这件事就解决了。
你的else语句总是触发,因为你得到的额外内容是null,这是因为你发送意图的代码是错误的... 使用此:
Intent startServiceIntent = new Intent(context, MainActivity.class);
startServiceIntent.putExtra("fromNotification", true);
context.startService(startServiceIntent);
答案 1 :(得分:0)
您的代码中有一点混淆。您正在创建和额外的包,但是您要将布尔值分配给额外的包。
Bundle extras = intent.getExtras();
Intent startServiceIntent = new Intent(context, MainActivity.class);
startServiceIntent.putExtra("fromNotification", true);
startServiceIntent.putExtras(extras);
context.startService(startServiceIntent);
将其更改为:
Intent startServiceIntent = new Intent(context, MainActivity.class);
Bundle extras = startServiceIntent.getExtras();
extras.putBoolean("fromNotification", true);
startServiceIntent.putExtras(extras);
context.startService(startServiceIntent);
更新
就我个人而言,我没有使用Bundle方式,我只使用了intent.putExtra()方法,但是我需要改变它的方式:
boolean fromNotification = getIntent().getBooleanExtra("fromNotification", false);
if (fromNoticiation) {
// I was called by notification
} else {
// started from somewhere else
}