Why i am not able to create the Notification in OnReceiver of BroadcastReceiver?

≡放荡痞女 提交于 2019-12-08 09:06:24

问题


I am going to create the notification and want to show it on the onReceiver of the BroadcastReceiver. But i am not able to do it. why ? The code for my class is:

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);
}

}

Give Solution for it. Thanks.


回答1:


Have you seen this: startActivity() from BroadcastReceiver

It doesn't look like you are using Context.registerReceiver() so you would have to statically add your receiver to the manifest, if you haven't already:

make sure you have the following in your manifest

<receiver android:name=".AlarmNotificationReceiver">
    <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
    </intent-filter>
</receiver>

Above, PHONE_STATE is just an example of an intent that may be used in conjuntion with the BroadcastReceiver

More reference: http://thinkandroid.wordpress.com/2010/02/02/custom-intents-and-broadcasting-with-receivers/

Hope that helps!



来源:https://stackoverflow.com/questions/8623208/why-i-am-not-able-to-create-the-notification-in-onreceiver-of-broadcastreceiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!