多个广播接收器不被称为其不幸停止的应用程序

时间:2016-06-08 12:00:19

标签: android

当我连接充电器或断开充电器时,不幸的是,代码如下

public int onStartCommand(Intent intent, int flags, int startId)
    {

        connectreceiver myPowerConnectedBCReceiver = new connectreceiver();
        IntentFilter intentPowerOnFilter = new IntentFilter();
        intentPowerOnFilter.addAction("android.intent.action.ACTION_POWER_CONNECTED");
        registerReceiver(myPowerConnectedBCReceiver, intentPowerOnFilter);

        BroadcastReceiver PowerConnectedReceiver = new BroadcastReceiver() 
        {
            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(context,"Connected",Toast.LENGTH_LONG);
            }
        };


        //      Handle Power Off
        disconnectreceiver myPowerDisonnectedBCReceiver = new disconnectreceiver();
        IntentFilter intentPowerDisconnectedOnFilter = new IntentFilter();
        intentPowerDisconnectedOnFilter.addAction("android.intent.action.ACTION_POWER_DISCONNECTED");
        registerReceiver(myPowerDisonnectedBCReceiver, intentPowerDisconnectedOnFilter);

        BroadcastReceiver PowerDisconnectedReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                Toast.makeText(context, "Disconnected", Toast.LENGTH_LONG);
            }
        };
        return super.onStartCommand(intent, flags, startId);
    }

2 个答案:

答案 0 :(得分:0)

使用onCreate方法注册接收器。

答案 1 :(得分:0)

简单的方法是创建一个类 PowerConnectedReceiver 作为“BroadcastReceiver”并在清单文件中声明它,如下面的代码

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

PowerConnectedReceiver 代码,如下面的代码

public class PowerConnectedReceiverextends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
         //start your service or do what you want her
         //Intent service = new Intent(context, MyService.class);
         //context.startService(intent);
    }
}

我希望这可以帮助您