我想在应用程序关闭时启动服务。
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)
}