Android第一行代码学习记录service启动方式

Service启动方式(主要是1,2两种):

1、startService启动 :主要用于启动服务执行后台任务,不进行通信。停止服务使用stopService;

 Intent startIntent =new Intent(MainActivity.this,MyService.class);
 startService(startIntent);

2、bindService 启动 :该方法启动的服务可以进行通信。

    private ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder=(MyService.DownloadBinder)service;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };




Intent bindIntent=new Intent(this,MyService.class);
bindService(bindIntent,connection,BIND_AUTO_CREATE)// 绑定MainActivity和MyService

 Android中bindService的使用及Service生命周期_孙群-CSDN博客_android中bindservice

使用IntentService

Service中的代码都是默认运行在主线程当中,运用Android多线程编程的技术,在Service的每个具体的方法里开启一个子线程,在这里处理耗时的逻辑

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        new Thread(new Runnable() {
            @Override
            public void run() {
                //处理具体的逻辑
                stopSelf();// 调用stopSelf()方法让一直处于运行状态的服务停止下来
            }
        }).start();
        Log.d("MyService", "onStartCommand executed");
        return super.onStartCommand(intent, flags, startId);
    }

调用stopService()或stopSelf()方法,使Service在执行完毕后自动停止的功能。

使用IntentService类,为了可以简单地创建一个异步的、会自动停止的Service

public class MyIntentService extends IntentService {
    public MyIntentService(){
        super("MyIntentService");
    }


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

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.d("MyIntentService","Thread id is "+Thread.currentThread().getId());
    }
}

首先要求必须先调用父类的构造函数,并传入一个字符串,这个字符串可以随意指定,只在调试的时候有用。子类中实现onHandlerIntent()这个抽象方法,在这个方法中可处理一些耗时的逻辑,方法在子线程中,通过打当前线程名证实。

IntentService特性,这个Service运行结束自动停止,重写onDestroy()方法,日志证实。

case R.id.start_intent_service:
                // 打印主线程的id
                Log.d("MainActivity","Thread id is "+Thread.currentThread().getId());
                Intent intentService=new Intent(this,MyIntentService.class);
                startService(intentService);

注册

   <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true">

        </service>

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值