gpt4 book ai didi

android - AlarmManager 在关机时删除所有计划?

转载 作者:太空宇宙 更新时间:2023-11-03 11:40:50 27 4
gpt4 key购买 nike

我在特定时间设置了闹钟。如果手机关机闹钟会丢失?我已经关闭手机,重新启动,但闹钟没有在指定时间触发。

PendingIntent pendingIntent = PendingIntent.getBroadcast(
Global.a.getApplicationContext(), (int) cd.e.alarmTime, intent, 0);

AlarmManager alarmManager = (AlarmManager) Global.a.getSystemService(Activity.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC, cd.e.alarmTime, pendingIntent);

最佳答案

首先您需要创建一个 BroadcastReceiver 以在 BOOT_COMPLETE 上触发

public class BootReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent mServiceIntent = new Intent();
mServiceIntent
.setAction("com.crossfire.appname.service.BootService");
ComponentName service = context.startService(mServiceIntent);
if (null == service) {
// something really wrong here
Log.e(TAG, "Could not start service ");
}
} else {
Log.e(TAG, "Received unexpected intent " + intent.toString());
}
}
}

然后创建一个服务来重置你所有的闹钟:

public class BootService extends Service {

private final String TAG = "BootService";

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

@Override
public void onCreate() {
super.onCreate();
Trace.i(TAG, "created");
}

@Override
public void onStart(final Intent intent, final int startId) {
super.onStart(intent, startId);
Trace.i(TAG, "started");

LoadAlarmsFromDatabase();

}

private void LoadAlarmsFromDatabase() {
Cursor c = mDbHelper.getPendingAlarms();
if (c.moveToFirst()) {
do {

int id = c.getInt(mDbHelper.ID_COLUMN);
String time = c.getString(mDbHelper.TIME_COLUMN);
addNotification(id, time);
} while (c.moveToNext());
}
c.close();
}

private void addNotification(int apptId, String time) {
Trace.d(TAG, "addNotification " + apptId + ", " + time);
Intent intent = new Intent(BootService.this,
ApptBroadcastReceiver.class);

intent.putExtra("appt_id", Integer.toString(apptId));

PendingIntent mAlarmSender = PendingIntent.getBroadcast(
BootService.this, apptId, intent, 0);

long alarmTime = System.currentTimeMillis() + 60000;
Calendar c = null;

try {
c = CustomDateUtils.StringToCalendar(time);
alarmTime = c.getTimeInMillis();
} catch (ParseException e) {
Log.e(TAG, "ParseException");
}

AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, alarmTime, mAlarmSender);

}
}

最后,在 list 中添加权限和接收者

 <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<receiver android:name=".receiver.BootReceiver" android:enabled="true">
<intent-filter>
<action android:name ="android.intent.action.BOOT_COMPLETED"></action>
</intent-filter>
</receiver>

关于android - AlarmManager 在关机时删除所有计划?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9671174/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com