2015-10-15 124 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

相关问题