android-service4

来源:互联网 发布:女子不孕不育网络咨询 编辑:程序博客网 时间:2024/05/19 23:01
一.创建: aidl文件
package com.example.administrator.servicetest.aidl;// Declare any non-default types here with import statements interface IMyAidlInterface {    /**     * Demonstrates some basic types that you can use as parameters     * and return values in AIDL.     */    void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,double aDouble, String aString);     String getData();     int getNumber();}
二.创建service
public class MyService_iadl extends Service{    private   MyIADL myIADL=new MyIADL();    public MyService_iadl() {    }    @Override    public IBinder onBind(Intent intent) {        // TODO: Return the communication channel to the service.        return myIADL;//throw new UnsupportedOperationException("Not yet implemented");    }    public class  MyIADL extends IMyAidlInterface.Stub    {        @Override        public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {        }        @Override        public String getData() throws RemoteException {            return "OK";        }        @Override        public int getNumber() throws RemoteException {            return 111;        }    }}
配置service
<service    android:name=".Service.MyService_iadl"    android:enabled="true"    android:exported="true">    <intent-filter>        <action android:name="android.intent.action.iadl"/>    </intent-filter></service>

三.调用service
通过  IMyAidlInterface  接口就可以调用了实现跨进程通信
public class Service_AIDL_Fragment extends Fragment implements View.OnClickListener {
IMyAidlInterface  myIADL=null;
 
connection=new ServiceConnection() {    @Override    public void onServiceConnected(ComponentName name, IBinder service) {        myIADL= IMyAidlInterface .Stub.asInterface(service);    }    @Override    public void onServiceDisconnected(ComponentName name) {    }};
开始service
Intent intent=new Intent();intent.setAction("android.intent.action.iadl");intent.setPackage(context.getPackageName());
context.bindService(intent,connection, Service.BIND_AUTO_CREATE);

注销service
context.unbindService(connection);

获取数据:
String str=  myIADL.getData();

}

0 0
原创粉丝点击