一、创建ServiceDemo继承IntentService
public class ServiceDemo extends IntentService {
private static final String TAG = "Service";
private static final int INTERVAL = 1000 * 15; // 15s
private static final int REQUEST_CODE = 0;
private static final int FLAG = 0;
public ServiceDemo() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i(TAG, "Receive an intent: " + intent);
if (NetUtils.isNetConnected(getApplicationContext())) {
Log.i(TAG, "网络已连接!");
} else {
Log.i(TAG, "网络未连接!");
}
}
/**
* 设置后台定时服务
*
* @param context 发送intent的Context
* @param isOn 是否启动服务
*/
public static void setServiceAlarm(Context context, boolean isOn) {
Intent i = new Intent(context, ServiceDemo.class);
PendingIntent pi = PendingIntent.getService(context, REQUEST_CODE, i, FLAG);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
if (isOn) {
am.setRepeating(AlarmManager.RTC, System.currentTimeMillis(), INTERVAL, pi);
Log.i(TAG, "后台服务已开启");
} else {
am.cancel(pi);
pi.cancel();
Log.i(TAG, "后台服务已关闭");
}
}
二、在Activity中开始和停止定时服务
mOpenServiceBtn = (Button) findViewById(R.id.open_service_btn);
mOpenServiceBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ServiceDemo.setServiceAlarm(ServiceActivity.this, true);
}
});
mStopServiceBtn = (Button) findViewById(R.id.stop_service_btn);
mStopServiceBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
ServiceDemo.setServiceAlarm(ServiceActivity.this, false);
}
});