Abh*_*hek 9 android android-intent android-notifications
是否可以通知广播接收器?
我试过这段代码,但它不起作用.
创建通知但是当我点击它时没有任何反应.
注意:当我将notificationIntent更改为从MyBroadcastReceiver.class指向活动(如MainActivity.class)时,它可以正常工作.
通知创建:
NotificationManager notificationManager = (NotificationManager) context.getSystemService(
Context.NOTIFICATION_SERVICE);
int notificationIconId = XXXXXX
Notification notification = new Notification(
notificationIconId,
XXXXXX,
System.currentTimeMillis()
);
CharSequence contentTitle = XXXXXXX
CharSequence contentText = XXXXXX
Intent notificationIntent = new Intent(context,MyBroadcastReceiver.class);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
notificationManager.notify(1,notification);
Run Code Online (Sandbox Code Playgroud)
这是BroadcastReceiver
public static class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
/*
*/
}
}
Run Code Online (Sandbox Code Playgroud)
在AndroidManifest.xml中
<receiver android:name=".MyBroadcastReceiver" />
Run Code Online (Sandbox Code Playgroud)
Squ*_*onk 33
从你的代码......
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
Run Code Online (Sandbox Code Playgroud)
在创建PendingIntent目标a时BroadcastReceiver,您必须使用getBroadcast(...)而不是getActivity(...).
请参阅PendingIntent.getBroadcast(Context context,int requestCode,Intent intent,int flags)
另外,不要创建Intent这样的...
Intent notificationIntent = new Intent(context,MyBroadcastReceiver.class);
Run Code Online (Sandbox Code Playgroud)
这是一个明确的Intent,它针对特定的类(通常用于启动特定的Activity类).
而是Intent用'动作' 创建'广播' ,例如......
Intent notificationIntent = new Intent(MyApp.ACTION_DO_SOMETHING);
Run Code Online (Sandbox Code Playgroud)
您还需要为清单<intent-filter>的<receiver android:name=".MyBroadcastReceiver" />部分指定一个部分.
| 归档时间: |
|
| 查看次数: |
8856 次 |
| 最近记录: |