java - 应用程序崩溃后服务无法继续运行
问题描述
我的服务在应用程序启动时启动,但是当我从最近的应用程序中关闭应用程序时,它崩溃并停止绑定
我尝试在服务中使用线程,应用程序关闭后线程将继续,但它不起作用,我也在 onStartCommand 函数中返回 START_STICKY ,我无法理解问题是什么。
public class MyThread extends Thread {
@Override
public void run() {
while (true)
{
try {
this.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public int onStartCommand(final Intent intent,
final int flags,
final int startId) {
MyThread mt = new MyThread();
mt.start();
return START_STICKY;
}
我希望在我关闭应用程序并将其从最近的应用程序中删除后该服务继续。
解决方案
您需要创建状态栏通知以使您的服务前台服务并保持运行。您可以在此页面上阅读更多内容https://developer.android.com/guide/components/services
public class MyThread extends Thread {
@Override
public void run() {
while (true)
{
try {
this.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public int onStartCommand(final Intent intent,
final int flags,
final int startId) {
MyThread mt = new MyThread();
mt.start();
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent =
PendingIntent.getActivity(this, 0, notificationIntent, 0);
Notification notification =
new Notification.Builder(this, CHANNEL_DEFAULT_IMPORTANCE)
.setContentTitle(getText(R.string.notification_title))
.setContentText(getText(R.string.notification_message))
.setSmallIcon(R.drawable.icon)
.setContentIntent(pendingIntent)
.setTicker(getText(R.string.ticker_text))
.build();
startForeground(ONGOING_NOTIFICATION_ID, notification);
return START_STICKY;
}
推荐阅读
- android - 图标更改不适用于 SwitchPreference
- llvm - LLVM:将 alloca 作为函数参数传递
- java - 将文本从一项活动转移到另一项活动
- reactjs - Reactjs 使用 Latex 渲染几何图形
- nativescript - NativeScript:运行 TNS Doctor 时仍然出现“Android SDK 未安装错误”
- mysql - 当外键没有要引用的值时插入一行
- ionic-framework - Ionic Camera 生成的字符串 URL 太大而无法在 Firebase 中存储(作为字符串)
- docker - Docker-compose 容器无法相互发送请求
- flutter - Flutter AppBar Icon 在所有屏幕上都没有响应
- css - 在 npm 中运行前缀时遇到问题