使用广播接收器自动启动服务不起作用?



我想在设备重新启动时自动启动我的服务。请不要将其标记为问题的副本,但鉴于那里的解决方案不起作用!

BootUpReceiver.java (BroadcastReceiver(

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import java.util.Map;

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

安卓清单.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.shubham.servic">
<uses-permission android:name="android.permission.INTERNET"></uses-permission>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"></uses-permission>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver
android:enabled="true"
android:name=".BootUpReceiver"
android:permission="android.permission.RECEIVE_BOOT_COMPLETED">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true">
</service>
</application>
</manifest>

主活动.java

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
String msg = "Android : ";
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d(msg, "The onCreate() event");
}
public void startService(View view) {
startService(new Intent(getBaseContext(), MyService.class));
}
// Method to stop the service
public void stopService(View view) {
stopService(new Intent(getBaseContext(), MyService.class));
}
}

但是服务仍然不会在重新启动时自行启动。

我还有一个不同的问题
我必须在固定的时间间隔内运行我的后台服务,到目前为止我已经在服务本身内部创建了一个AlarmManager,它在一段时间后一次又一次地调用相同的服务,如何实现"以更有效的方式以固定的时间间隔运行后台服务"?

由于Android Oreo中的限制,您无法在后台启动服务。 包含详细信息的来源

就像消息来源建议的那样,您应该改用计划作业。管理这一点的最简单方法是使用像android-job或workmanager这样的库。Android Job是由Evernote开发的一个经常使用的第三方库,但他们宣布支持将在Workmanager(仍处于alpha阶段(投入生产一段时间后结束。

最新更新