我尝试了许多不同的示例,经过一段时间(长时间),我终于设法(几乎)从 BroadcastReceiver 接收日志,之后通知(通过服务)。尽管如此,问题仍然存在。
当我安装 apk 或构建它并在 USB 上运行它时,BroadcastReceiver 没有收到意图。我尝试手动运行应用程序数十次,然后重新启动(打开/关闭)我的手机 - 没有。之后,我尝试使用 adb shell 对其进行调试:
adb shell am 广播 -a android.intent.action.BOOT_COMPLETED -n com.myapp.example/.BootCompletedReceiver
而且,瞧!有效。我检查了重新启动 - 它有效!在那之后,我重新安装了应用程序,再次 - 没有工作。在我尝试使用 adb shell 之后 - 再次,一切正常。像它这样的接缝应该可以工作,但只有在我第一次从上面运行 adb shell 命令之后。
我没有尝试使用 AVD(它在我的机器上太慢),只是使用我的 HTC ONE(我还检查了 HTC ONE 问题,知道这是某些版本的 HTC 手机的问题 - 没有任何帮助)。
这是我的清单:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.myapp.example" >
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppThemeWhiteActionBar" >
<activity
android:name=".MainActivity"
android:label="@string/app_name"
android:screenOrientation="portrait"
android:theme="@style/AppThemeWhite" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
...
<receiver android:name=".BootCompletedReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.QUICKBOOT_POWERON" />
</intent-filter>
</receiver>
<receiver android:name=".util.AlarmReceiver"/>
<service android:name=".NotifyingDailyService" >
</service>
</application>
这些是 BootCompletedReceiver 和 NotifyingDailyService (几乎与这里的许多示例相同):
public class BootCompletedReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent arg1) {
Log.w("boot_broadcast_poc", "starting service...");
context.startService(new Intent(context, NotifyingDailyService.class));
}
}
public class NotifyingDailyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent pIntent, int flags, int startId) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification.Builder builder = new Notification.Builder(this);
builder.setSmallIcon(R.drawable.ic_launcher);
builder.setContentTitle(getString(R.string.random_string));
builder.setContentText(getString(R.string.random_string));
builder.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_LIGHTS);
mNotificationManager.notify(12345, builder.build());
return super.onStartCommand(pIntent, flags, startId);
}
}