Android -- service的开启方式, start开启和绑定开启服务,调用服务的的方法, aidl调用远程服务

1. 概述

bindService() 绑定服务  可以得到服务的代理人对象,间接调用服务里面的方法.
绑定服务: 间接调用服务里面的方法.
          如果调用者activity被销毁了, 服务也会跟着销毁
          (不求同时生,但求同时挂)         
开启服务: 不可以调用服务里面的方法.
          如果调用者activity退出了, 服务还会长期的在后台运行

生命周期:
1.单独调用  startService() - oncreate
            stopService()   ondestroy
 -----------------------------------
            bind ->oncreate -> onbind
            unbind -> onunbind ->ondestroy
            服务只能被解绑一次,多次的解除绑定服务 应用程序会报错.
   
混合调用.
需求: 既要保证服务长期的在后台运行,又想去调用服务里面的方法.
技巧: 1.先开启服务 2.绑定服务.
步骤:1.开启服务 startService()- oncreate();
     2.绑定服务 bindService() -  onbind();
     3.关闭程序 ,调用者退出, 服务被解绑.
     4.stopService() 停止服务.

2. 示意图

 

3. 示例代码

MainActivity.java 开启服务

public class MainActivity extends Activity {
	//步骤4: 在activity里面得到服务 ibinder对象的引用.
	private IService myBinder;
	
	private MyConn conn;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	/**
	 * 开启服务
	 * 
	 * @param view
	 */
	public void start(View view) {
		Intent intent = new Intent(this, CungeService.class);
		// 采用api 创建 服务 ,服务对象是被系统(框架 )new 出来
		startService(intent);
	}

	/**
	 * 停止服务
	 */
	public void stop(View view) {
		Intent intent = new Intent(this, CungeService.class);
		stopService(intent);
	}

	
	
	public void bind(View view){
		Intent intent = new Intent(this, CungeService.class);
		//intent 激活服务的意图
		// conn 代理人 中间人对象 用来跟服务建立联系 不能为空
		// BIND_AUTO_CREATE 在绑定服务的时候 如果服务不存在 就自动的创建
		//步骤1: 采用绑定服务的方式 开启服务
		conn = new MyConn();
		bindService(intent,conn , BIND_AUTO_CREATE);
	}
	
	//接触绑定服务的方法
	public void unbind(View view){
		unbindService(conn);
	}
	
	@Override
	protected void onDestroy() {
		try{
		unbindService(conn);
		}catch (Exception e) {
		}
		super.onDestroy();
	}
	
	private class MyConn implements ServiceConnection{

		// 在服务被成功绑定的时候 调用的方法
		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			System.out.println("春哥把代理人返回回来了...");
			//步骤3: 服务返回的ibinder对象 会被传递给 MyConn 的回调方法
			System.out.println(service);
			myBinder  = (IService) service;
			
		}
		// 在服务失去绑定的时候 调用的方法 只有程序异常 终止,
		@Override
		public void onServiceDisconnected(ComponentName name) {
			
		}
		
	}
	
	
	/**
	 * 调用服务里面的方法 ,换首歌
	 */
	public void change(View view) {
		// 由于系统框架在创建服务的时候 会创建与之对应的上下文,
		// 下面的代码 是直接new对象 .
		// CungeService service = new CungeService();
		// service.changeSing("月亮之上");
		//步骤5: 利用ibinder 对象 间接的调用了服务里面的方法
		myBinder.callChangeSing("月亮之上");
	}
}

CungeService.java 服务代码

/**
 * 在后台长期运行的组件 唱歌
 * @author Administrator
 *
 */
public class CungeService extends Service {

	@Override
	public void onCreate() {
		super.onCreate();
		System.out.println("onCreate 服务开始了 ,春哥 开始唱歌");
	}

	@Override
	public IBinder onBind(Intent intent) {
		System.out.println(" onBind 春哥服务被成功的绑定了....");
		
		//步骤2: 服务在成功绑定的时候  会调用onbind方法 返回一个ibinder对象.
		//返回自定义的代理人对象
		MyBinder mybinder = new MyBinder();
		System.out.println(mybinder.toString());
		return mybinder;
	}
	
	/**
	 * 更改唱的歌曲
	 * @param singName
	 */
	public  void changeSing(String singName){
		Toast.makeText(getApplicationContext(), "开始唱"+singName, 0).show();
	}
		
	private class MyBinder extends Binder implements IService{
		//间接的利用代理人 调用了春哥的方法
		//内部类为private, 通过IService接口只暴露所需的方法
		public void callChangeSing(String name){
			changeSing(name);
		}
		
		public void peiCungeWatchTV(){
			
		}
		public void peiCungeCountMoney(){
			
		}
	}
			
	@Override
	public boolean onUnbind(Intent intent) {
		System.out.println("onunbind");
		return super.onUnbind(intent);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		System.out.println("onDestroy 服务销毁了 ,春哥停止唱歌");
	}
	
}

IService.java ,Binder接口,限制暴露出来的方法个数

//春哥代理人的接口
public interface IService {
	 public void callChangeSing(String name);
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.itheima.testservice"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.itheima.testservice.MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".CungeService"></service>
    </application>

</manifest>

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="start"
        android:text="开启服务" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="stop"
        android:text="停止服务" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="bind"
        android:text="绑定服务" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="unbind"
        android:text="解除绑定服务" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="change"
        android:text="调用服务里面的方法,换首歌" />

</LinearLayout>


4. aidl调用远程服务

绑定服务: 绑定服务不仅可以绑定本地的服务 还可以绑定远程(调用者和服务在不同的进程)服务,一个app调用另一个app的服务。

被调服务仍然是上面的服务, 只需要做两个修改

(1. 将 IService.java 文件改为 IService.aidl , 并将里面的public去掉

(2. 配置文件注册的时候添加action

        <service android:name=".RemoteService" >
            <intent-filter>
                <action android:name="com.kevin.remoteservice" >
                </action>
            </intent-filter>
        </service>
另一个app调用时操作也类似,

(1. 将IService.aidl 连同包名一起拷贝到当前app工程, 一定要连同包名拷贝

(2. MainActivity.java   开启服务

public class MainActivity extends Activity {
	private IService iService;
	private MyConn conn;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}

	public void bind(View view){
		Intent intent = new Intent();
		intent.setAction("com.kevin.remoteservice");
		conn = new MyConn();
		bindService(intent,conn , BIND_AUTO_CREATE);
		
	}
	
	public void call(View view){		
		try {
			iService.callMethodInService();
		} catch (RemoteException e) {
			e.printStackTrace();
		}			
	}
	
	
	private class MyConn implements ServiceConnection{

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			//Iservice 远程调用API
			iService = IService.Stub.asInterface(service);
		}
		@Override
		public void onServiceDisconnected(ComponentName name) {
					
		}		
	}
	
}


原文地址:https://www.cnblogs.com/xj626852095/p/3647965.html