Android Service詳解(三) AIDL使用解析

    aidl是 Android Interface definition language的縮寫,它是一種android內部進程通信接口的描述語言,通過它我們可以定義進程間的通信接口。

    通過aidl我們可以完成從服務端到客戶端的數據通信

    在aidl中我們可以聲明任意多個方法,除了內建類型(int boolean等)都需要導入,規則如下:

    1、Java 原始類型不需要導入。

    2、String、Lsit、Map 和 CharSequence 不需要導入。

    創建aidl文件,New->file->文件名.aidl,添加如下代碼:

package com.example.new1;

interface INewService {
    void setAge(int age);
    int getAge();
    void setName(String name);
    String getName();
}

點擊保存,刷新工程,會在gen下自動產生java代碼。

(產生的代碼有時候沒有縮進,可以右鍵->Source->Format進行設置)


                    wKiom1T116rDRG8AAABsjC3apQw714.jpg

在生成的代碼中又一個Stud類,他繼承於IBinder。可以把它作爲Service的onBind的返回值,一旦這個Service被其他程序的服務綁定,就將這個IBinder類實例發送出去,同樣這個實例裏重寫的方法數據也跟着一起發送出去。


新建一個Servers,命名爲NewService.java

裏面聲明一個Stub類,完成上面定義的四個函數,代碼如下:

package com.example.new1;
import com.example.new1.INewService.Stub;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;
public class NewService extends Service {
    private String name="www.51ct0.com";
    private int age=18;
    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        Toast.makeText(NewService.this, "onBind", Toast.LENGTH_LONG).show();
        Log.i("SERVICE","onbind");
        return mbinder;                //返回接口
    }
    public void onCreate() {
        super.onCreate();
        Log.i("SERVICE","oncreat");
    }
    public void onStart(Intent intent,int startId) {
        Log.i("SERVICE","onstart");
    }
    public void onDestroy() {
        Log.i("SERVICE","ondestory");
    }
    private INewService.Stub mbinder = new Stub() {
        @Override                                        //實現接口定義的函數
        public void setAge(int age) throws RemoteException {
            // TODO Auto-generated method stub
            NewService.this.age = age;
        }
        @Override
        public int getAge() throws RemoteException {
            // TODO Auto-generated method stub
            return NewService.this.age;
        }
        @Override
        public void setName(String name) throws RemoteException {
            // TODO Auto-generated method stub
            NewService.this.name=name;
        }
        @Override
        public String getName() throws RemoteException {
            // TODO Auto-generated method stub
            return NewService.this.name;
        }
    };
}

    到目前爲止,已經實現了接口中的全部函數,下面,將實現客戶端的調用:

新建一個Activity.java,代碼如下:

package com.example.new1;
import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.ComponentName;
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.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends Activity {
    private TextView textview;
    private INewService inewservice;//聲明接口
    private ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName arg0, IBinder arg1) {
            // TODO Auto-generated method stub
            inewservice = INewService.Stub.asInterface(arg1);//獲得接口
            try {
                inewservice.setName("我是Activity");    //調用函數
                inewservice.setAge(25);
                textview.setText(inewservice.getName()+inewservice.getAge());
            } catch (RemoteException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            Log.i("SERVICE","success"    );
        }
        @Override
        public void onServiceDisconnected(ComponentName arg0) {
            // TODO Auto-generated method stub
            Log.i("SERVICE","errer");
        }
    };
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1=(Button)this.findViewById(R.id.btn1);
        textview=(TextView)this.findViewById(R.id.mytext1);
        button1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                bindService(new Intent(MainActivity.this,NewService.class),conn,BIND_AUTO_CREATE);
            }
        });
    }
}


運行結果如下:

                    wKiom1T2d9vQ6P4TAACTMpf5E5c099.jpg                                     wKioL1T2ePvihND5AACQOC0Hywg134.jpg




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章