2010-07-16 77 views

回答

9

ACTION_BATTERY_CHANGED設置BroadcastReceiver。額外的Intent會告訴你充電狀態是什麼 - 詳情請參閱BatteryManager

+0

謝謝!無法輪詢此信息? – NPike 2010-07-21 02:41:31

+0

@NPike:看到這個[接受的答案](http://stackoverflow.com/questions/3997289/get-temperature-of-battery-on-android/3997349#3997349)的意見另一個問題 - 一個可以得到當前狀態使用在那裏顯示的方法而不訂閱。 – 2011-03-09 14:03:21

+1

Tu be precise:Intent ix = main.registerReceiver(null,new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); \t \t \t \t boolean plugged = ix!= null && ix.getIntExtra(「plugged」,0)!= 0; – mdiener 2013-09-16 14:23:29

59

在AndroidManifest.xml

<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

請注意,onReceive()方法應位於擴展BroadcastReceiver的PlugInControlReceiver類中。 – 2014-04-03 08:58:32

+1

感謝您的解釋@OdedBreiner – 2014-04-07 06:35:15

+0

但以上解決方案不適用於VIVO和OPPO手機 – 2017-05-29 05:51:27

-1

還有一件事你必須檢查是否有明顯錯誤--->應用程序。 如果然後點擊顯示錯誤的字段,只需點擊鏈接「名稱」 然後出現對話框添加一個類。添加類並在類中複製接收的代碼。即上面的代碼應該複製到類文件中而不是主要活動中。 謝謝 Pzycoderz

1

另一種方式是使用電池管理器。爲此,我可用於API> = 21

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; 
    } 
} 
-1

下面是另一種方式來輪詢信息:

讀出的值在這裏:離。

經由機器人殼

cat /sys/class/power_supply/usb/online 

1 =連接,0 =沒有。反映USB連接狀態。

貓/ SYS /類/ POWER_SUPPLY/AC /在線

1 =連接,0 =沒有。反映AC連接狀態。

同時使用這兩個,我想會告訴設備是否接收電源。不知道所有設備的位置是否相同。在三星平板電腦和RockChip設備上找到了位置相同的Android 7+和5+。