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

问题描述 投票:2回答:2

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

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

    }
android service
2个回答
1
投票

使用BroadcastReceiver。让它开始你的Service


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)
}
© www.soinside.com 2019 - 2024. All rights reserved.