检查设备是否插入

时间:2021-07-11 07:20:57

My app has a broadcast receiver to listen for changes to ACTION_POWER_CONNECTED, and in turn flag the screen to stay on.

我的应用程序有一个广播接收器来监听ACTION_POWER_CONNECTED的更改,并将屏幕标记为继续。

What I am missing is the ability for the app to check the charging status when it first runs. Can anyone please help me with code to manually check charging status?

我所缺少的是应用程序在第一次运行时检查充电状态的能力。请问有谁可以帮我用代码手动检查充电状态吗?

9 个解决方案

#1


121  

Thanks to CommonsWare here is the code I wrote.

感谢CommonsWare,这是我写的代码。

public class Power {
    public static boolean isConnected(Context context) {
        Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;
    }
}

if (Power.isConnected(context)) {
    ...
}

or the Kotlin version

或芬兰湾的科特林的版本

object Power {
    fun isConnected(context: Context): Boolean {
        val intent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
        val plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
        return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS
    }
}

Note BatteryManager.BATTERY_PLUGGED_WIRELESS requires API Level 17 (Jelly Bean MR1). For backward compatibility change the last line to:

注意BatteryManager。BATTERY_PLUGGED_WIRELESS需要API级别17 (Jelly Bean MR1)。对于向后兼容性,将最后一行更改为:

return plugged == BatteryManager.BATTERY_PLUGGED_AC || 
       plugged == BatteryManager.BATTERY_PLUGGED_USB || 
       (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && 
        plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS)

http://developer.android.com/training/monitoring-device-state/battery-monitoring.html

http://developer.android.com/training/monitoring-device-state/battery-monitoring.html

#2


28  

public static boolean isPlugged(Context context) {
    boolean isPlugged= false;
    Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    isPlugged = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
    if (VERSION.SDK_INT > VERSION_CODES.JELLY_BEAN) {
        isPlugged = isPlugged || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;
    }
    return isPlugged;
}

A minor update to support Wireless charging.

一个支持无线充电的小更新。

#3


25  

Call registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)). This will return an Intent that has extras defined on BatteryManager to let you know if it is plugged in or not.

调用registerReceiver(null,新IntentFilter(Intent.ACTION_BATTERY_CHANGED))。这将返回一个意图,该意图在电池管理器上有额外的定义,让您知道它是否插入。

This works because Intent.ACTION_BATTERY_CHANGED is a sticky broadcast.

因为这样的意图。ACTION_BATTERY_CHANGED是粘性广播。

#4


5  

Your answer is in the android reference !

你的答案是在android系统中!

Here is the example code:

下面是示例代码:

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                 status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

#5


4  

On Android M+ you can use the BatteryManager service via getSystemService(BATTERY_SERVICE). On devices running pre-M you can use a sticky broadcast as mentioned by others. Example:

在Android M+中,可以通过getSystemService(BATTERY_SERVICE)使用BatteryManager服务。在运行pre-M的设备上,您可以使用别人提到的粘性广播。例子:

public static boolean isCharging(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        BatteryManager batteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
        return batteryManager.isCharging();
    } else {
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent intent = context.registerReceiver(null, filter);
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        if (status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL) {
            return true;
        }
    }
    return false;
}

#6


3  

Easy way is to use an intent filter ACTION_BATTERY_CHANGED

简单的方法是使用一个意图过滤器ACTION_BATTERY_CHANGED

public void checkBatteryState(View sender) {
    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = registerReceiver(null, filter);

    int chargeState = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    String strState;

    switch (chargeState) {
        case BatteryManager.BATTERY_STATUS_CHARGING:
        case BatteryManager.BATTERY_STATUS_FULL:
            strState = "charging";
            break;
        default:
            strState = "not charging";
    }

    TextView tv = (TextView) findViewById(R.id.textView);
    tv.setText(strState);
}

#7


2  

try this:

试试这个:

public class PowerConnectionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, ifilter);


        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging =    status == BatteryManager.BATTERY_STATUS_CHARGING ||
                                status == BatteryManager.BATTERY_STATUS_FULL;

        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge   = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge    = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;


        if (batteryStatus != null) {
            int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            float batteryPct = level / (float) scale;
        }


    }//end onReceive


}//end PowerConnectionReceiver

#8


2  

BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String action = intent.getAction();
        if(action.equalsIgnoreCase(ACTION_POWER_CONNECTED))
        {


                if(chargerConnected != null )
                {
                    chargerConnected.setText("Cable Connected");
                }
                if(chargerImage != null )
                {
                    chargerImage.setImageDrawable(getResources().getDrawable(R.drawable.usb));
                }

        }else if(action.equalsIgnoreCase(ACTION_POWER_DISCONNECTED))
        {


                if(chargerConnected != null )
                {
                    chargerConnected.setText("NOT CHARGE");
                }
                if(chargerImage != null )
                {
                    chargerImage.setImageDrawable(getResources().getDrawable(R.drawable.battery_icon));
                }

            try {

                Toast.makeText(context, "Power Cable Disconnected", Toast.LENGTH_SHORT).show();
            }catch (Exception e){e.printStackTrace();}

        }
    }
};

#9


1  

It's a sticky intent, you don't need to register a BroadcastReceiver—by simply calling registerReceiver passing in null as the receiver as shown in the next snippet, the current battery status intent is returned. You could pass in an actual BroadcastReceiver object here, but we'll be handling updates in a later section so it's not necessary.

这是一个棘手的意图,您不需要注册一个broadcastreceiver—只需调用registerReceiver,将其作为接收者传入null作为接收者,如下面的代码片段所示,当前的电池状态意图将被返回。您可以在这里传递一个实际的广播接收器对象,但是我们将在后面的部分中处理更新,所以这不是必需的。

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

You can extract both the current charging status and, if the device is being charged, whether it's charging via USB or AC charger:

您可以提取当前的充电状态,如果设备正在充电,无论是通过USB还是交流充电器充电:

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                     status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

The BatteryManager broadcasts an action whenever the device is connected or disconnected from power. It's important to receive these events even while your app isn't running—particularly as these events should impact how often you start your app in order to initiate a background update—so you should register a BroadcastReceiver in your manifest to listen for both events by defining the ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED within an intent filter.

当设备连接或断开电源时,BatteryManager会广播一个动作。接收这些事件很重要即使应用程序并不像这些事件running-particularly应该影响你多久开始应用程序以启动背景update-so你应该注册一个BroadcastReceiver清单侦听事件通过定义ACTION_POWER_CONNECTED和ACTION_POWER_DISCONNECTED在一个意图过滤器。

<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>

Within the associated BroadcastReceiver implementation, you can extract the current charging state and method as described in the previous step.

在关联的BroadcastReceiver实现中,可以提取上一步中描述的当前充电状态和方法。

public class PowerConnectionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                            status == BatteryManager.BATTERY_STATUS_FULL;

        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    }
}

#1


121  

Thanks to CommonsWare here is the code I wrote.

感谢CommonsWare,这是我写的代码。

public class Power {
    public static boolean isConnected(Context context) {
        Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;
    }
}

if (Power.isConnected(context)) {
    ...
}

or the Kotlin version

或芬兰湾的科特林的版本

object Power {
    fun isConnected(context: Context): Boolean {
        val intent = context.registerReceiver(null, IntentFilter(Intent.ACTION_BATTERY_CHANGED))
        val plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1)
        return plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS
    }
}

Note BatteryManager.BATTERY_PLUGGED_WIRELESS requires API Level 17 (Jelly Bean MR1). For backward compatibility change the last line to:

注意BatteryManager。BATTERY_PLUGGED_WIRELESS需要API级别17 (Jelly Bean MR1)。对于向后兼容性,将最后一行更改为:

return plugged == BatteryManager.BATTERY_PLUGGED_AC || 
       plugged == BatteryManager.BATTERY_PLUGGED_USB || 
       (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1 && 
        plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS)

http://developer.android.com/training/monitoring-device-state/battery-monitoring.html

http://developer.android.com/training/monitoring-device-state/battery-monitoring.html

#2


28  

public static boolean isPlugged(Context context) {
    boolean isPlugged= false;
    Intent intent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
    isPlugged = plugged == BatteryManager.BATTERY_PLUGGED_AC || plugged == BatteryManager.BATTERY_PLUGGED_USB;
    if (VERSION.SDK_INT > VERSION_CODES.JELLY_BEAN) {
        isPlugged = isPlugged || plugged == BatteryManager.BATTERY_PLUGGED_WIRELESS;
    }
    return isPlugged;
}

A minor update to support Wireless charging.

一个支持无线充电的小更新。

#3


25  

Call registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)). This will return an Intent that has extras defined on BatteryManager to let you know if it is plugged in or not.

调用registerReceiver(null,新IntentFilter(Intent.ACTION_BATTERY_CHANGED))。这将返回一个意图,该意图在电池管理器上有额外的定义,让您知道它是否插入。

This works because Intent.ACTION_BATTERY_CHANGED is a sticky broadcast.

因为这样的意图。ACTION_BATTERY_CHANGED是粘性广播。

#4


5  

Your answer is in the android reference !

你的答案是在android系统中!

Here is the example code:

下面是示例代码:

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                 status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

#5


4  

