2014-07-19 143 views
0

在這裏,我需要獲得電池的狀態與services.Service每秒鐘後獲取電池的狀態,當我斷開設備它顯示USB連接到設備多少時間?請建議解決方案...............使用服務獲取電池電量

public class serviceclass extends Service{ 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO Auto-generated method stub 
     return null; 
    } 
    @Override 
     public int onStartCommand(Intent intent, int flags, int startId) { 
      // Let it continue running until it is stopped. 
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); 
      return START_STICKY; 
     } 
     @Override 
     public void onDestroy() { 
      super.onDestroy(); 
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show(); 
     } 
} 
+0

是的你上面粘貼的代碼只是一個簡單的服務示例代碼。讓我們知道你有什麼進一步嘗試。 –

+0

當我添加USB設備時,它會啓動服務,記下當前連接USB的時間,並記錄每秒鐘後的時間,當我移除USB時,它會顯示連接的時間。 – Shobin

回答

0

您不需要爲此提供服務。 有兩個廣播接收器可以知道是否連接了外部電源,以及外部電源是否已從設備中移除。如果你想知道設備連接的時間,我會這樣做:

public class Receiver extends BroadcastReceiver{ 

private long timeConnected; 
private long startConnected; 
private long endConnected; 

@Override 
public void onReceive(Context context, Intent intent) { 
    String action = intent.getAction(); 
    if(action.equals(Intent.ACTION_POWER_CONNECTED)){ 
     startConnected = new Calendar().getTimeInMillis(); 
    } else if(action.equals(Intent.ACTION_POWER_DISCONNECTED)){ 
     endConnected = new Calendar().getTimeInMillis(); 
     timeConnected = endConnected - startConnected; 
    } 
} 
+0

這將顯示以毫秒或秒爲單位的答案。我想在幾秒鐘內得到時間 – Shobin

+0

以秒爲單位獲得答案很簡單。現在時間以毫秒爲單位,以秒爲單位:timeMilliseconds/1000 – abemart

+0

謝謝... @ abemart – Shobin