快捷搜索: 王者荣耀 脱发

AIDL调用第三方应用程序服务中的方法

今天自己写了一个Demo,利用AIDL在两个进程间进行通讯,步奏如下:

1.新建一个服务工程,在其中新建一个服务,代码如下:

package com.zouwj.remoteservice; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.widget.Toast; public class RemoteService extends Service { @Override public IBinder onBind(Intent intent) { System.out.println("onBind"); return new MyBinder(); } public class MyBinder extends IService.Stub{ @Override public void callMethodInService() { methodInService(); } } @Override public void onCreate() { System.out.println("onCreate"); super.onCreate(); } @Override public void onDestroy() { System.out.println("onDestroy"); super.onDestroy(); } @Override public boolean onUnbind(Intent intent) { System.out.println("onUnbind"); return super.onUnbind(intent); } public void methodInService() { System.out.println("调用了远程服务中的方法"); Toast.makeText(this, "haha", 0).show(); } }

为服务配置:

<service android:name="com.zouwj.remoteservice.RemoteService" android:exported="true"> <intent-filter> <action android:name="com.zouwj.myremoteservice"/> </intent-filter>

</service>

配置<intent-filter>是是服务可以被第三方应用调用

2.IService.aidl如下所示:

package com.zouwj.remoteservice; interface IService { void callMethodInService(); }

3.新建另外一个调用服务的安卓工程,新建一个包,名字和提供服务的工程的IService.aidl文件所在的包名一致,并把IService.aidl文件拷贝到包下。

在activity中调用远程服务的方法

package com.zouwj.callremotemethod; import com.zouwj.remoteservice.IService; import android.os.Bundle; import android.os.IBinder; import android.os.RemoteException; import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.view.View; public class MainActivity extends Activity { private MyConn conn; private IService binder; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } public void bind(View view) { Intent service = new Intent(); service.setAction("com.zouwj.myremoteservice"); conn=new MyConn(); bindService(service, conn, BIND_AUTO_CREATE); } public class MyConn implements ServiceConnection{ @Override public void onServiceConnected(ComponentName name, IBinder service) { binder=IService.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { } } public void call(View view) { try { binder.callMethodInService(); } catch (RemoteException e) { System.out.println(e); e.printStackTrace(); } } @Override protected void onDestroy() { unbindService(conn); super.onDestroy(); } }

程序运行后,出现异常:

10-02 03:22:20.272: E/JavaBinder(7275): java.lang.RuntimeException: Cant create handler inside thread that has not called Looper.prepare()

经分析,发现问题在于第三方应用的服务并不是运行在本进程的主UI,并不能直接更改主UI界面。也就是服务的方法中不能直接弹土司。

经验分享 程序员 微信小程序 职场和发展