0
我正在嘗試使用Service
來監視當前的電池狀態。我寫了一些代碼,我可以使用日誌顯示電池電量一次,但我想每5秒鐘根據計時器監視電池電量。從服務器監視電池電量
public class ServiceStatusUpdate extends Service {
GPSTracker gps;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
while (true) {
new Handler().postDelayed(new Runnable() {
public void run() {
batteryLevel();
Log.e("Status changed", "Status changed");
}
}, 5000);
return START_STICKY;
}
}
private void batteryLevel() {
BroadcastReceiver batteryLevelReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
context.unregisterReceiver(this);
int rawlevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
int level = -1;
if (rawlevel >= 0 && scale > 0) {
level = (rawlevel * 100)/scale;
}
Log.e("Batarry status iss", level + "mm");
}
};
IntentFilter batteryLevelFilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
registerReceiver(batteryLevelReceiver, batteryLevelFilter);
return;
}
}
MainActivity.java
:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, ServiceStatusUpdate.class));
}
}
manifest.xml
源:
<receiver
android:name=".OnBootReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<service
android:name=".ServiceStatusUpdate"
android:enabled="true" />
OnBootReceiver
:
public class OnBootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
//int batteryLevel = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
Intent serviceLauncher = new Intent(context, ServiceStatusUpdate.class);
context.startService(serviceLauncher);
}
}
}
我也試圖發送一個HTTP請求每/ XXX倍。 HTTP請求將包含一些文本,電池狀態和經度和緯度。
我知道如何發送帶有參數的要求,但我的服務工作只有一次。
我更新了我的MainActivity.java源。 PS我刪除batteryLevel方法和Log.e狀態更改messige只顯示一次 – BekaKK
我想檢查每XXX時間battary狀態通過服務 – BekaKK
那麼這是不同於你最初問。給我一分鐘,我會更新答案。 –