编程语言
首页 > 编程语言> > java – 如何在android中的设备启动时启动服务?

java – 如何在android中的设备启动时启动服务?

作者:互联网

参见英文答案 > Auto start application after boot completed in Android                                    5个
我正在创建一个应用程序,它需要一直运行的服务,即使应用程序关闭,从设备启动到设备关闭.这可以在android中完成吗?

解决方法:

>首先,您需要获得许可

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

>然后创建一个广播接收器

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class Startup extends BroadcastReceiver {

    public Startup() {
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        // start your service here
        context.startService(new Intent(context, SERVICE.class));
    }

}

>在清单中注册此BroadCast Receiver

<receiver android:name="YOUR_PACKAGE.Startup" >
    <!-- This intent filter receives the boot completed event -->
    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
</receiver>

Note: A service too is not guaranteed to run from device boot to device
shut down, as in extreme cases the Android system may kill the service
also to gain additional memory.

标签:java,android,android-launcher
来源: https://codeday.me/bug/20190718/1491769.html