2015-10-15 120 views
1

當內存不足時,Android會殺死一些服務。如何防止Android顯示應用程序停止消息

像這樣:

app stopped

我知道我可以使用前臺服務,禁止機器人殺死我的服務

public class MyService extends Service { 
    @Override 
    public IBinder onBind(Intent intent) { 
     return null; 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 
     try { 
      Notification notification = new Notification(R.mipmap.ic_launcher,"this is service", System.currentTimeMillis()); 

      Intent intent = new Intent(this, MainActivity.class); 
      PendingIntent contentIntent = PendingIntent.getActivity(this, 0,intent , 0); 
      notification.setLatestEventInfo(this, "myapp", "myservice", contentIntent); 
      notification.flags =Notification.FLAG_AUTO_CANCEL; 
      startForeground(123,notification); 
     } 
     catch(Exception e) 
     { 
      stopSelf(); 
     } 

    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     stopForeground(true); 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 
     return super.onStartCommand(intent, flags, startId); 
    } 
} 

但是,這將在屏幕上

我顯示通知寧願殺服務比顯示通知,但我也不想顯示停止的消息。

我發現了一些應用程序,當android殺死它時,它不會顯示任何消息。

例如Screen Dimmer

如何禁止android顯示應用程序停止的消息?

回答

2

檢查:https://stackoverflow.com/a/32229266/2965799

根據我使用了下面的代碼來處理異常。我想顯示另一條消息,所以我添加了我自己的消息,但是如果您使用他的答案,則不會有消息。

Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() { 
     @Override 
     public void uncaughtException(Thread paramThread, Throwable paramThrowable) { 

      new Thread() { 
       @Override 
       public void run() { 
        Looper.prepare(); 
        Toast.makeText(getActivity(),"Your message", Toast.LENGTH_LONG).show(); 
        Looper.loop(); 
       } 
      }.start(); 
      try 
      { 
       Thread.sleep(4000); // Let the Toast display before app will get shutdown 
      } 
      catch (InterruptedException e) { } 
      System.exit(2); 
     } 
    }); 
2

一種方法是使用您自己的自定義失敗代碼實施UncaughtExceptionHandler。安裝處理程序的API是這樣的:

public static void setDefaultUncaughtExceptionHandler(Thread.UncaughtExceptionHandler eh); 

is documented here。作爲一個非常簡單的例子:

import java.lang.Thread.UncaughtExceptionHandler; 

public final class CrashHandler implements UncaughtExceptionHandler { 
    @Override 
    public void uncaughtException(Thread thread, Throwable ex) { 
     android.util.Log.wtf("My app name", "Oops, caught it dying on me!"); 
    } 
} 

一個完整的工作示例是available here

相關問題