如何使Android应用不被杀

看了一篇写的非常不错

Android 操作系统的内存回收机制 http://www.oschina.net/question/129540_64132

总结一下有一下几点:

  • 必须是非 persistent 进程,即非系统进程;
  • 必须是空进程,即进程中没有任何 activity 存在。如果杀死存在 Activity 的进程,有可能关闭用户正在使用的程序,或者使应用程序恢复的时延变大,从而影响用户体验;
  • 必须无 broadcast receiver。运行 broadcast receiver 一般都在等待一个事件的发生,用户并不希望此类程序被系统强制关闭;
  • 进程中 service 的数量必须为 0。存在 service 的进程很有可能在为一个或者多个程序提供某种服务,如 GPS 定位服务。杀死此类进程将使其他进程无法正常服务。

这个时候才会杀掉进程。

具体代码只粘贴一下,需要详细讲解请那片文章

final void trimApplications()
    {
        synchronized(this)
        {
            for(int i = mRemovedProcesses.size() - 1; i >= 0; i--)
            {
                ProcessRecord app = (ProcessRecord)mRemovedProcesses.get(i);
                if(app.activities.size() != 0 || app.curReceiver != null || app.services.size() != 0)
                    continue;
                Slog.i("ActivityManager", (new StringBuilder()).append("Exiting empty application process ").append(app.processName).append(" (").append(app.thread == null ? null : ((Object) (app.thread.asBinder()))).append(")\n").toString());
                if(app.pid > 0 && app.pid != MY_PID)
                {
                    EventLog.writeEvent(30023, new Object[] {
                        Integer.valueOf(app.pid), app.processName, Integer.valueOf(app.setAdj), "empty"
                    });
                    Process.killProcessQuiet(app.pid);
                } else
                {
                    try
                    {
                        app.thread.scheduleExit();
                    }
                    catch(Exception e) { }
                }
                cleanUpApplicationRecordLocked(app, false, true, -1);
                mRemovedProcesses.remove(i);
                if(app.persistent && app.persistent)
                    addAppLocked(app.info, false);
            }

            updateOomAdjLocked();
        }
    }


下面讲解一下自己的心得

1. 用Notification绑定Service,让Service优先级别高,不过,这样需要通知栏一直显示图标,具体代码

NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification n = new Notification(R.drawable.ic_launcher,
                "Hello,there!", System.currentTimeMillis());
        n.flags = Notification.FLAG_ONGOING_EVENT;
        Intent i = new Intent(this, MainActivity.class);
        i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_NEW_TASK);
        // PendingIntent
        PendingIntent contentIntent = PendingIntent.getActivity(this,
                R.string.app_name, i, PendingIntent.FLAG_UPDATE_CURRENT);

        n.setLatestEventInfo(this, "Hello,there!", "Hello,there,I'm john.",
                contentIntent);
        nm.notify(R.string.app_name, n);

2.待续

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值