Android 2个Service实现相互保活,通过bindservice来实现,不通过广播实现

1,093次阅读
没有评论

1,实现原理:启动2个Service,相互绑定监听,当A Service监听到连接断开的时候,说明B服务可能被 Kill掉了,这时需要重新开启A服务,同样B服务的监听断掉了,重新启动A服务。A,B两个服务都是单独的进程,需要使用AIDL来通讯。

2,A服务源码:

public class StepService extends Service {

String TAG="StepService";
private int NOTICE_ID=1000;
@Override
public void onCreate() {
    super.onCreate();
    LogUtil.d(TAG,"StepService 被创建:"+new Date().toLocaleString());
    startGuardService();
}

void startGuardService(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            Intent service=new Intent("com.foxconn.androidlib.service.GuardService");
            String packageName = "com.foxconn.androidlib";//需要开启服务的app包名
            String serviceClassName = packageName + "com.foxconn.androidlib.service.GuardService";//服务的类名全限定名
            service.setComponent(new ComponentName(packageName, "com.foxconn.androidlib.service.GuardService"));
            startService(service);
            bindService(service,mServiceConnection, Context.BIND_AUTO_CREATE);
        }
    }).start();
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
    return new ProcessConnection.Stub() {
    };
}

private Notification getNotification(){
    String channelId = "notification_simple";
    Notification notification;
    if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        NotificationChannel channel = new NotificationChannel(channelId, "simple", NotificationManager.IMPORTANCE_DEFAULT);
        manager.createNotificationChannel(channel);
        notification = new NotificationCompat.Builder(this, channelId)
                .setContentTitle("保持前台运行")

// .setContentText(“This is content text”)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.build();
// manager.notify(1, notification);
}else{
NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notification = new NotificationCompat.Builder(this, channelId)
.setContentTitle(“保持前台运行”)
// .setContentText(“This is content text”)
.setWhen(System.currentTimeMillis())
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
.build();
// manager.notify(1, notification);
}
return notification;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

// startForeground(1, new Notification());
//绑定建立链接
return super.onStartCommand(intent,flags,startId);
}

private ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        //链接上
        Log.d(TAG, "StepService:建立链接");
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        LogUtil.d(TAG,"StepService 断开连接:"+new Date().toLocaleString());
        //断开链接

// startService(new Intent(StepService.this, GuardService.class));
startGuardService();
}
};

@Override
public void onDestroy() {

// releaseLock();
LogUtil.d(TAG,”StepService 销毁:”+new Date().toLocaleString());
unbindService(mServiceConnection);
super.onDestroy();
}

private PowerManager.WakeLock mWakeLock;
/**
 * 同步方法 得到休眠锁
 *
 * @param context
 * @return
 */
synchronized private void getLock(Context context) {
    if (mWakeLock == null) {
        PowerManager mgr = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        mWakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, StepService.class.getName());
        mWakeLock.setReferenceCounted(true);
        Calendar c = Calendar.getInstance();
        c.setTimeInMillis((System.currentTimeMillis()));
        int hour = c.get(Calendar.HOUR_OF_DAY);
        if (hour >= 23 || hour <= 6) {
            mWakeLock.acquire(5000);
        } else {
            mWakeLock.acquire(300000);
        }
    }
    Log.v(TAG, "get lock");
}

synchronized private void releaseLock()
{
    if(mWakeLock!=null){
        if(mWakeLock.isHeld()) {
            mWakeLock.release();
            Log.v(TAG,"release lock");
        }

        mWakeLock=null;
    }
}

}

3,B服务的源源码如下:

public class GuardService extends Service {
String TAG=”GuardService”;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return new ProcessConnection.Stub() {
};
}

@Override
public void onCreate() {
    super.onCreate();
    LogUtil.d(TAG,"GuardService 创建:"+new Date().toLocaleString());
    startStepService();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

// startForeground(1, new Notification());
//绑定建立链接

    return super.onStartCommand(intent,flags,startId);
}

void startStepService(){
    new Thread(new Runnable() {
        @Override
        public void run() {
            Intent service=new Intent("com.foxconn.androidlib.service.StepService");
            String packageName = "com.foxconn.androidlib";//需要开启服务的app包名
            String serviceClassName = packageName + ".StepService";//服务的类名全限定名
            service.setComponent(new ComponentName(packageName, "com.foxconn.androidlib.service.StepService"));
            startService(service);
            bindService(service,mServiceConnection, Context.BIND_AUTO_CREATE);
        }
    }).start();
}

private ServiceConnection mServiceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        //链接上
        Log.d("test", "GuardService:建立链接");
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        LogUtil.d(TAG,"GuardService 断开链接:"+new Date().toLocaleString());
        //断开链接
        startStepService();
    }
};

@Override
public void onDestroy() {
    super.onDestroy();
    LogUtil.d(TAG,"GuardService 销毁:"+new Date().toLocaleString());
    unbindService(mServiceConnection);
}

}

4,AIDL文件如下:

