效果图:
AlramIntentService
package com.example.admin.water;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
public class AlramIntentService extends IntentService {
public AlramIntentService() {
super("AlramIntentService");
}
@Override
protected void onHandleIntent( Intent intent) {
new Thread(new Runnable() {
@Override
public void run() {
NotificationUtils.remindUserBecauseCharging(AlramIntentService.this);
}
}).start();
AlarmManager alarmManager=(AlarmManager)getSystemService(Context.ALARM_SERVICE);
long triggerAtTime=SystemClock.elapsedRealtime()+60*1000;
Intent i=new Intent(this,AlarmReceiver.class);
PendingIntent pendingIntent=PendingIntent.getBroadcast(this,0,i,0);
alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP,triggerAtTime,pendingIntent);
}
}
AlarmReceiver
package com.example.admin.water;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
intent=new Intent(context,AlramIntentService.class);
context.startService(intent);
}
}
最后在MainActivity加上
Intent i=new Intent(this,AlramIntentService.class);
startService(i);
github项目源码:https://github.com/NeoWu55/Android-Water