为了创建一个在设备启动时就启动的服务,我采纳了描述这里和这里的建议。构建完成得很好,主活动也可以在Nexus-5虚拟设备上很好地启动。
但是,当我检查logcat输出以验证服务是否启动时,没有提到我在BackgroundService类中向logcat写入的文本BackgroundService。这使我相信,下面的代码没有正常工作。另外,在启动虚拟设备时,我没有看到Toast。我遗漏了什么?
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.alexander.bootservice">
<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">
<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:name="com.example.alexander.bootservice.BootCompletedIntentReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service android:name="com.example.alexander.bootservice.BackgroundService"/>
</application>
</manifest>广播接收机类
package com.example.alexander.bootservice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
/**
* Created by alexander on 13/06/16.
*/
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);
}
}
}服务类
package com.example.alexander.bootservice;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
/**
* Created by alexander on 13/06/16.
*/
public class BackgroundService extends Service {
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "OK", Toast.LENGTH_LONG).show();
super.onCreate();
Log.d("MYLOG", "onCreate has been called");
}
}发布于 2016-06-29 17:59:05
从您的android:permission="android.permission.RECEIVE_BOOT_COMPLETED"中删除<receiver>。这意味着,发送广播的人必须持有RECEIVE_BOOT_COMPLETED权限,这并不一定是事实。
发布于 2016-06-29 18:38:08
你的代码运行得很好。您之所以没有在logcat中看到"MYLOG“,是因为您希望它在您第一次在模拟器上安装应用程序时看到它。
您需要在设备上安装应用程序,并打开它一次,然后才能在每次启动完成时接收到动作android.intent.action.BOOT_COMPLETED的意图。如果你安装了这个应用程序而没有打开它(可能是亚行在真实的手机上安装),那么在重新启动你的应用程序时,你的应用程序将不会有意图动作android.intent.action.BOOT_COMPLETED。
要进行测试,请在模拟器上安装应用程序并打开它。然后在终端中使用adb shell am broadcast -a android.intent.action.BOOT_COMPLETED命令发送此操作。您的设备将重新启动,您将能够看到日志和您的祝酒词。如果有任何混淆,请告诉我。
是的,您应该按照其中一个答案中的建议,将android:permission="android.permission.RECEIVE_BOOT_COMPLETED“从接收器中删除,这是不需要的。
https://stackoverflow.com/questions/38106920
复制相似问题