从服务监控电池电量

时间:2016-02-16 23:36:44

标签: android broadcastreceiver android-service android-broadcast

我正在尝试使用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);
        }
    }
}

我也在尝试每隔/ xxx次发送一次HTTP请求。 HTTP请求将包括一些文本,电池状态以及纬度和经度。

我知道如何使用参数发送请求,但我的服务只运行一次。

1 个答案:

答案 0 :(得分:0)

您在第一次收到广播后取消注册batteryLevelReceiver。从onReceive删除此行以继续接收广播:

context.unregisterReceiver(this);

此外,您可能只想在创建/销毁服务器时注册和取消注册广播接收器,因此您应该在onCreate注册并在onDestroy取消注册。

以下是一些应该非常接近您想要的代码。请注意,所有这些都将在当前的UI线程上运行。

public class ServiceStatusUpdate extends Service {

    private static final int CHECK_BATTERY_INTERVAL = 5000;

    private GPSTracker gps;
    private double batteryLevel;
    private Handler handler;

    private BroadcastReceiver batInfoReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent batteryIntent) {
            int rawlevel = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
            int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);

            if (rawlevel >= 0 && scale > 0) {
                batteryLevel = (rawlevel * 100.0) / scale;
            }

            Log.e("Battery status is", batteryLevel + "mm");
        }
    };

    private Runnable checkBatteryStatusRunnable = new Runnable() {
        @Override
        public void run() {
            //DO WHATEVER YOU WANT WITH LATEST BATTERY LEVEL STORED IN batteryLevel HERE...

            // schedule next battery check
            handler.postDelayed(checkBatteryStatusRunnable, CHECK_BATTERY_INTERVAL);
            Log.e("Battery status is", batteryLevel + "mm cached");
        }
    };

    @Override
    public void onCreate() {
        handler = new Handler();
        handler.postDelayed(checkBatteryStatusRunnable, CHECK_BATTERY_INTERVAL);
        registerReceiver(batInfoReceiver,
                new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
    }

    @Override
    public void onDestroy() {
        unregisterReceiver(batInfoReceiver);
        handler.removeCallbacks(checkBatteryStatusRunnable);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return START_STICKY;
    }
}