在Boot上启动BroadcastReceiver

时间:2015-11-25 12:00:28

标签: android broadcastreceiver

我在用户run code移动时尝试plug or unplug。 我想我可以通过创建一个广播接收器并将Manifest中的触发器设置为android.intent.action.BOOT_COMPLETED来实现这一点 然后从BOOT_COMPLETED RECEIVER启动一个服务并烘烤debugmessage 我从服务中为android.intent.action.ACTION_POWER_CONNECTEDandroid.intent.action.ACTION_POWER_DISCONNECTED启动了另一个广播接收器 Everthing运行良好并且调试消息被广播,服务执行ACTION_POWER广播接收器的启动过程但接收器没有触发。 任何人都知道如何解决它?

代码:
清单:

<application

    ...


    <receiver
        android:name="de.mrglue.nfc.BootReceiver"
        android:enabled="true"
        android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        </intent-filter>
    </receiver>

    <service android:name="de.mrglue.nfc.BootService" >
    </service>


</application>


<receiver android:name=".PowerConnectionReceiver">
    <intent-filter>
        <action android:name="android.intent.action.ACTION_POWER_CONNECTED"/>
        <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED"/>
    </intent-filter>
</receiver>




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

BootReceiver:

public class BootReceiver extends BroadcastReceiver{

@Override
public void onReceive(Context context, Intent intent) {
    //Can't toast here
    //Starting service
    context.startService(new Intent(context, BootService.class));
}

服务:

public class BootService extends Service{

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Starting second Receiver!",   Toast.LENGTH_LONG).show();
        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_BATTERY_CHANGED);
        registerReceiver(new PowerConnectionReceiver(), filter);
        Toast.makeText(this, "done!", Toast.LENGTH_LONG).show();
        stopSelf();
        return START_NOT_STICKY;
    }
}

BatteryReceiver:

public class PowerConnectionReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
            status == BatteryManager.BATTERY_STATUS_FULL;

        Toast.makeText(context, "CHARGE" + isCharging, Toast.LENGTH_LONG).show();

    }
}

2 个答案:

答案 0 :(得分:0)

您的清单文件中缺少手机状态权限 包括以下权限以阅读手机状态:

使用权限android:name =&#34; android.permission.READ_PHONE_STATE

答案 1 :(得分:0)

只需要干净且完全重启。

编辑否1
我将通过添加更多细节来尝试更清晰地回答我的问题:

安装新软件后,设备需要完全重启才能看到任何效果 新的Broadcastreceivers系统必须在不运行应用程序的情况下执行。调用意图android.intent.action.BOOT_COMPLETED不会对我认为的设备产生任何影响。