service在安卓中能实现在后台中持久化运行,一个service的典型使用方法,就是在程序第一次运行时启动服务,服务启动后发送一条广播,广播接收器接到广播后再次启动服务,这样就可以保证服务在后台及时更新数据,持久化运行。
我们写一个简单的例子:
在程序运行后,我们启动服务。
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this,MyService.class));
}
}
在服务启动后执行onStartCommond方法,因为服务是默认运行在主线程中的,所以我们启动一个线程来执行耗时操作,在这里服务启动后我们打印现在的时间。Alarm类似于java中的timer类,是用来执行定时操作的,首先我们从系统服务中取得alarmmanager对象,manager对象有一个set方法,这个方法有三个参数,第一个参数是Alarm的种类,
我们选用的这个种类是指是从1970年1月1日开始计算时间,第二个参数是1970年1月1日到现在的毫秒数加上我们选择的延时时间,这里我选择延时10000毫秒发送一次广播。
第三个参数是一个pendingintent,用来发送广播。这样我们在每次执行服务后的10000毫秒,就会发送一条广播。
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
Log.i("MyService","time is"+ new Date().toString());
}
}).start();
AlarmManager manager = (AlarmManager) getSystemService(ALARM_SERVICE);
int sec = 10000;
long time = 1000+ SystemClock.currentThreadTimeMillis();
intent = new Intent(this,MyReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(this,1,intent,0);
manager.set(AlarmManager.RTC_WAKEUP,time,pendingIntent);
return super.onStartCommand(intent, flags, startId);
}
}
在接到服务发出的广播后,我们又开启服务,这样就可以保证每10000毫秒,服务就重新执行一次。
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@Override
public void onReceive(Context context, Intent intent) {
intent = new Intent(context,MyService.class);
context.startService(intent);
}
}