安卓双进程保活的代码

简介: 首先要声明,双进程保活,不是为了解决被杀之后复活的问题。因为在新版本的安卓上,这个办法已经不灵了(也许有人有更好的办法?)。这里介绍这个双进程保活,是为在电视盒子上的应用。如果进程死了,有的系统会自动启动,有的就不会。而有的应用在电视盒子上必须常在线。

首先要声明,双进程保活,不是为了解决被杀之后复活的问题。因为在新版本的安卓上,这个办法已经不灵了(也许有人有更好的办法?)。这里介绍这个双进程保活,是为在电视盒子上的应用。如果进程死了,有的系统会自动启动,有的就不会。而有的应用在电视盒子上必须常在线。


 本文实现方法,与其他介绍的原理一样,代码更加精练。为什么呢?因为使用了继承。


 首先写一个AIDL:

package com.csdn;
interface IKeepAliveServiceConnection
{
    String getProcessName();
}

然后写一个父类:

package com.keepalive;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import com.newayte.nvideo.IKeepAliveServiceConnection;
public abstract class KeepAliveService extends Service
{
    private static final String TAG = KeepAliveService.class.getCanonicalName();
    private static final String KEEP_ALIVE = "keep-alive";
    private KeepAliveBinder mKeepAliveBinder;
    private KeepAliveServiceConnection mKeepAliveConnection;
    @Override
    public void onCreate()
    {
        super.onCreate();
        if (mKeepAliveBinder == null)
        {
            mKeepAliveBinder = new KeepAliveBinder();
            mKeepAliveConnection = new KeepAliveServiceConnection();
        }
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        bindService(getConnectionIntent(), mKeepAliveConnection, Context.BIND_IMPORTANT);
        Log.d(TAG, "onStartCommand()");
        /*PendingIntent contentIntent = PendingIntent.getService(this, 0, intent, 0);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setTicker("CSDN")
                .setContentIntent(contentIntent)
                .setContentTitle("TITLE")
                .setAutoCancel(true)
                .setContentText("CONTENT")
                .setWhen( System.currentTimeMillis());
        //把service设置为前台运行
        startForeground(startId, builder.build());*/
        return START_STICKY;
    }
    @Override
    public IBinder onBind(Intent intent)
    {
        //子类如果跟其他进程绑定时,从父类得到的binder不为空,说明是从保活服务启动的。
        Log.d(TAG, KEEP_ALIVE+"="+intent.getBooleanExtra(KEEP_ALIVE, false)+", "+intent);
        if (intent.getBooleanExtra(KEEP_ALIVE, false))
        {
            return mKeepAliveBinder;
        }
        return null;
    }
    private Intent getConnectionIntent()
    {
        Intent intent = new Intent(KeepAliveService.this, getPeerService());
        intent.putExtra(KEEP_ALIVE, true);
        return intent;
    }
    class KeepAliveBinder extends IKeepAliveServiceConnection.Stub
    {
        @Override
        public String getProcessName() throws RemoteException
        {
            return getServiceName();
        }
    }
    class KeepAliveServiceConnection implements ServiceConnection
    {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service)
        {
            Log.d(TAG, getPeerService().getCanonicalName()+"建立连接成功!");
        }
        @Override
        public void onServiceDisconnected(ComponentName name)
        {
            Log.d(TAG, getPeerService().getCanonicalName()+"服务进程已死。重新启动并建立链接。");
            //启动被干掉的
            KeepAliveService.this.startService(getConnectionIntent());
            KeepAliveService.this.bindService(getConnectionIntent(), mKeepAliveConnection, Context.BIND_IMPORTANT);
        }
    }
    /**
     * 这两个并不是必要的。
     * 考虑到子类,还是要有点代码的。
     *
     * @return
     */
    protected abstract String   getServiceName();
    protected abstract Class<?> getPeerService();
}

子类服务助手(怎么样?使用了继承,极为简单吧):

package com.keepalive;
public class AssistantServiceTv extends KeepAliveService
{
    @Override
    protected String   getServiceName()
    {
        return AssistantServiceTv.class.getCanonicalName();
    }
    @Override
    protected Class<?> getPeerService()
    {
        return NetworkServiceTv.class;
    }
}

主服务(注意onBind()的代码):

package com.keepalive;
public class NetworkServiceTv extends KeepAliveService
{
    @Override
    public IBinder onBind(Intent intent)
    {
        Log.d(TAG, "service onBind="+intent);
        IBinder binder = super.onBind(intent);
        if (null != binder)
        {
            return binder;
        }
        return mBinder;
    }
    @Override
    protected String   getServiceName()
    {
        return NetworkServiceTv.class.getCanonicalName();
    }
    @Override
    protected Class<?> getPeerService()
    {
        return AssistantServiceTv.class;
    }
}

在NetworkServiceTv中负责联网。这样即使其中一个进程因错误崩溃,也可以被启动再次联网。

目录
相关文章
|
18天前
|
Ubuntu 网络协议 Java
【Android平板编程】远程Ubuntu服务器code-server编程写代码
【Android平板编程】远程Ubuntu服务器code-server编程写代码
|
18天前
|
人工智能 IDE 开发工具
Studio Bot - 让 AI 帮我写 Android 代码
Studio Bot - 让 AI 帮我写 Android 代码
188 1
|
5天前
|
移动开发 监控 Android开发
构建高效Android应用:从内存优化到电池寿命代码之美:从功能实现到艺术创作
【5月更文挑战第28天】 在移动开发领域,特别是针对Android系统,性能优化始终是关键议题之一。本文深入探讨了如何通过细致的内存管理和电池使用策略,提升Android应用的运行效率和用户体验。文章不仅涵盖了现代Android设备上常见的内存泄漏问题,还提出了有效的解决方案,包括代码级优化和使用工具进行诊断。同时,文中也详细阐述了如何通过减少不必要的后台服务、合理管理设备唤醒锁以及优化网络调用等手段延长应用的电池续航时间。这些方法和技术旨在帮助开发者构建更加健壮、高效的Android应用程序。
|
16天前
|
存储 设计模式 监控
88 PM撸代码之【Android四大基本组件】
88 PM撸代码之【Android四大基本组件】
19 0
|
16天前
|
Java Android开发
82 PM撸代码之Android【绝顶高手排行榜】
82 PM撸代码之Android【绝顶高手排行榜】
6 0
|
16天前
|
达摩院 安全 Java
80 PM撸代码之Android【武侠讲封装、继承、多态】
80 PM撸代码之Android【武侠讲封装、继承、多态】
24 0
|
16天前
|
算法 Java BI
79 PM撸代码之Android【武侠篇:面向对象基础】
79 PM撸代码之Android【武侠篇:面向对象基础】
17 0
|
16天前
|
XML 编解码 算法
76 PM撸代码之Android【宏观篇】
76 PM撸代码之Android【宏观篇】
21 0
|
16天前
|
XML 前端开发 Android开发
Android架构设计——MVC(1),Android多进程从头讲到尾
Android架构设计——MVC(1),Android多进程从头讲到尾
|
18天前
|
Ubuntu Android开发 数据安全/隐私保护
【Android平板编程】远程Ubuntu服务器Code-Server编程写代码
【Android平板编程】远程Ubuntu服务器Code-Server编程写代码

相关实验场景

更多