gpt4 book ai didi

android - 未绑定(bind)的服务在 Activity 被终止时被销毁

转载 作者:行者123 更新时间:2023-11-29 00:12:21 25 4
gpt4 key购买 nike

我想创建一个即使在应用程序被终止时也能运行的服务,所以我创建了一个未绑定(bind)的服务,这样它就不会绑定(bind)到 Activity 生命周期。但是每次我通过长按和滑动来终止应用程序时,该服务也会被终止。有人可以帮助我吗?谢谢

服务

public class MyService extends Service {

public GCMNotificationIntentService() {
}

@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "Service binded");
return null;
}

@Override
public boolean onUnbind(Intent intent) {
Log.d(TAG, "Service unbound");
return super.onUnbind(intent);
}

@Override
public void onCreate() {
Log.d(TAG, "Service created");
super.onCreate();
}

@Override
public void onDestroy() {
Log.d(TAG, "Service destoryed");
super.onDestroy();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {

Log.d(TAG, "Service started");

Thread readerThread = new Thread(new Runnable() {
@Override
public void run() {

while(true) {
Log.d(TAG, "Thread present");
try {
// thread to sleep for 1000 milliseconds
Thread.sleep(3000);
} catch (Exception e) {
System.out.println(e);
}
}
}
});
readerThread.start();

return super.onStartCommand(intent, flags, startId);
}

}

我从这样的 Activity 中调用它

startService(新 Intent (MyService.class.getName()));

服务运行良好,直到应用程序处于后台或前台,但当我很长时间按住并扫一扫应用程序,服务也会停止并出现这样的崩溃消息

计划在 1000 毫秒内重启崩溃的服务 com.net.gs.MyService

I/ActivityManager(1160): 强制停止服务 ServiceRecord{44989bf0 u0 com.net.gs.MyService}

最佳答案

// Display sticky notification using below function in notification-bar.   
private static final int NOTIFICATION_ID=1;

private void displayNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(
this).setSmallIcon(R.drawable.ic_launcher).setContentTitle(
"Player");
builder.setContentText("content text");

if (getFileStructure() != null) {
String title = Utils.filter(getFileStructure().getTitle());
if (title.length() > 45)
title = title.substring(0, 44);
builder.setContentText(Utils.filter(title));
}
Intent resultIntent = new Intent(PlayerService.this, MainActivity.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(
PlayerService.this, 0, resultIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
builder.setAutoCancel(false);
NotificationManager nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nManager.notify(NOTIFICATION_ID, builder.build());
startForeground(NOTIFICATION_ID, builder.build());
}

关于android - 未绑定(bind)的服务在 Activity 被终止时被销毁,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29293364/

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