Android 如何将参数从通知点击发送到活动?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1198558/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to send parameters from a notification-click to an activity?
提问by Vidar Vestnes
I can find a way to send parameters to my activity from my notification.
我可以找到一种方法从我的通知中将参数发送到我的活动。
I have a service that creates a notification. When the user clicks on the notification I want to open my main activity with some special parameters. E.g an item id, so my activity can load and present a special item detail view. More specific, I'm downloading a file, and when the file is downloaded I want the notification to have an intent that when clicked it opens my activity in a special mode. I have tried to use putExtra
on my intent, but cant seem to extract it, so I think I'm doing it wrong.
我有一个创建通知的服务。当用户点击通知时,我想用一些特殊参数打开我的主要活动。例如,项目 ID,因此我的活动可以加载并呈现特殊的项目详细信息视图。更具体地说,我正在下载一个文件,当下载文件时,我希望通知有一个意图,即在单击时它会以特殊模式打开我的活动。我试图按照putExtra
我的意图使用,但似乎无法提取它,所以我认为我做错了。
Code from my service that creates the Notification:
我的服务中创建通知的代码:
// construct the Notification object.
final Notification notif = new Notification(R.drawable.icon, tickerText, System.currentTimeMillis());
final RemoteViews contentView = new RemoteViews(context.getPackageName(), R.layout.custom_notification_layout);
contentView.setImageViewResource(R.id.image, R.drawable.icon);
contentView.setTextViewText(R.id.text, tickerText);
contentView.setProgressBar(R.id.progress,100,0, false);
notif.contentView = contentView;
Intent notificationIntent = new Intent(context, Main.class);
notificationIntent.putExtra("item_id", "1001"); // <-- HERE I PUT THE EXTRA VALUE
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notif.contentIntent = contentIntent;
nm.notify(id, notif);
Code from my Activity that tries to fetch the extra parameter from the notification:
我的活动中尝试从通知中获取额外参数的代码:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Bundle extras = getIntent().getExtras();
if(extras != null){
Log.i( "dd","Extra:" + extras.getString("item_id") );
}
The extras is always null and I never gets anything into my log.
extras 总是空的,我从来没有在我的日志中得到任何东西。
Btw... the onCreate
is only run when my activity starts, if my activity is already started I also want to collect the extras and present my activity according to the item_id I receive.
顺便说一句...onCreate
仅在我的活动开始时运行,如果我的活动已经开始,我还想收集额外内容并根据我收到的 item_id 展示我的活动。
Any ideas?
有任何想法吗?
回答by Lucas S.
Take a look at this guide (creating a notification) and to samples ApiDemos "StatusBarNotifications" and "NotificationDisplay".
看看本指南(创建通知)和示例 ApiDemos“StatusBarNotifications”和“NotificationDisplay”。
For managing if the activity is already running you have two ways:
要管理活动是否已经在运行,您有两种方法:
Add FLAG_ACTIVITY_SINGLE_TOPflag to the Intent when launching the activity, and then in the activity class implement onNewIntent(Intent intent)event handler, that way you can access the new intent that was called for the activity (which is not the same as just calling getIntent(), this will always return the first Intent that launched your activity.
Same as number one, but instead of adding a flag to the Intent you must add "singleTop"in your activity AndroidManifest.xml.
启动活动时在Intent中添加 FLAG_ACTIVITY_SINGLE_TOP标志,然后在活动类中实现 onNewIntent(Intent intent)事件处理程序,这样就可以访问为该活动调用的新Intent(这与只调用getIntent不同(),这将始终返回启动您的活动的第一个意图。
与第一项相同,但不是向 Intent 添加标志,而是必须在活动 AndroidManifest.xml 中添加“singleTop”。
If you use intent extras, remeber to call PendingIntent.getActivity()
with the flag PendingIntent.FLAG_UPDATE_CURRENT
, otherwise the same extras will be reused for every notification.
如果您使用 Intent extras,请记住PendingIntent.getActivity()
使用 flag调用PendingIntent.FLAG_UPDATE_CURRENT
,否则每个通知都会重复使用相同的 extras。
回答by Muhammad Yousaf Sulahria
I had the similar problem my application displays message notifications. When there are multiple notifications and clicking each notification it displays that notification detail in a view message activity. I solved the problem of same extra parameters is being received in view message intent.
我的应用程序显示消息通知时遇到了类似的问题。当有多个通知并单击每个通知时,它会在查看消息活动中显示该通知详细信息。我解决了在视图消息意图中收到相同额外参数的问题。
Here is the code which fixed this. Code for creating the notification Intent.
这是修复此问题的代码。用于创建通知意图的代码。
Intent notificationIntent = new Intent(getApplicationContext(), viewmessage.class);
notificationIntent.putExtra("NotificationMessage", notificationMessage);
notificationIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(getApplicationContext(),notificationIndex,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingNotificationIntent);
Code for view Message Activity.
查看消息活动的代码。
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
onNewIntent(getIntent());
}
@Override
public void onNewIntent(Intent intent){
Bundle extras = intent.getExtras();
if(extras != null){
if(extras.containsKey("NotificationMessage"))
{
setContentView(R.layout.viewmain);
// extract the extra-data in the Notification
String msg = extras.getString("NotificationMessage");
txtView = (TextView) findViewById(R.id.txtMessage);
txtView.setText(msg);
}
}
}
回答by pinaise
Maybe a bit late, but: instead of this:
也许有点晚了,但是:而不是这样:
public void onNewIntent(Intent intent){
Bundle extras = intent.getExtras();
Log.i( "dbg","onNewIntent");
if(extras != null){
Log.i( "dbg", "Extra6 bool: "+ extras.containsKey("net.dbg.android.fjol"));
Log.i( "dbg", "Extra6 val : "+ extras.getString("net.dbg.android.fjol"));
}
mTabsController.setActiveTab(TabsController.TAB_DOWNLOADS);
}
Use this:
用这个:
Bundle extras = getIntent().getExtras();
if(extras !=null) {
String value = extras.getString("keyName");
}
回答by jamchen
Encounter same issue here. I resolve it by using different request code, use same id as notification, while creating PendingIntent. but still don't know why this should be done.
在这里遇到同样的问题。我通过使用不同的请求代码来解决它,使用与通知相同的 id,同时创建 PendingIntent。但仍然不知道为什么要这样做。
PendingIntent contentIntent = PendingIntent.getActivity(context, **id**, notificationIntent, 0);
notif.contentIntent = contentIntent;
nm.notify(**id**, notif);
回答by Vidar Vestnes
After reading some email-lists and other forums i found that the trick seems to add som unique data to the intent.
在阅读了一些电子邮件列表和其他论坛后,我发现这个技巧似乎为意图添加了一些独特的数据。
like this:
像这样:
Intent notificationIntent = new Intent(Main.this, Main.class);
notificationIntent.putExtra("sport_id", "sport"+id);
notificationIntent.putExtra("game_url", "gameURL"+id);
notificationIntent.setData((Uri.parse("foobar://"+SystemClock.elapsedRealtime())));
I dont understand why this needs to be done, It got something to do with the intent cant be identified only by its extras...
我不明白为什么需要这样做,它与无法仅通过其附加内容识别的意图有关......
回答by Dheeraj Sachan
I tried everything but nothing worked.
我尝试了一切,但没有任何效果。
eventually came up with following solution.
最终想出了以下解决方案。
1- in manifest add for the activity android:launchMode="singleTop"
1- 在清单中添加活动 android:launchMode="singleTop"
2- while making pending intent do the following, use bundle instead of directly using intent.putString() or intent.putInt()
2- 在使待定意图执行以下操作时,使用 bundle 而不是直接使用 intent.putString() 或 intent.putInt()
Intent notificationIntent = new Intent(getApplicationContext(), CourseActivity.class);
Bundle bundle = new Bundle();
bundle.putString(Constants.EXAM_ID,String.valueOf(lectureDownloadStatus.getExamId()));
bundle.putInt(Constants.COURSE_ID,(int)lectureDownloadStatus.getCourseId());
bundle.putString(Constants.IMAGE_URL,lectureDownloadStatus.getImageUrl());
notificationIntent.putExtras(bundle);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP |
Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(),
new Random().nextInt(), notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
回答by Miguel Jesus
AndroidManifest.xml
AndroidManifest.xml
Include launchMode="singleTop"
包括 launchMode="singleTop"
<activity android:name=".MessagesDetailsActivity"
android:launchMode="singleTop"
android:excludeFromRecents="true"
/>
SMSReceiver.java
短信接收器.java
Set the flags for the Intent and PendingIntent
为 Intent 和 PendingIntent 设置标志
Intent intent = new Intent(context, MessagesDetailsActivity.class);
intent.putExtra("smsMsg", smsObject.getMsg());
intent.putExtra("smsAddress", smsObject.getAddress());
intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, notification_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
MessageDetailsActivity.java
消息详细信息Activity.java
onResume() - gets called everytime, load the extras.
onResume() - 每次都被调用,加载额外内容。
Intent intent = getIntent();
String extraAddress = intent.getStringExtra("smsAddress");
String extraBody = intent.getStringExtra("smsMsg");
Hope it helps, it was based on other answers here on stackoverflow, but this is the most updated that worked for me.
希望它有所帮助,它基于 stackoverflow 上的其他答案,但这是对我有用的最新版本。
回答by David Hackro
It's easy,this is my solution using objects!
很简单,这是我使用对象的解决方案!
My POJO
我的POJO
public class Person implements Serializable{
private String name;
private int age;
//get & set
}
Method Notification
方法通知
Person person = new Person();
person.setName("david hackro");
person.setAge(10);
Intent notificationIntent = new Intent(this, Person.class);
notificationIntent.putExtra("person",person);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.notification_icon)
.setAutoCancel(true)
.setColor(getResources().getColor(R.color.ColorTipografiaAdeudos))
.setPriority(2)
.setLargeIcon(bm)
.setTicker(fotomulta.getTitle())
.setContentText(fotomulta.getMessage())
.setContentIntent(PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT))
.setWhen(System.currentTimeMillis())
.setContentTitle(fotomulta.getTicketText())
.setDefaults(Notification.DEFAULT_ALL);
New Activity
新活动
private Person person;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_notification_push);
person = (Person) getIntent().getSerializableExtra("person");
}
Good Luck!!
祝你好运!!
回答by mohit
After doing some search i got solution from android developer guide
在做了一些搜索之后,我从 android 开发者指南中得到了解决方案
PendingIntent contentIntent ;
Intent intent = new Intent(this,TestActivity.class);
intent.putExtra("extra","Test");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(ArticleDetailedActivity.class);
contentIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
To Get Intent extra value in Test Activity class you need to write following code :
要在测试活动类中获得 Intent 额外价值,您需要编写以下代码:
Intent intent = getIntent();
String extra = intent.getStringExtra("extra") ;
回答by Carlos Espinoza
In your notification implementation, use a code like this:
在您的通知实现中,使用如下代码:
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
...
Intent intent = new Intent(this, ExampleActivity.class);
intent.putExtra("EXTRA_KEY", "value");
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
nBuilder.setContentIntent(pendingIntent);
...
To Get Intent extra values in the ExampleActivity, use the following code:
要在 ExampleActivity 中获取 Intent 额外值,请使用以下代码:
...
Intent intent = getIntent();
if(intent!=null) {
String extraKey = intent.getStringExtra("EXTRA_KEY");
}
...
VERY IMPORTANT NOTE:the Intent::putExtra()method is an Overloaded one. To get the extra key, you need to use Intent::get[Type]Extra()method.
非常重要注意:该意向:: putExtra()方法是一个重载一个。要获得额外的密钥,您需要使用Intent::get[Type]Extra()方法。
Note: NOTIFICATION_IDand NOTIFICATION_CHANNEL_IDare an constants declared in ExampleActivity
注意:NOTIFICATION_ID和NOTIFICATION_CHANNEL_ID是 ExampleActivity 中声明的常量