AIDL:Android接口自定义语言,进程之间的通讯
下面运用AIDL实现两个应用之间简单的通讯(一个客户端应用调用另一个应用的服务)
(一)建一个工程BService,在包下面建一个文件IMusicPlayer.aidl(与接口名相同)
package com.example.bservice;
interface IMusicPlayer {
void playMusic(String path);
}
(二)写一个服务类MusicPlayerService
package com.example.bservice;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.RemoteException;
import android.widget.Toast;
import com.example.bservice.IMusicPlayer.Stub;
public class MusicPlayerService extends Service {
private Handler mHandler = new Handler();
private ServiceBind serviceBind = new ServiceBind();
public class ServiceBind extends Stub{
@Override
public void playMusic(String path) throws RemoteException {
mHandler.post(new Runnable() {
@Override
public void run() {
Toast.makeText(MusicPlayerService.this, "调用成功", Toast.LENGTH_SHORT).show();
}
});
}
}
@Override
public IBinder onBind(Intent arg0) {
return serviceBind;
}
}
(三)在AndroidManifest里注册服务和action(用于隐式调用)
<service android:name="com.example.bservice.MusicPlayerService">
<intent-filter >
<action android:name="com.example.bservice.MUSIC_PLAYER"/>
</intent-filter>
</service>
(四)建一个工程AClient,把工程BService的包复制到AClient的src下,只要aidl文件,看到gen里生成了相同的包名既可
(五)写一个Activity
package com.example.aclient;
import android.app.Activity;
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.view.View;
import com.example.bservice.IMusicPlayer;
public class MainActivity extends Activity {
private IMusicPlayer mIMusicPlayer;//声明接口
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName arg0) {
mIMusicPlayer = null;
}
@Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
mIMusicPlayer = IMusicPlayer.Stub.asInterface(arg1);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//绑定服务
Intent intent = new Intent();
intent.setAction("com.example.bservice.MUSIC_PLAYER");
bindService(intent, connection, BIND_AUTO_CREATE);
}
//按键点击事件
public void onBtnClick(View v){
try {
mIMusicPlayer.playMusic("");
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (connection != null) {
unbindService(connection);//解除绑定
connection = null;
}
}
}