最近用timer用起来不是那么理想,就想了其他的方法。网上找了些资料,整理了下,写个demo。和大家分享下。感谢网上的大神,没有他们我也不能这么快写出来。逻辑“后台Service中开启轮询,定时发送广播。在广播中做需要做的任务”。
项目下载地址:http://download.csdn.net/detail/hello_12413/8649553
项目 UTF-8编码
项目结构如下:
工具类,启动和停止轮询服务:
package com.example.servicedemo.utils;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.SystemClock;
public class PollingUtils {
// 开启轮询服务
public static void startPollingService(Context context, int seconds, Class<?> cls, String action) {
// 获取AlarmManager系统服务
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
// 包装需要执行Service的Intent
Intent intent = new Intent(context, cls);
intent.setAction(action);
// PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, 0);
// 触发服务的起始时间
long triggerAtTime = SystemClock.elapsedRealtime();
// 使用AlarmManger的setRepeating方法设置定期执行的时间间隔(seconds秒)和需要执行的Service
manager.setRepeating(AlarmManager.ELAPSED_REALTIME , triggerAtTime, seconds * 1000, pendingIntent);
}
// 停止轮询服务
public static void stopPollingService(Context context, Class<?> cls, String action) {
AlarmManager manager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Intent intent = new Intent(context, cls);
intent.setAction(action);
PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// 取消正在执行的服务
manager.cancel(pendingIntent);
}
}
TimeReceiver.java 广播接收器
package com.example.servicedemo.broadcase;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;
public class TimeReceiver extends BroadcastReceiver {
public static final String ACTION = "com.example.servicedemo.TimeReceiver";
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ACTION.equals(action)) {
Log.e(getClass().getSimpleName(),"============TimeReceiver");
Toast.makeText(context, "定时任务", Toast.LENGTH_SHORT).show();
}
}
}
后台服务:
package com.example.servicedemo.service;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.ComponentName;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import com.example.servicedemo.R;
import com.example.servicedemo.broadcase.MyBroadcastReciver;
import com.example.servicedemo.broadcase.TimeReceiver;
import com.example.servicedemo.utils.PollingUtils;
/**
* @project ServiceDemo
* @ClassName BackGroundService.java
* @Description
* @author xugang
* @date 2015-4-30 下午2:26:13
*/
public class BackGroundService extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
int time = intent.getIntExtra("time", 1);
PollingUtils.startPollingService(this, time * 60, TimeReceiver.class, TimeReceiver.ACTION);
showNotification("定是时间:" + time + "分钟");
registerMyReceiver();
return START_STICKY;
}
@SuppressWarnings("deprecation")
public void showNotification(String content) {
Notification notification = new Notification(R.drawable.ic_launcher, getString(R.string.app_name), System.currentTimeMillis());
PendingIntent pendingintent = PendingIntent.getActivity(this, 0, getIntent(), 0);
notification.setLatestEventInfo(this, getString(R.string.app_name), content, pendingintent);
startForeground(1000, notification);
}
public Intent getIntent() {
Intent intent = new Intent("android.intent.action.MAIN");
intent.addCategory("android.intent.category.LAUNCHER");
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
intent.setComponent(ComponentName.unflattenFromString("com.example.servicedemo/.activity.MainActivity"));
return intent;
}
/**
* 注册广播
*/
private void registerMyReceiver() {
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(MyBroadcastReciver.ACTION);
this.registerReceiver(new MyBroadcastReciver(this), intentFilter);
}
@Override
public void onDestroy() {
super.onDestroy();
stopForeground(true);
PollingUtils.stopPollingService(this, TimeReceiver.class, TimeReceiver.ACTION);
}
}