使用服务获得电池电量

时间:2014-07-19 10:33:32

标签: android

这里我需要获得带有服务的电池状态。服务每秒钟后获取电池的状态,当我断开设备时,它会显示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();
       }
}

1 个答案:

答案 0 :(得分: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;
    }
}