2013-06-28 96 views
0

有沒有辦法改變布爾標籤?我的意思是,如果電池通過USB充電,我正在控制。如果是,則輸出爲真。我想在其他方面改變true。可能嗎?這是代碼:如何更改布爾標籤?

public static boolean isPhonePluggedIn(Context context){ 
    boolean charging = false; 

    final Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 
    int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); 
    boolean batteryCharge = status==BatteryManager.BATTERY_STATUS_CHARGING; 

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

    if (batteryCharge) charging=true; 
    if (usbCharge) charging=true; 
    if (acCharge) charging=true; 

    return charging; 
} 
+0

你想改變'真正'的東西..什麼? – CRUSADER

+1

這是非常高級的編程,超出了我們大多數:)。嚴肅的回答 - 布爾人是真的還是假的,就是這樣。也許用'isPhonePluggedIn()'顯示你在做什麼,我們可以幫忙嗎? –

+0

以及我想要做什麼不打印「真實」,但例如「正在收費」。 –

回答

0

如果你談論的是顯示文本,你可以做到這一點是:

public static String isPhonePluggedIn(Context context){ 
    boolean charging = false; 
    String result = "No"; 
    final Intent batteryIntent = context.registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 
    int status = batteryIntent.getIntExtra(BatteryManager.EXTRA_STATUS, -1); 
    boolean batteryCharge = status==BatteryManager.BATTERY_STATUS_CHARGING; 

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

    if (batteryCharge) charging=true; 
    if (usbCharge) charging=true; 
    if (acCharge) charging=true; 

    if(charging) result="Yes"; 
    return result; 
} 

所以,你可以設置此字符串的TextView或吐司。

希望它有幫助。

+0

問題是,這是我在一個void方法我不能寫回報。 –

+0

@ user2508402該方法已經返回布爾值。它不是空的 –

+0

這部分:'int chargePlug = batteryIntent.getIntExtra(BatteryManager.EXTRA_PLUGGED,-1); boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB; boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC; if(batteryCharge)charging = true; if(usbCharge)charging = true;如果(acCharge)充電=真,則爲 ; if(charging)result =「Yes」;'在無效方法內。我現在更改了代碼。 –