IntentService+BroadcastReceiver 实现定时任务

效果图:IntentService+BroadcastReceiver 实现定时任务
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
上一篇:Winfrom 基于TCP的Socket 编程


下一篇:zabbix邮件报警功能的验证