android aidl的建立

本文深入探讨了Android Service的两种启动方式——context.startService()与context.bindService(),详细解析了它们的生命周期过程及区别。同时,介绍了Service的生命周期方法如onCreate(), onStart(), onDestroy()等,并解释了在Service每次开启关闭过程中,哪些方法可以被多次调用。最后,文章还简述了onStartCommand方法中int返回值的作用,包括START_STICKY、START_NOT_STICKY、START_REDELIVER_INTENT和START_STICKY_COMPATIBILITY四种情况。

Serviceandroid 系统中的一种组件,它跟Activity的级别差不多,但是他不能自己运行,只能后台运行,并且可以和其他组件进行交互。Service的启动有两种方式:context.startService()context.bindService()。
 
使用context.startService() 启动Service是会会经历:
context.startService()  ->onCreate()- >onStart()->Service running
context.stopService() | ->onDestroy() ->Service stop 
 
如果Service还没有运行,则android先调用onCreate()然后调用onStart();如果Service已经运行,则只调用onStart(),所以一个Service的onStart方法可能会重复调用多次。 
 
stopService的时候直接onDestroy,如果是调用者自己直接退出而没有调用stopService的话,Service会一直在后台运行。该Service的调用者再启动起来后可以通过stopService关闭Service
 
所以调用startService的生命周期为:onCreate --> onStart(可多次调用) --> onDestroy
 
使用使用context.bindService()启动Service会经历:
context.bindService()->onCreate()->onBind()->Service running
onUnbind() ->onDestroy() ->Service stop
 
onBind将返回给客户端一个IBind接口实例,IBind允许客户端回调服务的方法,比如得到Service运行的状态或其他操作。这个时候把调用者(Context,例如Activity)会和Service绑定在一起,Context退出了,Srevice就会调用onUnbind->onDestroy相应退出。 
      
所以调用bindService的生命周期为:onCreate --> onBind(只一次,不可多次绑定) --> onUnbind --> onDestory。
 
Service每一次的开启关闭过程中,只有onStart可被多次调用(通过多次startService调用),其他onCreate,onBind,onUnbind,onDestory在一个生命周期中只能被调用一次。

Android开发的过程中,每次调用startService(Intent)的时候,都会调用该Service对象的onStartCommand(Intent,int,int)方法,然后在onStartCommand方法中做一些处理。然后我们注意到这个函数有一个int的返回值,这篇文章就是简单地讲讲int返回值的作用。
Android官方文档中,我们知道onStartCommand有4种返回值:

START_STICKY:如果service进程被kill掉,保留service的状态为开始状态,但不保留递送的intent对象。随后系统会尝试重新创建service,由于服务状态为开始状态,所以创建服务后一定会调用onStartCommand(Intent,int,int)方法。如果在此期间没有任何启动命令被传递到service,那么参数Intent将为null。

START_NOT_STICKY:“非粘性的”。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统不会自动重启该服务。

START_REDELIVER_INTENT:重传Intent。使用这个返回值时,如果在执行完onStartCommand后,服务被异常kill掉,系统会自动重启该服务,并将Intent的值传入。


START_STICKY_COMPATIBILITY:START_STICKY的兼容版本,但不保证服务被kill后一定能重启。



1.在ECLIPSE 下面新建工程 testAidl,建立包名称:com.cardroid.aidl

2.在工程建立完成后:新建文件UnTtleText file名称为:TestAidlInterface然后在里面写上自己的内容


package com.cardroid.aidl;
interface TestAidlInterface
{
    void testString(String name);
    void testInt(int num);
   
}

然后保存,保存的时候后缀为.aidl,如果里面接口的内容不写错的话,ADT会帮你在gen下面帮你生成一个和你当前AIDL接口文件所在的包名一样的下面会有一个同名的JAVA文件

这个文件不用我们去管理。

3,然后将接口和SERVICE绑定,我们新建服务类后,在服务类中将接口类实现,返回绑定到服务中:

package com.cardroid.aidl;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.cardroid.aidl.TestAidlInterface.Stub;

public class AidlService extends Service{

    private String TAG="AidlService";
    @Override
    public void onCreate() {
        Log.i(TAG, "===onCreate=====");
        super.onCreate();
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i(TAG, "===onStartCommand=====");
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "=======onBind======");
        return mBinderStub;
        //return new MyServiceImpl();
    }

    private TestAidlInterface.Stub mBinderStub=new TestAidlInterface.Stub() {
        
        @Override
        public void testString(String name) throws RemoteException {
            Log.i(TAG, "testString(String name)==="+name);
            
        }
        
        @Override
        public void testInt(int num) throws RemoteException {
            Log.i(TAG, "testInt()=num=="+num);
        }
    };

}

4,在客户端实现调用aidl ,常在ACTIVITY中实现调用:

package com.cardroid.aidl;


import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;

public class AidlActivity extends Activity {
    /** Called when the activity is first created. */
    private String TAG="===AidlActivity===";
    private TextView mText;
    private TestAidlInterface aidlService=null;
    private ServiceConnection mConnection=new ServiceConnection(){

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            Log.i(TAG, "===onServiceConnected======");
            aidlService= TestAidlInterface.Stub.asInterface(service);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            Log.i(TAG, "===onServiceDisconnected======");
            aidlService=null;
        }
    };
    
    private void binder(){
     ContextWrapper cw = new ContextWrapper(this);
     cw.startService(new Intent(cw, AidlService.class));
    // cw.bindService((new Intent()).setClass(cw, AidlService.class), mConnection, 0);
}
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Intent service = new Intent("com.cardroid.aidl.TestAidlInterface");
        service.putExtra("name", "aaa");
        bindService(service, mConnection, Context.BIND_AUTO_CREATE);
        mText=(TextView) findViewById(R.id.tv);
        mText.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                
                
                try {
                    aidlService.testInt(5);
                     aidlService.testString("TOM");
                } catch (RemoteException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        });
       
        
    }
}


最后在AndroidManifest.xml将服务,ACTIVITY,和AIDL配置好:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.cardroid.aidl"
      android:versionCode="1"
      android:versionName="1.0">
    <uses-sdk android:minSdkVersion="8" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".AidlActivity"
                  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=".AidlService"
      
        ><!--  android:process=".remote" -->
        <intent-filter>
        <action android:name="com.cardroid.aidl.TestAidlInterface"/>
        </intent-filter>
        </service>
     </application>
</manifest>

一个aidl就完成了,注意事项:

在AndroidManifest.xml文件中配置AIDL服务,尤其要注意的是,<action>标签中android:name的属性值就是客户端要引用该服务的ID,也就是Intent类的参数值。

aidl文件的内容与Java代码非常相似,但要注意,不能加修饰符(例如,public、private)、AIDL服务不支持的数据类型(例如,InputStream、OutputStream)等内容。

<!--  android:process=".remote" -->如果服务和本地在一起(即时同一个包名下)就不能添加这个属性,如果在两个不同的工程或者不同的包名下面就要使用这个属性。

aidl文件最好和服务类放入到同一个包名下面,因为是结合服务使用的。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值