On Android M+ you can use the BatteryManager service via getSystemService(BATTERY_SERVICE). On devices running pre-M you can use a sticky broadcast as mentioned by others. Example:

在Android M+中,可以通过getSystemService(BATTERY_SERVICE)使用BatteryManager服务。在运行pre-M的设备上,您可以使用别人提到的粘性广播。例子:

public static boolean isCharging(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
        BatteryManager batteryManager = (BatteryManager) context.getSystemService(Context.BATTERY_SERVICE);
        return batteryManager.isCharging();
    } else {
        IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent intent = context.registerReceiver(null, filter);
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        if (status == BatteryManager.BATTERY_STATUS_CHARGING || status == BatteryManager.BATTERY_STATUS_FULL) {
            return true;
        }
    }
    return false;
}

#6


3  

Easy way is to use an intent filter ACTION_BATTERY_CHANGED

简单的方法是使用一个意图过滤器ACTION_BATTERY_CHANGED

public void checkBatteryState(View sender) {
    IntentFilter filter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
    Intent batteryStatus = registerReceiver(null, filter);

    int chargeState = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
    String strState;

    switch (chargeState) {
        case BatteryManager.BATTERY_STATUS_CHARGING:
        case BatteryManager.BATTERY_STATUS_FULL:
            strState = "charging";
            break;
        default:
            strState = "not charging";
    }

    TextView tv = (TextView) findViewById(R.id.textView);
    tv.setText(strState);
}

#7


2  

try this:

试试这个:

public class PowerConnectionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {

        IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
        Intent batteryStatus = context.registerReceiver(null, ifilter);


        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging =    status == BatteryManager.BATTERY_STATUS_CHARGING ||
                                status == BatteryManager.BATTERY_STATUS_FULL;

        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge   = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge    = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;


        if (batteryStatus != null) {
            int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
            float batteryPct = level / (float) scale;
        }


    }//end onReceive


}//end PowerConnectionReceiver

#8


2  

BroadcastReceiver receiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        String action = intent.getAction();
        if(action.equalsIgnoreCase(ACTION_POWER_CONNECTED))
        {


                if(chargerConnected != null )
                {
                    chargerConnected.setText("Cable Connected");
                }
                if(chargerImage != null )
                {
                    chargerImage.setImageDrawable(getResources().getDrawable(R.drawable.usb));
                }

        }else if(action.equalsIgnoreCase(ACTION_POWER_DISCONNECTED))
        {


                if(chargerConnected != null )
                {
                    chargerConnected.setText("NOT CHARGE");
                }
                if(chargerImage != null )
                {
                    chargerImage.setImageDrawable(getResources().getDrawable(R.drawable.battery_icon));
                }

            try {

                Toast.makeText(context, "Power Cable Disconnected", Toast.LENGTH_SHORT).show();
            }catch (Exception e){e.printStackTrace();}

        }
    }
};

#9


1  

It's a sticky intent, you don't need to register a BroadcastReceiver—by simply calling registerReceiver passing in null as the receiver as shown in the next snippet, the current battery status intent is returned. You could pass in an actual BroadcastReceiver object here, but we'll be handling updates in a later section so it's not necessary.

这是一个棘手的意图,您不需要注册一个broadcastreceiver—只需调用registerReceiver,将其作为接收者传入null作为接收者,如下面的代码片段所示,当前的电池状态意图将被返回。您可以在这里传递一个实际的广播接收器对象,但是我们将在后面的部分中处理更新,所以这不是必需的。

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

You can extract both the current charging status and, if the device is being charged, whether it's charging via USB or AC charger:

您可以提取当前的充电状态,如果设备正在充电,无论是通过USB还是交流充电器充电:

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                     status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

The BatteryManager broadcasts an action whenever the device is connected or disconnected from power. It's important to receive these events even while your app isn't running—particularly as these events should impact how often you start your app in order to initiate a background update—so you should register a BroadcastReceiver in your manifest to listen for both events by defining the ACTION_POWER_CONNECTED and ACTION_POWER_DISCONNECTED within an intent filter.

当设备连接或断开电源时,BatteryManager会广播一个动作。接收这些事件很重要即使应用程序并不像这些事件running-particularly应该影响你多久开始应用程序以启动背景update-so你应该注册一个BroadcastReceiver清单侦听事件通过定义ACTION_POWER_CONNECTED和ACTION_POWER_DISCONNECTED在一个意图过滤器。

<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>

Within the associated BroadcastReceiver implementation, you can extract the current charging state and method as described in the previous step.

在关联的BroadcastReceiver实现中,可以提取上一步中描述的当前充电状态和方法。

public class PowerConnectionReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
        boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                            status == BatteryManager.BATTERY_STATUS_FULL;

        int chargePlug = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
        boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
        boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;
    }
}