首页 > 解决方案 > starting background service while phone turn on with example code

问题描述

I need an app which will run always in the background and apps will start while phone is turn on. Please help me with example code. I already tried several code but it run on background while pressing button after start the apps

标签: android

解决方案


您需要接听BOOT_COMPLETED电话,然后启动服务。请按照以下步骤操作

第 1 步:创建您的服务

public class myService extends Service{
    public  myService(){}
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
    }
}

第 2 步:创建引导接收器

public class BootReceiver extends BroadcastReceiver {

    public void onReceive(final Context context, Intent intent) {
        Intent i = new Intent(context, RemindersService.class);
        context.startService(i);    
    }
}

第 3 步:将它们添加到应用程序内的清单

    <service
        android:name=".services.RemindersService"
        android:enabled="true"
        android:exported="true" />
    <receiver
        android:name=".services.BootReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </receiver>

第 4 步:在清单中添加权限

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

而已。快乐编码。请注意,在 android Oreo 中,您需要将服务作为前台启动

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        context.startForegroundService(i);
    } 

推荐阅读