您的位置:首页 > 编程语言

第一行代码-9.5 服务的更多技巧

2016-02-27 10:41 330 查看
1、使用前台服务

  使用一般的服务依然有被系统回收的可能,因为优先级还比较低,前台服务则可以保持运行状态,不会因为系统内存不够而被回收。它和一般的服务最大的区别在于它会一直有一个正在运行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,非常类似于通知的效果。比如360、墨迹天气等。



// MyService.java - 修改的内容
@Override
public void onCreate() {
Log.d("MyService", "执行onCreate()!");
// 设置前台服务
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle("前台服务标题");
builder.setContentText("前台服务内容");
Intent notificationIntent = new Intent(MyService.this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(pendingIntent);
Notification notification = builder.getNotification();
notification.defaults = Notification.DEFAULT_ALL;
startForeground(1, notification); // 之前是manager.notify(id, notification)
super.onCreate();
}


  这段代码其实就来自上一章学的显示通知的内容,只不过最后显示通知的函数变成了startForeground(id, notification)。



2、使用IntentService

  由于服务的代码还是在主线程中执行的,所以如果要在服务中进行网络连接等耗时的操作,依然要开启子线程,但是这样服务一旦开启之后,就会一直处于运行状态,除非执行stopService()或stopSelf(),所以为了Android专门提供了IntentService避免这种麻烦。

  新建MyIntentService,如下:

// MyIntentService.java
public class MyIntentService extends IntentService{

public MyIntentService() {
super("MyIntentService"); // 调用父类的有参构造函数
}

@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService", "执行onDestroy()!");
}

@Override
protected void onHandleIntent(Intent intent) {
// 打印当前线程的id
Log.d("MyIntentService", "当前线程id是" + Thread.currentThread().getId());
}
}


  然后在MainActivity.java中开启这个服务,看一下是否会开启子线程,以及是否会自动结束服务。

// MainActivity.java - 增加的部分
case R.id.start_intent_service_button:
// 打印主线程id
Log.d("MainActivity", "主线程id是"+Thread.currentThread().getId());
Intent intentService = new Intent(MainActivity.this, MyIntentService.class);
startService(intentService);
break;


  最后别忘记在manifest中注册。执行效果:



  可以看到确实在执行onHandleIntent的时候,会创建新的线程,而且在onHandleIntent执行完之后,会自动结束服务。其方便性不言而喻。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: