C/C++教程

android调用远程service(一个apk调用另一个apk的service)

本文主要是介绍android调用远程service(一个apk调用另一个apk的service),对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

根据android的binder,以及网上aidl的例子,编写了一个调用远程service的例子.


server//

1.aidl

建立com.easymorse包,aidl文件为ICountService.aidl

文件内容:

package com.easymorse;


interface ICountService{
int getCount();
}


2.service

public class CountService extends Service {


    private boolean threadDisable;


    private int count;
    
    public ICountService.Stub serviceBinder=new ICountService.Stub(){
@Override
public int getCount() throws RemoteException {
return count;
}
   
    };


    @Override
    public IBinder onBind(Intent intent) {
    count = 103;
    Log.v("zxl---onBind", "Count is " + count);
        return serviceBinder;
    }


    @Override
    public void onCreate() {
        super.onCreate();
    }


    @Override
    public void onDestroy() {
        super.onDestroy();
        this.threadDisable = true;
        Log.v("zxl---CountService", "on destroy");
    }
}


3.AndroidManifest.xml

       <service 
            android:name="com.example.myservice.CountService">
           
       

server//


client//


1.aidl

建立com.easymorse包,aidl文件为ICountService.aidl

文件内容:

package com.easymorse;


interface ICountService{
int getCount();
}


2.调用

public class MyClientActivity extends Activity {

private ServiceConnection serviceConnection = new ServiceConnection() {

@Override
public void onServiceDisconnected(ComponentName name) {
System.out.println("zxl---onServiceDisconnected---"+name);
}

@Override
public void onServiceConnected(ComponentName name, IBinder service) {
ICountService iCountService = ICountService.Stub.asInterface(service);
try {
System.out.println("zxl---onServiceConnected---"+iCountService.getCount());
} catch (RemoteException e) {
e.printStackTrace();
}
}
};


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my_client);
        
        Intent service = new Intent("com.easymorse.CountService");
        bindService(service, serviceConnection, BIND_AUTO_CREATE);
    }
    
    @Override
    protected void onDestroy() {
    // TODO Auto-generated method stub
    unbindService(serviceConnection);
    super.onDestroy();
    }
}


client//
















这篇关于android调用远程service(一个apk调用另一个apk的service)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!