我有一个MainActivity
什么都不做,一个名为BootCompletedIntentReceiver
的班级extends BroadcastReciever
和另一个名为MyServices
的班级extends Service
。我想要做的就是在设备开启后自动运行我的应用程序,由BootCompletedIntentReceiver
处理,然后启动Service
,显示吐司8次。但是,当我重启设备时,没有任何反应。我尽力解决这个问题。任何人都可以帮我找到我被卡住的地方
这是我的BootCompletedIntentReceiver
代码:
package com.anshuman.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
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, MyService.class);
context.startService(pushIntent);
}
}
}
这里是MyService
课程:
package com.anshuman.myapplication;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;
public class MyService extends Service {
@Override
public void onCreate() {
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId){
int a=2;
while (a<10) {
Toast.makeText(this, "onStartCommand", Toast.LENGTH_LONG).show();
a++;
}
return Service.START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
我的androidManifest文件:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.anshuman.myapplication">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<receiver android:name=".BootCompletedIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".MyService"/>
</application>
答案 0 :(得分:0)
代码工作正常问题是只有我的xiaomi设备没有使用此代码。