如果重启设备,请启动AlarmManager

时间:2013-07-16 10:09:07

标签: android restart android-alarms reboot

在我的应用中,我希望每天使用AlarmManager在特定时间运行一些代码。在android documentation我发现了这个:

  

当设备处于睡眠状态时,会保留已注册的警报,但如果关闭并重新启动,则会被清除。

这就是问题所在。即使用户重新启动手机,我也想运行代码。如果用户重新启动手机,他当前必须重新启动我的应用以再次启动闹钟。我怎么能阻止这个?我应该使用更好的机制吗?

3 个答案:

答案 0 :(得分:33)

使用以下代码创建启动接收器:

public class BootBroadcastReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context pContext, Intent intent) {
        // Do your work related to alarm manager
    }
}

在您的清单中,注册此广播接收器:

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

不要忘记在AndroidManifest.xml中添加权限:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

答案 1 :(得分:7)

使用可以在设备启动时使用广播接收器创建服务

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

许可:

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

答案 2 :(得分:4)

您需要在清单中添加启动接收器,如此

<application ...  >

    <receiver android:name=".OnBootReceiver" >
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <uses-permission android:name="android.permission.WAKE_LOCK" />
        </intent-filter>
    </receiver>
</application>

然后像这样创建启动接收器类......

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class OnBootReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context ctxt, Intent intent) {
AlarmHelper.setAlarm(ctxt);
}
}

我的警报帮助程序类是一个简单的白天启动警报......

public class AlarmHelper {

public static void testAlarm(Context context) {
Calendar when = Calendar.getInstance();
when.add(Calendar.SECOND, 10);
setAlarm(context, when);    
}

public static void setAlarm(Context context) {
Calendar when = Calendar.getInstance();
when.add(Calendar.DAY_OF_YEAR, 1);
when.set(Calendar.HOUR_OF_DAY, 0);
when.set(Calendar.MINUTE, 0);
when.set(Calendar.SECOND, 0);
setAlarm(context, when);
}

    @SuppressLint("SimpleDateFormat")
private static void setAlarm(Context context, Calendar when) {

SharedPreferences prefs = PreferenceManager
.getDefaultSharedPreferences(context.getApplicationContext());

Boolean showNotifications = prefs.getBoolean("PREF_SHOW_NOTIFICATIONS",
false);

if (showNotifications) {    
AlarmManager am = (AlarmManager) context
.getSystemService(Context.ALARM_SERVICE);

am.setRepeating(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), AlarmManager.INTERVAL_DAY, getPendingIntent(context.getApplicationContext()));

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

Log.i(TAG, "Alarm set " + sdf.format(when.getTime()));
}
}