我想在应用程序关闭时启动服务。
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;
}
}
答案 0 :(得分:1)
使用BroadcastReceiver
。让它开始你的Service
。
答案 1 :(得分:0)
您已在评论中写道:"我希望在应用程序关闭的应用程序关闭时启动该服务"
在这种情况下,为什么不使用这样的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)
}