2013-09-24 85 views
0

我需要確定電源線(USB電纜)是否插入。SO上的解決方案都使用廣播接收器來接收電源更改事件。這種方法的問題是,在我的接收器被註冊之前,電纜可能已經被插入,在這種情況下,不會發生改變事件。我需要一種方法來確定電纜是否插入而不依賴廣播接收器。確定電源/ USB電纜是否插入到Android設備中

+2

這裏涵蓋:http://developer.android.com/training/monitoring-device-state/battery-monitoring.html#DetermineChargeState因爲這是一個棘手的意圖,你並不需要註冊一個BroadcastReceiver。 ....返回當前的電池狀態意圖。 – Kuffs

回答

3

檢查this link

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; 
    } 
} 
相關問題