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

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执行完之后,会自动结束服务。其方便性不言而喻。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值