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

1,113次阅读
没有评论

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...
“昆山杯”第二十七届清华大学创业大赛决赛举行

“昆山杯”第二十七届清华大学创业大赛决赛举行

“昆山杯”第二十七届清华大学创业大赛决赛举行 一水 2025-12-22 17:04:24 来源:量子位 本届...
MiniMax海螺视频团队首次开源:Tokenizer也具备明确的Scaling Law

MiniMax海螺视频团队首次开源:Tokenizer也具备明确的Scaling Law

MiniMax海螺视频团队首次开源:Tokenizer也具备明确的Scaling Law 一水 2025-12...
真正面向大模型的AI Infra,必须同时懂模型、系统、产业|商汤大装置宣善明@MEET2026

真正面向大模型的AI Infra,必须同时懂模型、系统、产业|商汤大装置宣善明@MEET2026

真正面向大模型的AI Infra,必须同时懂模型、系统、产业|商汤大装置宣善明@MEET2026 量子位的朋友...
最新评论
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-12-18 08:57:11 ...
ISC.AI 2025创新百强颁奖典礼落幕,首发智能体专家驱动产业升级

ISC.AI 2025创新百强颁奖典礼落幕,首发智能体专家驱动产业升级

ISC.AI 2025创新百强颁奖典礼落幕,首发智能体专家驱动产业升级 量子位的朋友们 2025-12-18 ...
具身智能的数据难题,终于有了可规模化的解法

具身智能的数据难题,终于有了可规模化的解法

具身智能的数据难题,终于有了可规模化的解法 思邈 2025-12-18 14:20:44 来源:量子位 成立4...
医生版ChatGPT,估值120亿美元

医生版ChatGPT,估值120亿美元

医生版ChatGPT,估值120亿美元 Jay 2025-12-18 13:45:12 来源:量子位 Jay ...
国产AI芯片看两个指标:模型覆盖+集群规模能力 | 百度智能云王雁鹏@MEET2026

国产AI芯片看两个指标:模型覆盖+集群规模能力 | 百度智能云王雁鹏@MEET2026

国产AI芯片看两个指标:模型覆盖+集群规模能力 | 百度智能云王雁鹏@MEET2026 西风 2025-12-...