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

时间:2017-12-19 08:38:48

标签: android service

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

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;
    }

    }

2 个答案:

答案 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)
}