Service、Alarm与BroadcastReceiver的使用方法

1:定义一个服务类,在服务类中使用AlarmManager 来管理服务的运行

public class WtacService extends Service{
private AlarmManager alarmManager = null;
private PendingIntent alarmIntent = null; @Override
public IBinder onBind(Intent arg0) {
return null;
} @Override
public void onCreate() {
super.onCreate();
alarmManager = (AlarmManager)this.getSystemService(Context.ALARM_SERVICE);
String ALARM_ACTION = WR.ACTION_WTAC_ALAEM;
Intent intentTo = new Intent(ALARM_ACTION);
alarmIntent = PendingIntent.getBroadcast(this, 0, intentTo, 0);
} @Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Context context = this.getApplicationContext(); int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
long timeRepeat = SystemClock.elapsedRealtime()+(10*1000);
long intervalMillis = 10*1000;
alarmManager.setInexactRepeating(alarmType, timeRepeat, intervalMillis, alarmIntent); Thread mThread = new Thread(new Runnable(){
@Override
public void run() {
try{
DBManager dbManager = new DBManager(context);
List<Wtac> list = dbManager.selectWtacs();
Gson gson = new Gson();
String json = gson.toJson(list, new TypeToken<List<Wtac>>(){}.getType());
System.out.println("结果:"+json);
}finally{
//服务每次执行完成就关闭
stopSelf();
}
}
});
mThread.start(); return Service.START_NOT_STICKY;
}
}

2:在AndroidManifest.xml文件中注册这个Service

<service
android:name="com.wzh.service.WtacService"
android:enabled="true"
android:exported="false" />

3:定义广播接收器

public class WtacAlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
Intent startIntent = new Intent(context, WtacService.class);
context.startService(startIntent);
}
}

4:在AndroidManifest.xml文件中注册这个广播接收器

<receiver android:name="com.wzh.receiver.WtacAlarmReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="com.wzh.receiver.ACTION_WTAC_ALAEM"/>
</intent-filter>
</receiver>
上一篇:TCP/IP学习笔记


下一篇:websocket 项目应用