如何创建即使在手机重启后也能始终运行的通知?

时间:2017-08-10 04:54:15

标签: android firebase-realtime-database notifications broadcastreceiver bootcompleted

我在MainActivity 的方法 setAlarm()中设置了一个警报管理器,其中包含来自firebase数据库的日期,并根据该日期设置警报。当我尝试运行它时,这是非常好的。但是当我在闹钟响起之前尝试重新启动手机时,没有发生任何事情。

我也尝试创建一个引用服务的Receiver。从这个服务 onHandleIntent(Intent intent),我调用 MainActivity.setAlarm()。此外,我已经在Android清单中添加了一个权限启动完成。之后,我尝试重新启动手机,当我的手机完成启动时,该应用已强行关闭。我认为它停止了因为我在一个活动类中调用了一个方法。

这是我的闹钟接收器

public class AlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
    Intent notificationIntent = new Intent(context, BabyListActivity.class);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
    stackBuilder.addParentStack(BabyListActivity.class);
    stackBuilder.addNextIntent(notificationIntent);

    PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    Notification notification1 = builder.setContentTitle("1")
            .setContentText("New Notification From Demo App..")
            .setTicker("New Message Alert!")
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentIntent(pendingIntent).build();

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notification1);
}

这是我的startAlarm()方法

public static void startAlarm(Context context){
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
    notificationIntent.addCategory("android.intent.category.DEFAULT");

    PendingIntent broadcast = PendingIntent.getBroadcast(context, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 2017);
    cal.set(Calendar.MONTH, 8-1);
    cal.set(Calendar.DAY_OF_MONTH, 10);
    cal.set(Calendar.HOUR_OF_DAY, 10);
    cal.set(Calendar.MINUTE, 15);
    cal.set(Calendar.SECOND, 4);

    alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);
}

这是我的 BootAlarmReceiver

public class BootAlarmReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {

    if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {

        // It is better to reset alarms using Background IntentService
        Intent i = new Intent(context, BootService.class);
        ComponentName service = context.startService(i);

        if (null == service) {
            // something really wrong here
            Log.e(TAG, "Could not start service ");
        }
        else {
            Log.e(TAG, "Successfully started service ");
        }

    } else {
        Log.e(TAG, "Received unexpected intent " + intent.toString());
    }
}

这是我的启动服务

public class BootService extends Service {


public BootService() {
    super("BootService");
}

@Override
public void onCreate() {
    MainActivity.startAlarm(this);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_NOT_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
    return null;
}

}

这是我的 android清单

<receiver android:name=".AlarmReceiver">
        <intent-filter>
            <action android:name="android.media.action.DISPLAY_NOTIFICATION"></action>
            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

    <service android:name=".BootService"/>

    <receiver android:name=".BootAlarmReceiver" android:enabled="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>

有人能告诉我如何解决这个问题吗?感谢...

1 个答案:

答案 0 :(得分:1)

我认为至少有两个错误。首先,你永远不会新建一个Activity类,它应该由android框架管理,如果你只是想调用它中的一些方法,你最好将方法提取到实用程序类中,或者只是将方法更改为静态,不推荐。其次,onHandleIntent方法将在后台线程中运行,您不能调用应该在主线程上运行的方法。

因此,在我看来,对于测试,您可以在MainActivity中使startAlarm()方法为静态而BootService扩展服务而不是IntentService,进行这些更改并重试。

更改setAlarm()方法,如下所示:

public static void startAlarm(Context context){
    AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    Intent notificationIntent = new Intent("android.media.action.DISPLAY_NOTIFICATION");
    notificationIntent.addCategory("android.intent.category.DEFAULT");

    PendingIntent broadcast = PendingIntent.getBroadcast(context, 100, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    Calendar cal = Calendar.getInstance();
    cal.set(Calendar.YEAR, 2017);
    cal.set(Calendar.MONTH, 8-1);
    cal.set(Calendar.DAY_OF_MONTH, 10);
    cal.set(Calendar.HOUR_OF_DAY, 11);
    cal.set(Calendar.MINUTE, 40);
    cal.set(Calendar.SECOND, 00);

    alarmManager.setExact(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), broadcast);
}

像这样更改你的BootAlarmReceiver:

public class BootService extends Service {


    @Override
    public void onCreate() {
        MainActivity.startAlarm(this);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

再试一次!