为啥我无法在 BroadcastReceiver 的 OnReceiver 中创建通知?
Posted
技术标签:
【中文标题】为啥我无法在 BroadcastReceiver 的 OnReceiver 中创建通知?【英文标题】:Why i am not able to create the Notification in OnReceiver of BroadcastReceiver?为什么我无法在 BroadcastReceiver 的 OnReceiver 中创建通知? 【发布时间】:2012-01-27 05:39:29 【问题描述】:我将创建通知并希望在 BroadcastReceiver 的 onReceiver 上显示它。但我做不到。为什么 ? 我的课的代码是:
public class AlarmNotificationReceiver extends BroadcastReceiver
//private Intent intent;
private NotificationManager notificationManager;
private Notification notification;
@Override
public void onReceive(Context context, Intent intent)
// TODO Auto-generated method stub
long value1 = intent.getLongExtra("param1", 0);
String value2 = intent.getStringExtra("param2");
Toast.makeText(context, "Hello! How r u ?", Toast.LENGTH_SHORT).show();
addTwoMonthNotification();
private void addTwoMonthNotification()
notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
int icon = R.drawable.icon;
CharSequence text = "Your amout is due on this date";
CharSequence contentTitle = "Tax Calculator App";
CharSequence contentText = "Your tax amount is due on the "+System.currentTimeMillis()+"";
long when = System.currentTimeMillis();
Intent intent = new Intent(this, NotificationViewer.class);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, 0);
notification = new Notification(icon,text,when);
long[] vibrate = 0,100,200,300;
notification.vibrate = vibrate;
notification.ledARGB = Color.RED;
notification.ledOffMS = 300;
notification.ledOnMS = 300;
notification.defaults |= Notification.DEFAULT_LIGHTS;
//notification.flags |= Notification.FLAG_SHOW_LIGHTS;
notification.setLatestEventInfo(this, contentTitle, contentText, contentIntent);
notificationManager.notify(NotificationConstants.NOTIFICATION_ID, notification);
为它提供解决方案。 谢谢。
【问题讨论】:
【参考方案1】:你见过这样的: startActivity() from BroadcastReceiver
您似乎没有使用Context.registerReceiver()
,因此您必须将您的接收器静态添加到清单中,如果您还没有:
确保清单中有以下内容
<receiver android:name=".AlarmNotificationReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
在上面,PHONE_STATE
只是一个意图示例,可以与BroadcastReceiver
结合使用
更多参考:http://thinkandroid.wordpress.com/2010/02/02/custom-intents-and-broadcasting-with-receivers/
希望有帮助!
【讨论】:
以上是关于为啥我无法在 BroadcastReceiver 的 OnReceiver 中创建通知?的主要内容,如果未能解决你的问题,请参考以下文章
为啥 BroadcastReceiver 需要一个默认构造函数?
为啥Android要使用各种BroadcastReceiver
BroadcastReceiver - 无法从关闭或后台应用程序启动活动
为啥 proguard 处理 AndroidManifest.xml