# KeepAlive **Repository Path**: cmzl_ohos/keep-alive-ohos ## Basic Information - **Project Name**: KeepAlive - **Description**: openharmony保活 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 1 - **Created**: 2021-06-21 - **Last Updated**: 2021-08-31 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README # OhosKeepAlive #### 介绍 - 用于被杀死的服务自动重启 - 通过两个app的service相互绑定,监听service连接状态。当其中一个service被系统回收时,另一个service监听到断开消息,试图重启对方app的service;从而防止service被系统回收。 #### 使用说明 1.通过两个app的service相互绑定,监听service连接状态 ``` // 创建连接回调实例 private IAbilityConnection connection = new IAbilityConnection() { // 连接到Service的回调 @Override public void onAbilityConnectDone(ElementName elementName, IRemoteObject iRemoteObject, int resultCode) { HiLog.error(TAG, "RemoteService::onAbilityConnectDone"); mIsBound = true; iMyIdlInterface = MyIdlInterfaceStub.asInterface(iRemoteObject); try { iMyIdlInterface.bindSuccess(); } catch (RemoteException e) { HiLog.error(TAG, "RemoteService::" + e.getMessage()); HiLog.error(TAG, "RemoteService::" + Arrays.toString(e.getStackTrace())); } } // 断开与Service连接的回调 @Override public void onAbilityDisconnectDone(ElementName elementName, int resultCode) { mIsBound = false; HiLog.error(TAG, "RemoteService::onAbilityDisconnectDone"); createTransferAbility(); } }; ``` ``` private MyIdlInterfaceStub stub = new MyIdlInterfaceStub("com.wuzy.aidlserver.IMyIdlInterface") { @Override public void bindSuccess() throws RemoteException { HiLog.error(TAG, "RemoteService: bindSuccess"); } @Override public void unbind() throws RemoteException { getApplicationContext().disconnectAbility(connection); HiLog.error(TAG, "RemoteService: disconnectAbility"); } }; ``` 2.在config.json中配置权限 - 为了使service被其他app访问,记得设置"visible": true - APP AIDLServer ``` { "name": "com.wuzy.aidlserver.RemoteService", "icon": "$media:icon", "description": "$string:remoteservice_description", "type": "service", "visible": true, "exported": true, "enabled": true } ``` - APP AIDLClient ``` { "name": "com.wuzy.aidlclient.LocalService", "icon": "$media:icon", "description": "$string:localservice_description", "type": "service", "visible": true, "exported": true, "enabled": true } ``` 3.去掉TransferAbility启动动画,隐藏TransferAbility页面 ``` startAbility(newIntent); setTransitionAnimation(0,0); ``` ``` { "orientation": "unspecified", "name": "com.wuzy.aidlclient.TransferAbility", "icon": "$media:icon", "description": "$string:transferability_description", "label": "$string:app_name", "type": "page", "launchType": "standard", "skills": [ { "actions": [ "com.wuzy.aidlclient.TransferAbility.FROM_SELF", "com.wuzy.aidlclient.TransferAbility.FROM_OTHER" ] } ], "metaData": { "customizeData": [ { "name": "hwc-theme", "value": "androidhwext:style/Theme.Emui.Translucent.NoTitleBar" } ] } } ``` ``` ```