Android 8,程序员必学之一
作者:互联网
void bindSuccess();
void unbind();
}
注意两个应用的 AIDL 文件必须一致,包括包名。
然后,编写两个 binder 实体服务 RemoteService 、LocalService,主要代码如下:
public class RemoteService extends Service {
private static final String TAG = “RemoteService”;
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, “onCreate: 创建 RemoteService”);
bindLocalService();
}
@Override
public IBinder onBind(Intent intent) {
return stub;
}
private IMyAidlInterface.Stub stub = new IMyAidlInterface.Stub() {
@Override
public void bindSuccess
() throws RemoteException {
Log.e(TAG, “bindSuccess: LocalService 绑定 RemoteService 成功”);
}
@Override
public void unbind() throws RemoteException {
Log.e(TAG, “unbind: 此处解除 RemoteService 与 LocalService 的绑定”);
getApplicationContext().unbindService(connection);
}
};
/**
- 绑定 LocalService
*/
private void bindLocalService() {
Intent intent = new Intent();
intent.setComponent(new ComponentName(“com.wuzy.aidlclient”, “com.wuzy.aidlclient.LocalService”));
if (!getApplicationContext().bindService(intent, connection, Context.BIND_AUTO_CREATE)) {
Log.e(TAG, “bindLocalService: 绑定 LocalService 失败”);
stopSelf();
}
}
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
}
@Override
public void onServiceDisconnected(ComponentName name) {
// bindRemoteService();
createTransferActivity();
}
};
private void createTransferActivity() {
Intent intent = new Intent(this, TransferActivity.class);
intent.setAction(TransferActivity.ACTION_FROM_SELF);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
public class LocalService extends Service {
private static final String TAG = “LocalService”;
@Override
public void onCreate() {
super.onCreate();
Log.e(TAG, “onCreate: 创建 LocalService”);
bindRemoteService();
}
@Override
public IBinder onBind(Intent intent) {
Log.e(TAG, “onBind: 绑定 LocalService”);
return stub;
}
private IMyAidlInterface.Stub stub = new IMyAidlInterface.Stub() {
@Override
public void bindSuccess() throws RemoteException {
Log.e(TAG, “bindSuccess: RemoteService 绑定 LocalService 成功”);
}
@Override
写在最后
很多人在刚接触这个行业的时候或者是在遇到瓶颈期的时候,总会遇到一些问题,比如学了一段时间感觉没有方向感,不知道该从哪里入手去学习,对此我整理了一些资料
如果你熟练掌握以下列出的知识点,相信将会大大增加你通过前两轮技术面试的几率!这些内容都供大家参考,互相学习。
①「Android面试真题解析大全」PDF完整高清版+②「Android面试知识体系」学习思维导图压缩包,最后觉得有帮助、有需要的朋友可以点个赞
ZB7ddF7-1647701648584)][外链图片转存中…(img-eBgDFyBz-1647701648585)]
[外链图片转存中…(img-Q7CpYMEj-1647701648586)]
标签:void,必学,程序员,TAG,intent,LocalService,Override,Android,public 来源: https://blog.csdn.net/m0_68318673/article/details/123604988