Service基础-Android四大组件

目录

1、进程的简介

2、startService

3、bindService

4、通过bindService方式调用服务中的方法

5、既想让服务在后台长期运行,又需要调用服务中的方法。

6.aidl实现进程间通信IPC


1、进程的简介

App在启动时,会创建一个进程和线程。

优先级:

【1】、Forceground Process: 前台进程,优先级最高。相当于activity执行了onResume方法,用户正在交互。

【2】、Visible Process:可视进程,一直能让用户可见。相当于activity执行了onPause方法。

扫描二维码关注公众号,回复: 11592631 查看本文章

【3】、Service Process:服务进程,通过startService方法开启了一个服务。

【4】、Background Process:后台进程,相当于activity执行了onStop方法。界面不可见,但是activity没有被销毁。

【5】、Empty Process:空进程,不会维持任何组件运行。最先被销毁的进程

2、startService

【1】、定义一个类继承Service,在清单文件中注册Service。

【2】、使用startService方法执行intent中的自定义Service。

【3】、第一次开启服务会执行onCreate和onStartCommand方法,第二次开启服务只会执行onStartCommand方法。调用stopService方法可以停止服务。

【4】、服务一旦开启,就会长期运行在后台,知道用户手工停止。

3、bindService

【1】、定义一个类继承Service,在清单文件中注册Service。

【2】、定义一个类实现ServiceConnection接口,然后使用bindService(Intent service, ServiceConnection conn, int flags)方法绑定此服务。当onBind方法返回null时,不执行ServiceConnection中的onServiceConnected方法。第一次开启服务会执行onCreate,onBind方法,第二次开启服务无响应。

【3】、unbindService(ServiceConnection conn),bindService创建的服务不可以多次解绑。

【4】、bindService创建的服务与创建者(activity)同时销毁。

4、通过bindService方式调用服务中的方法

【1】、新建一个需要被外部调用的方法A。

// 服务中的方法,无法脱离Context使用

public void A(Integer money) {

Toast.makeText(getApplicationContext(), "充值成功:" + money, Toast.LENGTH_LONG).show();

}

【2】、定义一个继承Binder的内部类,定义外部调用的方法,方法内调用A。

public class MyBinder extends Binder {

public void callFunc(Integer money) {

(money);

}

}

【3】、在service类的onBind方法中返回继承Binder类的实例。

public IBinder onBind(Intent intent) {

Log.d(TAG, "onBind: ");

return new MyBinder();

}

【4】、在bindService中的ServiceConnection中的onServiceConnected中接收继承Binder类的实例。

private class MyServiceConn implements ServiceConnection {

// 服务连接成功时调用

@Override

public void onServiceConnected(ComponentName name, IBinder service) {

Log.d(TAG, "onServiceConnected: ");

myBinder = (ScreenService.MyBinder) service;

}

@Override

public void onServiceDisconnected(ComponentName name) {

Log.d(TAG, "onServiceDisconnected: ");

}

}

【5】获取到myBinder 实例。就可以在直接调用MyBinder 中对外的方法。

myBinder.callFunc(1000);

5、既想让服务在后台长期运行,又需要调用服务中的方法。

【1】、调用startService方法开启服务,能够保证服务在后台长期运行

【2】、调用bindService方法,获取Binder实例

【3】、调用完服务中的方法,使用unBindService方法解绑服务

【4】、调用stopService停止服务

6.aidl实现进程间通信IPC

【1】、将IService.java文件变成一个aidl文件,去掉public。

【2】、编辑器build目录会自动生成一个IService.java文件,自动生成Stub类,继承Binder,实现IService接口

【3】、自定义的Binder对象直接继承Stub

【4】、保证两个aidl文件一样,保证两个aidl文件所在的包名一样

【5】、继承ServiceConnection的类中获取Binder对象的方法不一样,调用Stub.asInterface(service)返回IBinder对象。即可调用远程进程的方法

猜你喜欢

转载自blog.csdn.net/qq_40913065/article/details/107980288