Create Notification with BroadcastReceiver

人走茶凉 提交于 2019-12-04 02:46:55

问题


I tried to create a Notification with this Code:

private void setNotificationAlarm(Context context) 
{
    Intent intent = new Intent(getApplicationContext() , MyNotification.class);
    PendingIntent pendingIntent  = PendingIntent.getBroadcast(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);  

    AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
    am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 , pendingIntent);
    Log.d("ME", "Alarm started");
}

public class MyNotification extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        Log.d("ME", "Notification started");

        NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle("My notification")
            .setContentText("Hello World!");

        NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.notify(1, mBuilder.build());
    }
}

And here my Mainfest declaration:

<receiver
    android:name=".MyNotification"
    android:enabled="true"
    android:exported="false" >
</receiver>

My problem now is, that the alarm is generated but the Notification isn't displayed. The BroadcastReceiver is declared in the mainfest file and there are no compiler or runtime errors.

My second problem is that setLatestEventInfo and new Notification Contructor are deprecated. What can I use instead of it?


回答1:


I think you need to use

PendingIntent.getBroadcast (Context context, int requestCode, Intent intent, int flags)

instead of getService




回答2:


you can use

Intent switchIntent = new Intent(BROADCAST_ACTION);

instead of using

Intent intent = new Intent(getApplicationContext() , MyNotification.class);

in here BROADCAST_ACTION is action that you are defining in manifest

<receiver android:name=".MyNotification " android:enabled="true" >
    <intent-filter>
        <action android:name="your package.ANY_NAME" />
    </intent-filter>
</receiver>

you can catch it by using that action name

public class MyNotification extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
    String act = "your package.ANY_NAME";
        if(intent.getAction().equals(act)){

            //your code here
        }
}}



回答3:


You use Notification.Builder to build the notification now and the pending intent needs to be PendingIntent.getBroadcast()



来源:https://stackoverflow.com/questions/16491631/create-notification-with-broadcastreceiver

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