如何在应用程序关闭时启动服务

我想在应用程序关闭时启动服务。

java代码

public class AudioRecorder extends Service { public static final String SENDER_ID = "274211616343"; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onCreate() { Toast.makeText(this, " MyService Created ", Toast.LENGTH_LONG).show(); } @Override public int onStartCommand(Intent intent, int flags, int startId) { Toast.makeText(this, " MyService Started", Toast.LENGTH_LONG).show(); return START_STICKY; } } 

使用BroadcastReceiver 。 让它开始你的Service

你在评论中写道:“当应用程序关闭应用程序中的服务器端数据时,我想启动服务”

在这种情况下,你为什么不使用这样的AlarmManager(这是一个Kotlin):

 private fun startServiceAndExit() { val startService = Intent(appContext, YourService::class.java) val pendingIntentId = 123456 PendingIntent pendingIntent = PendingIntent.getService( appContext, pendingIntentId, intent, 0); val mgr = appContext.getSystemService(Context.ALARM_SERVICE) as AlarmManager mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, pendingIntent) System.exit(0) }