连接"公共类MainActivity扩展BroadcastReceiver"到xml活动&叫那个

时间:2016-08-19 10:58:14

标签: android

我想当我的手机连接到AC或USB时显示Toast,但我无法使用,因为我不知道如何打电话,也不知道如何将它们附加到xml活动。

public class MainActivity extends BroadcastReceiver {

    @Override
    public void onReceive (Context context, Intent intent){

        int status = intent.getByteExtra(BatteryManager.EXTRA_PLUGGED, (byte) -1);
        boolean usbcharge = status == BatteryManager.BATTERY_PLUGGED_USB;
        boolean accharge = status == BatteryManager.BATTERY_PLUGGED_AC;

        if (usbcharge) {
            // Toast toast= Toast.makeText(getAbortBroadcast(), "its a usb charger",  Toast.LENGTH_SHORT );
            //  Toast.makeText(MainActivity.this, "hi", Toast.LENGTH_SHORT).show();

            Toast.makeText(context, "connected to the usb charger", Toast.LENGTH_LONG).show();
        }
        if (accharge) {
            Toast.makeText(context, "connected to the ac sharger", Toast.LENGTH_LONG).show();
        }
        Toast.makeText(context, "hi", Toast.LENGTH_LONG).show();
    }
}

1 个答案:

答案 0 :(得分:0)

请在清单文件中注册您的收件人 您的广播接收器是连接USB适配器时自动侦听。 所以在您的清单文件中注册您的广播接收器

<receiver android:name="yourpackagename.MyReciever"></receiver>

for more information about Broadcast receiver