activity被杀service的通知还在但是播放停止了,调用者一死播放死,是用startservice启动的服务
基于Monster 组和GPT的调写:
当使用startService()方法启动服务时,该服务将在后台独立运行,直到其完成其工作或由客户端使用stopService()方法停止为止。如果调用startService()的组件(例如Activity)被销毁,服务仍将在后台运行。
但是,如果应用程序进程被杀死,服务也会随之终止,无论它是使用startService()还是bindService()方法启动的。当应用程序进程被杀死时,所有与该进程相关联的组件和服务都将被停止。
当应用程序进程被杀死时,即使使用startService()启动的服务也将停止。因此,需要在onDestroy()方法中停止所有在onCreate()中启动的线程或其他后台任务,以确保在服务停止时进行正确的清理工作。
此外,可以使用startForeground()方法将服务提升到前台,这样即使应用程序进程被杀死,服务也将继续在前台运行。这对于播放音乐等需要长时间运行的任务特别有用。
你好,service 虽然是开的一个子线程 后台播放的,但是它到生命周期是跟随 activity 的,也就是 service 是作为了守护线程,你如果有需求是想让 service 作为单独线程运行,那么可以考虑 开启新线程开启动,而不是直接通过 startservice 启动,也就是不要在 原本 activity 这个线程中启动。
你可以这样来做。
new Thread(() -> {
// 在新的线程中 调用
startservice();
}).run();
不知道你这个问题是否已经解决, 如果还没有解决的话:public class taskService extends Service {
/** 调用startService()启动服务时回调 */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//在Service服务类中发送广播消息给Activity活动界面
Intent intentBroadcastReceiver = new Intent();
intentBroadcastReceiver.setAction(MainActivity.ACTION_SERVICE_NEED);
sendBroadcast(intentBroadcastReceiver);
return super.onStartCommand(intent, flags, startId);
}
/** 通过bindService()绑定到服务的客户端 */
@Override
public IBinder onBind(Intent intent) {
return null;
}
}