使用BroadcastReceiver创建通知

Cil*_*nco 17 notifications android 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());
    }
}
Run Code Online (Sandbox Code Playgroud)

在这里,我的Mainfest宣言:

<receiver
    android:name=".MyNotification"
    android:enabled="true"
    android:exported="false" >
</receiver>
Run Code Online (Sandbox Code Playgroud)

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

我的第二个问题是setLatestEventInfonew NotificationContructor已被弃用.我可以用什么代替呢?

Ash*_*ngi 9

我想你需要用

PendingIntent.getBroadcast (Context context, int requestCode, Intent intent, int flags)
Run Code Online (Sandbox Code Playgroud)

代替 getService

  • BroadcastReceivers 通常处理一些动作。定义您的广播接收器将使用的操作,然后将该操作添加到清单和意图中。更多详情[这里](http://www.vogella.com/articles/AndroidBroadcastReceiver/article.html) (2认同)

Kau*_*lva 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>
Run Code Online (Sandbox Code Playgroud)

你可以通过使用该动作名称来捕获它

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
        }
}}
Run Code Online (Sandbox Code Playgroud)