在您的应用程序或单个应用程序上编写服务。将 AIDL(Android 接口定义语言)定义为 IRemoteService.aidl,以下是我的伪代码或示例实现。使用这种方法,您可以通过您的应用程序启动活动并处理另一个应用程序的事件。
// IRemoteService.aidl
// Declare any non-default types here with import statements
/** Example service interface */
interface IAccountService {
String getLoggedInUserInfo(String appId);
void userLogin(String appId,ILoginCallback cb);
void signout(String appId);
}
interface ILoginCallback {
void loginSuccess(String userId);
void loginFailed();
}
在您的服务中有一些 RemoteCallbacks
@Override
public IBinder onBind(Intent intent) {
final RemoteCallbackList<ILoginCallback> mCallbacks = new RemoteCallbackList<ILoginCallback>();
if(mCallbacks!=null){
int i = mCallbacks.beginBroadcast();
while(i>0){
i--;
try {
Log.e(TAG, "Callback ...");
mCallbacks.getBroadcastItem(i).loginSuccess(newUserId);
} catch (RemoteException e) {
// The RemoteCallbackList will take care of removing
// the dead object for us.
}
}
mCallbacks.finishBroadcast();
}
}
private final IAccountService.Stub mBinder = new IAccountService.Stub() {
@Override
public void userLogin(String appId,ILoginCallback cb) throws RemoteException {
String userId = Settings.getSettings().getUserId();
if(userId ==null||userId.length()==0){
mCallbacks.register(cb);
Intent intent = new Intent(getApplicationContext(), AccountLoginActivity.class);
intent.putExtra("deviceId", Settings.getSettings().getDeviceUniqueId());
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
您可以在以下链接中找到详细的 AIDL 示例。
- http://owenhuangtw.pixnet.net/blog/post/23760257-android-aidl-(android-interface-definition-language)
- http://www.app-solut.com/blog/2011/04/using-the-android-interface-definition-language-aidl-to-make-a-remote-procedure-call-rpc-in-android/
- https://github.com/afollestad/aidl-example