简体   繁体   English

android中的本地通知在设备重启时使用Alarmmanager

[英]Local Notification in android using Alarmmanager on Reboot of device

I have created a local notification and i have trigger it in mainactivity.我创建了一个本地通知,并在 mainactivity 中触发了它。

MainActivity code below:主活动代码如下:

import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.SystemClock;
import android.support.v4.app.NotificationCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {
    public static final String NOTIFICATION_CHANNEL_ID = "10001";
    private final static String default_notification_channel_id = "default";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //here i create and call the notification, it will trigger every 30 seconds or so
        scheduleNotification(getNotification("30 second delay"), 30000);
    }

    public void scheduleNotification(Notification notification, int delay) {
        //here is the intent which uses the MyNotificationPublisher.class
        Intent notificationIntent = new Intent(this, MyNotificationPublisher.class);

        notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION_ID, 1);
        notificationIntent.putExtra(MyNotificationPublisher.NOTIFICATION, notification);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        long futureInMillis = SystemClock.elapsedRealtime() + delay;
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        assert alarmManager != null;
        //here i am starting the alarm manager with setInexactRepeating to continuesly run the notification every 30 seconds
        alarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, futureInMillis, 3000 * 10, pendingIntent);;

    }

    public Notification getNotification(String content) {
        //here i setup the notification
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this, default_notification_channel_id);
        builder.setContentTitle("Scheduled Notification");
        builder.setContentText(content);
        builder.setSmallIcon(R.drawable.ic_launcher_foreground);
        builder.setAutoCancel(true);
        builder.setChannelId(NOTIFICATION_CHANNEL_ID);
        return builder.build();
    }
}

Below is the code of the MyNotificationPublisher class:下面是MyNotificationPublisher类的代码:

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import static app.tutorialspoint.com.notifyme.MainActivity.NOTIFICATION_CHANNEL_ID;

public class MyNotificationPublisher extends BroadcastReceiver {

    public static String NOTIFICATION_ID = "notification-id";
    public static String NOTIFICATION = "notification";
    public void onReceive(Context context, Intent intent) {
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification = intent.getParcelableExtra(NOTIFICATION);

        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            int importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel notificationChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", importance);
            assert notificationManager != null;
            notificationManager.createNotificationChannel(notificationChannel);
        }
        int id = intent.getIntExtra(NOTIFICATION_ID, 0);
        assert notificationManager != null;
        notificationManager.notify(id, notification);
    }
}

This is the manifest xml where the receiver .MyNotificationPublisher exists这是接收方.MyNotificationPublisher所在的清单 xml

<? xml version = "1.0" encoding = "utf-8" ?>
<manifest xmlns: android = "http://schemas.android.com/apk/res/android"
   package= "app.tutorialspoint.com.notifyme" >
   <uses-permission android :name = "android.permission.VIBRATE" />
   <application
      android :allowBackup = "true"
      android :icon = "@mipmap/ic_launcher"
      android :label = "@string/app_name"
      android :roundIcon = "@mipmap/ic_launcher_round"
      android :supportsRtl = "true"
      android :theme = "@style/AppTheme" >
      <activity android :name = ".MainActivity" >
         <intent-filter>
            <action android :name = "android.intent.action.MAIN" />
            <category android :name = "android.intent.category.LAUNCHER" />
         </intent-filter>
      </activity>
      <receiver android :name = ".MyNotificationPublisher" />
   </application>
</manifest>

The code is working and the notification is triggered every 30 seconds but i need to achieve the following.代码正在运行,并且每 30 秒触发一次通知,但我需要实现以下目标。

  1. I need to start showing this notification when the app closes by the user.当用户关闭应用程序时,我需要开始显示此通知。 Not while the app is running.不是在应用程序运行时。
  2. How do i make the notification to run again and again after the device reboots (i tried this page instructions https://developer.android.com/training/scheduling/alarms at section "Start an alarm when the device restarts" but i do not know how to start the alarm and notification run again because every time the device closes all active alarms are cancelled. I tried using "android.permission.RECEIVE_BOOT_COMPLETED" as i was instructed by the webpage at https://developer.android.com/training/scheduling/alarms and then calling the public void scheduleNotification (Notification notification , int delay) using MainActivity mActivity = new MainActivity(); mActivity.scheduleNotification(mActivity.getNotification( "30 second delay" ) , 30000 ); from the MyNotificationPublisher class but the app crashes. )如何在设备重新启动后使通知一次又一次地运行(我在“设备重新启动时启动警报”部分尝试了此页面说明https://developer.android.com/training/scheduling/alarms ,但我这样做了不知道如何启动警报和通知再次运行,因为每次设备关闭所有活动警报都会被取消。我尝试使用“android.permission.RECEIVE_BOOT_COMPLETED”,因为我是在https://developer.android.com 上的网页指示的/training/scheduling/alarms然后调用 public void scheduleNotification (Notification notification , int delay) 使用 MainActivity mActivity = new MainActivity(); mActivity.scheduleNotification(mActivity.getNotification( "30 second delay" ) , 30000 ); 从 MyNotificationPublisher类,但应用程序崩溃。)

Any thoughts or solutions?任何想法或解决方案?

you need to add intent-filter in the manifest file for your receiver.您需要在清单文件中为您的接收器添加意图过滤器。 Try the below code.试试下面的代码。

<receiver android :name = ".MyNotificationPublisher">
   <intent-filter> 
        <action android:name="android.intent.action.BOOT_COMPLETED"></action> 
   </intent-filter>
</receiver> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM