Service

什么是Service

1.Service是Android四大组件之一,和Activity级别相当。

2.Service是可以长时间运行在后台的,是不可见,是没有界面的组件。

3.Service是运行在主线程中的。

4.Service可以跨进程调用。

Service有哪些应用场景

1.通过startService(Intent intent)的方式开启服务

2.bindService的启动过程,需要注意的是通过bindService启动service时,当service正常结束的时候,是不会调用onServiceDisconnected方法的,即使手动调用了unBindService()方法。

3.messenger使用service进行IPC通信:

messenger主要是使用了Ibinder机制,其本质也是使用了aidl,但是他的好处是不用手工编写aidl文件,也不用理会aidl的生成过程。使用么三messege 和 Handler进行消息进行传递通信。因为handler是线程安全而且是一对一的通信,所以当Android IPC是一对一的时候,可以考虑使用messenger代替aidl去实现进程间通信

4.最后就是aidl方式,aidl是处理Android进程间通信的,可以实现一对多的通信。

startService方式启动Service怎么做

1.新建类继承Service(我的类名是StartSv)

public class StartSv extends Service{
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

2.重写onCreate方法

@Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate: *************************" );
    }

3.实现onBind抽象方法

@Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

4.重写onStartCommand方法

  @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

5.重写onDestroy方法

@Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy: *************************");
        super.onDestroy();
    }

6.在AndroidManifest中注册Service

 <service android:name=".StartSv" />

7.在有Context环境中通过startService启动Service

                Intent intent=new Intent(this,StartSv.class);
                startService(intent);

8.在有Context环境中通过stopService停止Service

                Intent intent1=new Intent(this,StartSv.class);
                stopService(intent1);

完整StartSv类代码如下:

package com.example.androidthree;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by lenovo on 2018/6/19.
 */

public class StartSv extends Service{
    private String TAG="";
    private int count=0;
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e(TAG, "onCreate: *************************" );
    }

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

        Log.e(TAG, "onStartCommand: ********************************");
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (count<100){
                    Log.e(TAG, "run: "+count );
                    count++;
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        Log.e(TAG, "onDestroy: *************************");
        super.onDestroy();
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}

完整Java代码如下:

package com.example.androidthree;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class ServiceDemoActivity extends AppCompatActivity implements View.OnClickListener{
    private Button statrtBtn;
    private Button stopBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_demo);

        bindID();
    }

    private void bindID() {
        statrtBtn=findViewById(R.id.start_btn);
        stopBtn=findViewById(R.id.stop_btn);
        statrtBtn.setOnClickListener(this);
        stopBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.start_btn:
                Intent intent=new Intent(this,StartSv.class);
                startService(intent);
                break;
            case R.id.stop_btn:
                Intent intent1=new Intent(this,StartSv.class);
                stopService(intent1);
                break;
                default:
                    break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.e("", "onDestroy: +++++++++++++++++++++++++" );
    }
}

StartService的生命周期

这里写图片描述

bindService方式启动Service怎么做

bindService的方式和startService的方式差不多,bindService方式还需要多写一个onUnbind方法

  @Override
    public boolean onUnbind(Intent intent) {

        return super.onUnbind(intent);
    }

完整MyService类代码如下:

package com.example.androidthree;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {
    private final IBinder binder = new MyBinder();

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    public class MyBinder extends Binder {
        MyService getService() {
            return MyService.this;
        }
    }

    public void excute() {
        System.out.println("通过Binder得到Service的引用来调用Service内部的方法");
    }


    @Override
    public boolean onUnbind(Intent intent) {
        // 当调用者退出(即使没有调用unbindService)或者主动停止服务时会调用
        System.out.println("调用者退出了");
        return super.onUnbind(intent);
    }

    @Override
    public void onDestroy() {
        // 当调用者退出(即使没有调用unbindService)或者主动停止服务时会调用
        super.onDestroy();
    }


}

Java代码如下:

package com.example.androidthree;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;

/**
 * 此例的目的就是拿到MyService的引用,从而可以引用其内部的方法和变量
 *
 * @author Administrator
 *
 */

public class ServiceDemo1Activity extends AppCompatActivity {

    private MyService myService;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_demo1);
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, connection, Context.BIND_AUTO_CREATE);
    }

    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            myService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myService = ((MyService.MyBinder) service).getService();
            System.out.println("Service连接成功");
            // 执行Service内部自己的方法
            myService.excute();
        }
    };

    protected void onDestroy() {
        super.onDestroy();
        unbindService(connection);
    };
}

BindService的生命周期

这里写图片描述

IntentService有什么不同

bindService,startService都是运行在主线程中,如果有耗时操作,需要我们自己开线程并维护线程,IntentService不需要开启一个新的线程,如果做耗时操作时,它会自动转入子线程中。

IntentService怎么用,注意事项

使用IntentService的步骤

1.新建类继承IntentService类(我的类名之MyIntentService)

public class MyIntentService extends IntentService{
    private int count=0;

    public MyIntentService() {
        super("");
    }

    public MyIntentService(String name) {
        super(name);
    }
}

2.实现父类的构造方法

public MyIntentService(String name) {
        super(name);
    }

3.重写onHandleIntent()方法

@Override
    protected void onHandleIntent(@Nullable Intent intent) {
        while (count<100){
            count++;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

剩下的步骤和StartService差不多。

完整的MyIntentService代码如下:

package com.example.androidthree;

import android.app.IntentService;
import android.content.Intent;
import android.support.annotation.Nullable;
import android.util.Log;

/**
 * Created by lenovo on 2018/6/19.
 */

public class MyIntentService extends IntentService {

    private int count=0;
    private String TAG="";

    public MyIntentService(){
        super("");

    }

    public MyIntentService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
                   while (count<10){
                       Log.e(TAG, "onHandleIntent: *******************" +count);
                       count++;
                       try {
                           Thread.sleep(1000);
                       } catch (InterruptedException e) {
                           e.printStackTrace();
                       }
                   }
    }
}

Java代码如下:

package com.example.androidthree;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MyIntentActivity extends AppCompatActivity implements View.OnClickListener{
    private Button MyItBtn;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_intent);

        bindID();
    }

    private void bindID() {
        MyItBtn=findViewById(R.id.myit_btn);
        MyItBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()){
            case R.id.myit_btn:
                Intent intent=new Intent(this,MyIntentService.class);
                startService(intent);
                break;
                default:
                    break;
        }
    }
}

注意事项:

1..注册时候如果不加一个无参的构造方法注册表就会报错

这里写图片描述

无参构造方法这样写:

 public MyIntentService() {
        super("");
    }

2.启动Service只能用start启动Service

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值