使用BroadcastReceiver创建通知

时间:2013-05-10 22:24:36

标签: android notifications broadcastreceiver

我尝试使用此代码创建通知:

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

这是我的Mainfest宣言:

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

我现在的问题是,警报已生成,但未显示通知。 BroadcastReceiver在mainfest文件中声明,没有编译器或运行时错误。

我的第二个问题是setLatestEventInfonew Notification Contructor已弃用。我可以用什么而不是它?

3 个答案:

答案 0 :(得分:9)

我认为你需要使用

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

而不是getService

答案 1 :(得分:8)

你可以使用

Intent switchIntent = new Intent(BROADCAST_ACTION);

而不是使用

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

此处BROADCAST_ACTION是您在清单

中定义的操作
<receiver android:name=".MyNotification " android:enabled="true" >
    <intent-filter>
        <action android:name="your package.ANY_NAME" />
    </intent-filter>
</receiver>

您可以使用该操作名称

来捕获它
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
        }
}}

答案 2 :(得分:3)

您现在使用Notification.Builder构建通知,待处理的意图需要PendingIntent.getBroadcast()