Android 8,程序员必学之一

2022/3/20 1:28:19

本文主要是介绍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)]



这篇关于Android 8,程序员必学之一的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程