创建aidl文件:IMyAidlInterface.aidl Build-> Clean Project 重新编译下项目 生成IMyAidlInterface.class文件
interface IMyAidlInterface {
void basicTypes(int jk);
}
--MyService
public class MyService extends Service {
//定义音乐播放
private MediaPlayer mediaPlayer;
public MyService() {
System.out.println("==MyService===========MyService()==========");
}
@Override
public IBinder onBind(Intent intent) {
// TODO: 绑定服务 服务将中间人交出来 做连接用
mediaPlayer.start();
System.out.println("==MyService=====绑定服务======onBind(Intent intent)==========");
return new MiddlePeople();
}
/**中间人 */
class MiddlePeople extends IMyAidlInterface.Stub{
@Override
public void basicTypes(int jk) throws RemoteException {
if(jk > 5000){
Toast.makeText(getApplication(),"执行成功大于5000---中间人中的方法",Toast.LENGTH_LONG).show();
System.out.println("执行成功大于5000---中间人中的方法");
}else{
Toast.makeText(getApplication(),"执行成功小于5000---中间人中的方法",Toast.LENGTH_LONG).show();
System.out.println("执行成功小于5000---中间人中的方法");
}
}
}
@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(MyService.this,R.raw.dahuaxiyou);
System.out.println("==MyService========创建==onCreate()==========");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
System.out.println("==MyService========启动==onStartCommand()==========");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.release();
System.out.println("==MyService========销毁==onDestroy()==========");
}
@Override
public boolean onUnbind(Intent intent) {
System.out.println("==MyService========解绑服务==onUnbind==========");
return super.onUnbind(intent);
}
}
---MainActivity
/** 获取其他进程中服务的通信接口 */
private IMyAidlInterface rst;
//服务连接对象
private ServiceConnection connection;
//服务连接对象,应用一打开就去连接 onCreate方法中--
connection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//service 中间人,进程与服务中间人其取得联系,中间人服务交给当前进程
rst = IMyAidlInterface.Stub.asInterface(service);
}
@Override
public void onServiceDisconnected(ComponentName name) {
//
}
};
--
Intent intent = new Intent(MainActivity.this,MyService.class);
bindService(intent,connection,BIND_AUTO_CREATE); 绑定服务
unbindService(connection); 解绑服务
rst.basicTypes(50000); 调用服务中的方法