gpt4 book ai didi

android - 如何防止 Android 显示应用已停止消息

转载 作者:行者123 更新时间:2023-11-29 15:09:34 24 4
gpt4 key购买 nike

Android 会在内存不足时杀死一些服务。

像这样:

app stopped

我知道我可以使用前台服务来禁止android杀死我的服务

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 kill它时它可以不显示任何消息。

例如屏幕调光器

如何禁止android显示app stopped消息?

最佳答案

检查这个: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);
}
});

关于android - 如何防止 Android 显示应用已停止消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33141692/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com