2014-07-19 141 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