服务集合都是在后台运行的,一直以来它都是默默的做着幸苦的工作。但是服务的系统优先级还是比较低的,当系统出现内存不足时,就有可能会回收屌后台运行的服务。如果系统服务可以一直保持运行状态,而不会由于系统内存不足的原因导致被回收,就可以考虑使用前台服务。前台服务和普通服务最大的区别在于,它会一直有一个正在运行的图标在系统的状态栏显式,下拉状态栏可以看到更加相信的信息,非常类似于通知的效果。当然有时候你也可能不仅仅是为了防止服务被回收才使用前台服务的,有些项目由于特殊性的需求会要求必须使用前台服务,比如说墨迹天气,它的服务在后台更新天气数据的同时,还会在系统状态栏一直显示当前的天气信息。
我们修改Service中的onCreate方法
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
这样当我们创建服务的时候,就会在状态栏弹出一个提示,我们点击提示,会跳转到我们设置的Activity上
我们知道,Service中的代码都是默认运行在主线程当中的,如果直接在服务里去处理一些耗时的逻辑,就很容易出现ANR。
所以这个时候就需要用到Android多线程,为了简单的创建一个异步的、会自动停止的服务,Android专门提供了一个IntentService类,我们看一下它的用法。
MyIntentService.java
public class MyIntentService extends IntentService {
public MyIntentService(String name) {
super(name);
}
public MyIntentService() {
super("");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "service starting", Toast.LENGTH_SHORT).show();
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.d("TTTT", "MyIntentService - Thread id is " + Thread.currentThread().getId());
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d("TTTT", "onDestroy 方法执行了");
}
}
MainActivity.java
public class MainActivity extends Activity {
private Button bt_bind, bt_unbind;
private TextView tv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bt_bind = (Button) findViewById(R.id.bt_bind);
bt_unbind = (Button) findViewById(R.id.bt_unbind);
tv = (TextView) findViewById(R.id.tv);
bt_bind.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("TTTT", "MainActivity - Thread id is " + Thread.currentThread().getId());
Intent intent = new Intent(MainActivity.this, MyIntentService.class);
startService(intent);
}
});
}
}
Log提示如下:
05-31 13:43:29.437: D/TTTT(2535): MainActivity - Thread id is 1
05-31 13:43:29.462: D/TTTT(2535): MyIntentService - Thread id is 181
05-31 13:43:29.494: D/TTTT(2535): onDestroy 方法执行了
并且有Toast提示,代表onStartCommand方法的执行。
通过Log我们发现onDestroy方法在运行完毕之后自动执行了,所以IntentService是集开启线程和自动停止于一身的。