安卓启动服务在启动时,如何重新启动设备重新启动后的服务类?

我需要在启动时启动服务。我找了很多。他们正在谈论广播接收器。由于我是 Android 开发的新手,我对 Android 上的服务没有一个清晰的认识。请提供一些源代码。

159418 次浏览

你的接收器:

public class MyReceiver extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {


Intent myIntent = new Intent(context, YourService.class);
context.startService(myIntent);


}
}

您的 AndroidManifest.xml:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.broadcast.receiver.example"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name" android:debuggable="true">


<activity android:name=".BR_Example"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>


<!-- Declaring broadcast receiver for BOOT_COMPLETED event. -->
<receiver android:name=".MyReceiver" android:enabled="true" android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>


</application>


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


</manifest>

可以注册自己的应用程序服务以启动 当设备已经启动时自动执行。您需要这个,用于 例如,当您希望从 http 服务器接收推送事件并且 希望在新事件发生时立即通知用户 必须在服务开始之前手动启动活动..。

很简单,首先给你的应用程序许可 RECEIVE_BOOT_COMPLETED. Next you need to register a BroadcastReveiver. 我们称之为 BootCompletedInentReceiver。

Xml 现在应该是这样的:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jjoe64">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application>
<receiver android:name=".BootCompletedIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name=".BackgroundService"/>
</application>
</manifest>

As the last step you have to implement the Receiver. This receiver 刚刚开始你的背景服务。

package com.jjoe64;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;


import com.jjoe64.BackgroundService;


public class BootCompletedIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent pushIntent = new Intent(context, BackgroundService.class);
context.startService(pushIntent);
}
}
}

来自 http://www.jjoe64.com/2011/06/autostart-service-on-device-boot.html

还可以在 Manifest 中注册创建的服务,并将使用权限设置为

<application ...>
<service android:name=".MyBroadcastReceiver">
<intent-filter>
<action android:name="com.example.MyBroadcastReciver"/>
</intent-filter>
</service>
</application>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>

然后在布拉德斯特接受者呼叫您的服务

public class MyBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Intent myIntent = new Intent(context, MyService.class);
context.startService(myIntent);
}
}

首先将接收方注册到 Manif.xml 文件中:

    <receiver android:name="com.mileagelog.service.Broadcast_PowerUp" >
<intent-filter>
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>

然后为这个接收器写一个广播,比如:

public class Broadcast_PowerUp extends BroadcastReceiver {


@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();


if (action.equals(Intent.ACTION_POWER_CONNECTED)) {
Toast.makeText(context, "Service_PowerUp Started",
Toast.LENGTH_LONG).show();




} else if (action.equals(Intent.ACTION_POWER_DISCONNECTED)) {






Toast.makeText(context, "Service_PowerUp Stoped", Toast.LENGTH_LONG)
.show();
}
}
}

这里张贴的大多数解决方案都缺少一个重要的部分: 在没有唤醒锁的情况下进行操作,可能会导致您的服务在完成处理之前被终止。在另一个帖子里看到了这个答案,也回答了这个问题。

由于在 api 26中不推荐使用 WakefulBroadcastReceiver,因此建议使用 空气污染指数低于26

你需要获得一个唤醒锁。幸运的是,支持库为我们提供了一个类可以做到这一点:

public class SimpleWakefulReceiver extends WakefulBroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
// This is the Intent to deliver to our service.
Intent service = new Intent(context, SimpleWakefulService.class);


// Start the service, keeping the device awake while it is launching.
Log.i("SimpleWakefulReceiver", "Starting service @ " + SystemClock.elapsedRealtime());
startWakefulService(context, service);
}
}

then, in your Service, make sure to release the wake lock:

    @Override
protected void onHandleIntent(Intent intent) {
// At this point SimpleWakefulReceiver is still holding a wake lock
// for us.  We can do whatever we need to here and then tell it that
// it can release the wakelock.


...
Log.i("SimpleWakefulReceiver", "Completed service @ " + SystemClock.elapsedRealtime());
SimpleWakefulReceiver.completeWakefulIntent(intent);
}

不要忘记添加 WAKE _ LOCK 权限并在清单中注册接收器:

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


...


<service android:name=".SimpleWakefulReceiver">
<intent-filter>
<action android:name="com.example.SimpleWakefulReceiver"/>
</intent-filter>
</service>

您应该注册 BOOT _ COMPLETE 以及 REBOOT

<receiver android:name=".Services.BootComplete">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.REBOOT"/>
</intent-filter>
</receiver>

请检查 JobScheduler以上的26

WakeLock 是最好的选项,但是在 API 级别26中不推荐使用它 请检查 这个链接,如果你认为 api 水平高于26
Https://developer.android.com/reference/android/support/v4/content/wakefulbroadcastreceiver.html#startwakefulservice (android.content. Context,% 20android.content. intant)

上面说

从 Android O 开始,背景检查限制使得这个类不再普遍有用。(从收到广播开始启动服务通常是不安全的,因为您不能保证您的应用程序此时处于前台,因此可以这样做。)相反,开发人员应该使用 Android.app.job. JobScheduler来调度作业,这并不要求应用程序在调度作业时保持唤醒锁(系统将负责保持作业的唤醒锁)。

因此,它说考虑 JobScheduler
Https://developer.android.com/reference/android/app/job/jobscheduler

if it is to do something than to start and to keep it you can receive the broadcast ACTION_BOOT_COMPLETED

If it isn't about foreground pls check if an Accessibility service could do

另一种选择是从广播接收者启动一个活动,并在 onCreate ()中启动服务后完成它,因为较新的安卓版本不允许从接收者启动服务

要在 Android O或更多 ie OS > 28中重新启动服务,请使用此代码 < em > KOTLIN VERSION 1)在清单中添加权限

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

2) Create a Class and extend it with BroadcastReceiver

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.os.Build
import android.util.Log
import androidx.core.content.ContextCompat






class BootCompletedReceiver : BroadcastReceiver() {
override fun onReceive(context: Context, arg1: Intent?) {
Log.d("BootCompletedReceiver", "starting service...")
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
ContextCompat.startForegroundService(context, Intent(context, YourServiceClass::class.java))
} else {
context.startService(Intent(context, YourServiceClass::class.java))
}
}
}

3)像这样在应用程序标签下的 Manifest 文件中声明

<receiver android:name=".utils.BootCompletedReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>