在onReceive广播接收器中调用通知

时间:2016-12-10 16:35:16

标签: java android notifications

    public class MyBroadcaseciver extends BroadcastReceiver {

    MediaPlayer mymedia;
    @Override
    public void onReceive(Context context, Intent intent) {
        mymedia=MediaPlayer.create(context,R.raw.alarm);
        mymedia.start();
        Toast.makeText(context, "Alarm....", Toast.LENGTH_LONG).show();



    }



}

上面的代码是我的广播接收器,它在发射时播放一首歌。这是按预期工作的,但我希望在这里调用推送通知,并且我的通知也不在此处。

Notification.Builder bulider = new Notification.Builder(this)
                .setContentTitle("Rainfall Alert")
                .setContentText("Todays Rain");
        Notification notification = bulider.build();
        NotificationManager manager = (NotificationManager)
                getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(0,notification);

非常感谢帮助。

2 个答案:

答案 0 :(得分:0)

public void sendNotification(String title, String body, Intent intent,int pushid) {

    Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
            .setSmallIcon(R.mipmap.ic_launcher)
            .setContentTitle(title)
            .setStyle(new NotificationCompat.BigTextStyle()
                    .bigText(body))
            .setContentText(body)
            .setAutoCancel(true)
            .setSound(defaultSoundUri);

    if(intent!=null) {
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent,
                PendingIntent.FLAG_ONE_SHOT);
        notificationBuilder.setContentIntent(pendingIntent);
    }


    NotificationManager notificationManager =
            (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0, notificationBuilder.build());
}

在onrecive方法中调用此函数

Intent intent = new Intent(context, Mainscreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
sendNotification("title","message", intent, 0);

答案 1 :(得分:0)

/** @var int $sum This is a sum. */
$sum = 0;