代码之家  ›  专栏  ›  技术社区  ›  NPike

如何检测电源连接状态?

  •  23
  • NPike  · 技术社区  · 15 年前

    5 回复  |  直到 15 年前
        1
  •  9
  •   CommonsWare    15 年前

    建立一个 BroadcastReceiver 对于 ACTION_BATTERY_CHANGED Intent extra将告诉您充电状态是什么—请参阅 BatteryManager 详情。

        2
  •  71
  •   MBH OregonGhost    9 年前

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <receiver android:name=".receiver.PlugInControlReceiver">
            <intent-filter>
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
            </intent-filter>
        </receiver>
    </application>
    

    在代码中

    public class PlugInControlReceiver extends BroadcastReceiver {
       public void onReceive(Context context , Intent intent) {
           String action = intent.getAction();
    
           if(action.equals(Intent.ACTION_POWER_CONNECTED)) {
               // Do something when power connected
           }
           else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)) {
               // Do something when power disconnected
           }
       }
    }
    
        3
  •  5
  •   iman kazemayni    8 年前

    public class PowerUtil {
        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;
        }
    }
    
        4
  •  2
  •   Jesse Palmer    7 年前

    读取值here:ex.

    通过android shell:

    cat /sys/class/power_supply/usb/online
    

    cat/sys/class/电源/ac/在线

    1=已连接,0=未连接。反映交流连接状态。

    下面是一个Android API示例:

    File aFile = new File("/sys/class/power_supply/ac/online");
    try {
        BufferedReader br = new BufferedReader(new FileReader(aFile));
        char aBuff[] = new char[1];
        int aCount = br.read(aBuff,0, 1);
        Log.d(TAG, "run: Res:"+new String(aBuff));
    }catch(Exception e){
        Log.d(TAG, "Exception:Error:run: "+e.toString());
    }
    
        5
  •  -2
  •   Girish Sasidharan    12 年前

    还有一件事,您必须检查清单中是否有错误--->应用程序。 如果然后单击显示错误的字段,只需单击链接“Name” 然后出现添加类的对话框。添加类并在类中复制接收时的代码。即上述代码应复制到类文件中,而不是主要活动中。 谢谢