interface ProcessConnection {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
}
5,AndroidManifest.xml 代码如下:

    <service
        android:name="com.foxconn.androidlib.service.StepService"
        android:exported="true"
        android:process=":istep.service">
        <intent-filter>
            <action android:name="com.foxconn.androidlib.service.StepService"/>
        </intent-filter>
    </service>

    <service
        android:name="com.foxconn.androidlib.service.GuardService"
        android:exported="true"
        android:process=":GuardService">
        <intent-filter>
            <action android:name="com.foxconn.androidlib.service.GuardService"/>
        </intent-filter>
    </service>

6,启动Service:

Intent service = new Intent(“com.foxconn.androidlib.service.StepService”);
String packageName = “com.foxconn.androidlib”;//需要开启服务的app包名
String serviceClassName = packageName + “.StepService”;//服务的类名全限定名
service.setComponent(new ComponentName(packageName, “com.foxconn.androidlib.service.StepService”));
startService(service);
Intent service2 = new Intent(“com.foxconn.androidlib.service.GuardService”);
service2.setComponent(new ComponentName(packageName, “com.foxconn.androidlib.service.GuardService”));
startService(service2);

正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 0
评论(没有评论)

文心AIGC

2023 年 9 月
 123
45678910
11121314151617
18192021222324
252627282930  
文心AIGC
文心AIGC
人工智能ChatGPT,AIGC指利用人工智能技术来生成内容,其中包括文字、语音、代码、图像、视频、机器人动作等等。被认为是继PGC、UGC之后的新型内容创作方式。AIGC作为元宇宙的新方向,近几年迭代速度呈现指数级爆发,谷歌、Meta、百度等平台型巨头持续布局
文章搜索
热门文章
潞晨尤洋:日常办公没必要上私有模型,这三类企业才需要 | MEET2026

潞晨尤洋:日常办公没必要上私有模型,这三类企业才需要 | MEET2026

潞晨尤洋:日常办公没必要上私有模型,这三类企业才需要 | MEET2026 Jay 2025-12-22 09...
面向「空天具身智能」,北航团队提出星座规划新基准丨NeurIPS’25

面向「空天具身智能」,北航团队提出星座规划新基准丨NeurIPS’25

面向「空天具身智能」,北航团队提出星座规划新基准丨NeurIPS’25 鹭羽 2025-12-13 22:37...
钉钉又发新版本!把 AI 搬进每一次对话和会议

钉钉又发新版本!把 AI 搬进每一次对话和会议

钉钉又发新版本!把 AI 搬进每一次对话和会议 梦晨 2025-12-11 15:33:51 来源:量子位 A...
5天连更5次,可灵AI年末“狂飙式”升级

5天连更5次,可灵AI年末“狂飙式”升级

5天连更5次,可灵AI年末“狂飙式”升级 思邈 2025-12-10 14:28:37 来源:量子位 让更大规...
商汤Seko2.0重磅发布,合作短剧登顶抖音AI短剧榜No.1

商汤Seko2.0重磅发布,合作短剧登顶抖音AI短剧榜No.1

商汤Seko2.0重磅发布,合作短剧登顶抖音AI短剧榜No.1 十三 2025-12-15 14:13:14 ...
最新评论
ufabet ufabet มีเกมให้เลือกเล่นมากมาย: เกมเดิมพันหลากหลาย ครบทุกค่ายดัง
tornado crypto mixer tornado crypto mixer Discover the power of privacy with TornadoCash! Learn how this decentralized mixer ensures your transactions remain confidential.
ดูบอลสด ดูบอลสด Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
Obrazy Sztuka Nowoczesna Obrazy Sztuka Nowoczesna Thank you for this wonderful contribution to the topic. Your ability to explain complex ideas simply is admirable.
ufabet ufabet Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
ufabet ufabet You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!
ufabet ufabet Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
热评文章
读懂2025中国AI走向!公司×产品×人物×方案,最值得关注的都在这里了

读懂2025中国AI走向!公司×产品×人物×方案,最值得关注的都在这里了

读懂2025中国AI走向!公司×产品×人物×方案,最值得关注的都在这里了 衡宇 2025-12-10 12:3...
5天连更5次,可灵AI年末“狂飙式”升级

5天连更5次,可灵AI年末“狂飙式”升级

5天连更5次,可灵AI年末“狂飙式”升级 思邈 2025-12-10 14:28:37 来源:量子位 让更大规...
戴尔 x OpenCSG,推出⾯向智能初创企业的⼀体化 IT 基础架构解决方案

戴尔 x OpenCSG,推出⾯向智能初创企业的⼀体化 IT 基础架构解决方案

戴尔 x OpenCSG,推出⾯向智能初创企业的⼀体化 IT 基础架构解决方案 十三 2025-12-10 1...
九章云极独揽量子位三项大奖:以“一度算力”重构AI基础设施云格局

九章云极独揽量子位三项大奖:以“一度算力”重构AI基础设施云格局

九章云极独揽量子位三项大奖:以“一度算力”重构AI基础设施云格局 量子位的朋友们 2025-12-10 18:...
乐奇Rokid这一年,一路狂飙不回头

乐奇Rokid这一年,一路狂飙不回头

乐奇Rokid这一年,一路狂飙不回头 梦瑶 2025-12-10 20:41:15 来源:量子位 梦瑶 发自 ...