1. 程式人生 > >Android防止程序被殺

Android防止程序被殺

有時開啟新的app而記憶體不夠時,其它app可能會被Out Of Memory Killer清除防止程序不被殺死的辦法:

1.在AndroidManifest.xml檔案中設定persistent屬性為true

  <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:persistent="true">

2.在前端執行程式

    private void startForeground() {
        Notification notification = new NotificationCompat.Builder(this)
                .setContentTitle(getResources().getString(R.string.app_name))
                .setTicker(getResources().getString(R.string.app_name))
                .setContentText("Running")
                .setSmallIcon(R.drawable.unlock)
                .setContentIntent(null)
                .setOngoing(true)
                .build();
        startForeground(9999,notification);
    }