2014-03-02 106 views
0

我想開發一個小應用程序,可以顯示手機在充電過程中當前的電流。例如,手機通過A/C插入並拉動1A。檢測充電android手機時吸取的電流當前電流

從我的研究有現有的API:

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

但是這些只會告訴你它是否通過USB或A/C充電,它的當前狀態。

我想做一些測試,以查看不同電纜和A/C適配器的費率。

回答

0

您可以使用以下方法檢查電池電量

private static int checkBatteryLevel(Context context) { 
     IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED); 
     Intent batteryStatus = context.registerReceiver(null, ifilter); 

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

     // If the device is charging then set the state as charging and return. 
     if (isCharging) 
      return 100; 

     // Get the battery level. 
     int level = batteryStatus.getIntExtra(BatteryManager.EXTRA_LEVEL, -1); 
     int scale = batteryStatus.getIntExtra(BatteryManager.EXTRA_SCALE, -1); 

     // To get the battery level in % 
     int batteryLevel = (level * 100)/scale; 
     Log.e(Constants.TAG, "Battery Level: " + batteryLevel); 

     return batteryLevel; 
    } 

而且你可以使用下面的接收器來檢測得到連接和斷開

public class BatteryInformationReceiver extends BroadcastReceiver { 

    private static final String ACTION_POWER_CONNECTED = "android.intent.action.ACTION_POWER_CONNECTED"; 
    private static final String ACTION_POWER_DISCONNECTED = "android.intent.action.ACTION_POWER_DISCONNECTED"; 

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

     String intentAction = intent.getAction(); 
     if (intentAction.equalsIgnoreCase(ACTION_POWER_CONNECTED)) { 

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

     } 

    } 
} 

,並在清單

<receiver android:name="your.package.receivers.BatteryInformationReceiver" > 
      <intent-filter> 
       <action android:name="android.intent.action.ACTION_POWER_CONNECTED" /> 
       <action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" /> 
      </intent-filter> 
     </receiver> 

然後,在連接時,計算b使用上述方法進行attery級別。並斷開連接後,計算電池電量。並從時間和電池的價值之間的差異。你可以計算任何你想要的。

希望這會有所幫助