我终于自己弄明白了.我使用了服务和报警管理器的组合.每次我想处理强制关闭场景时,我都会启动一个运行无限循环的服务.这个循环每隔15秒就会迭代一次.在循环中,我设置了一个距离当前时间20秒的警报.现在,如果循环的下一次迭代发生,则更新警报并在新的当前时间之后重置为20秒.这样,只有当用户没有通过调用stopService()方法销毁服务时,才会触发警报.

public class MyIntentService extends IntentService {

public MyIntentService() {

super("My IntentService");

}

private boolean stopped = false;

private Thread runningThread;

private static MyIntentService mInstance;

@Override

public void onCreate() {

super.onCreate();

mInstance = MyIntentService.this;

}

@Override

public int onStartCommand(@Nullable Intent intent, int flags, int startId) {

return super.onStartCommand(intent, flags, startId);

}

@Override

protected void onHandleIntent(Intent intent) {

stopped = false;

runningThread = Thread.currentThread();

while(!this.stopped) {

Intent intent = new Intent("Your_Custom_Broadcast_Action");

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

PendingIntent broadcastIntent = PendingIntent.getBroadcast(WifiService.this, CLEAN_UP_ALARM_REQUEST_CODE,

intent, PendingIntent.FLAG_UPDATE_CURRENT);

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 20000, broadcastIntent);

} else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 20000, broadcastIntent);

} else {

alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 20000, broadcastIntent);

}

try {

Thread.sleep(15000);

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

@Override

public void onDestroy() {

super.onDestroy();

mInstance = null;

if (runningThread != null) {

runningThread.interrupt();

}

}

public void stopService() {

AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

PendingIntent broadcastIntent = PendingIntent.getBroadcast(WifiService.this, CLEAN_UP_ALARM_REQUEST_CODE,

intent, PendingIntent.FLAG_UPDATE_CURRENT);

alarmManager.cancel(broadcastIntent);

stopped = true;

if (runningThread != null)

runningThread.interrupt();

}

public static MyIntentService getActiveInstance() {

return mInstance;

}

}

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