使用BatteryStateChangeBroadcastReceiver和Notification的服务不起作用

时间:2014-07-18 12:13:20

标签: android service notifications broadcastreceiver

我试图发出通知,显示有关电池状态的一些信息,并在每次BatteryState更改时自行刷新。

首先我在Manifest.xml中注册了一个服务:

<service android:name=".BatteryStatusNotification"/>

然后我创建了Class并实现了服务的方法。之后我编写了NotificationBuilder和BatteryStateChange BroadcastReceiver。

public class BatteryStatusNotification extends Service {

    int level;
    String pluggedString;
    String temperature;
    String voltage;


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

    private BroadcastReceiver batteryReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context c, Intent intent) {

            level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
            int plugged= intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);

            DecimalFormat tempformatter = new DecimalFormat("##,##,#");
            int temp = intent.getIntExtra(BatteryManager.EXTRA_TEMPERATURE, 0);
            temperature = tempformatter.format(temp);

            DecimalFormat volformatter = new DecimalFormat("#,###");
            int  vol = intent.getIntExtra(BatteryManager.EXTRA_VOLTAGE, 0);
            voltage = volformatter.format(vol);

            switch (plugged) {
                case 0: pluggedString = (getResources().getString(R.string.batteryUncharging));
                    break;
                case 1: pluggedString = (getResources().getString(R.string.batteryChargingAC));
                    break;
                case 2: pluggedString = (getResources().getString(R.string.batteryChargingUSB));
                    break;
                case 4: pluggedString = (getResources().getString(R.string.batteryChargingWireless));
                    break;
            }

            batteryStatNotification();
        }
    };

    @Override
    public int onStartCommand(Intent intent, int flags, int StartId) {
        this.registerReceiver(this.batteryReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
        return START_STICKY;
    }

    public void batteryStatNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.ic_action_battery)
                .setContentTitle(pluggedString + " | " + level + " %")
                .setContentText(getResources().getString(R.string.notiTemp) + " " + temperature + " | " + getResources().getString(R.string.notiVol) + " " + voltage + getResources().getString(R.string.volts))
                .setOngoing(true);


        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(2, builder.build()); //Notification Id 2 = Battery
    }

    @Override
    public void onDestroy() {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(2);
    }
}

在我的MainActivity中,我有一个ToggleButton:

    //Toggle Battery Notification
    ToggleButton batteryToggle = (ToggleButton) findViewById(R.id.batToggleNotification);
    batteryToggle.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked) {
                SharedPreferences sharedPref = getSharedPreferences("FileName", MODE_PRIVATE);
                SharedPreferences.Editor prefEditor = sharedPref.edit();
                prefEditor.putInt("batteryToggle", 1);
                prefEditor.commit();
                enableBatteryNotification();
            } else {
                enableBatteryNotification();
                disableBatteryNotification();
                SharedPreferences sharedPref = getSharedPreferences("FileName", MODE_PRIVATE);
                SharedPreferences.Editor prefEditor = sharedPref.edit();
                prefEditor.putInt("batteryToggle", 0);
                prefEditor.commit();
            }
        }
    });

    int batteryTogglePref = sharedPref.getInt("batteryToggle", 0);

    switch (batteryTogglePref) {
        case 0: toggle.setChecked(false);
            break;
        case 1: toggle.setChecked(true);
            break;
    }

保存自己的状态并在App启动时返回它并调用这两种方法:

public void enableBatteryNotification() {
    startService = new Intent(this, BatteryStatusNotification.class);
}

public void disableBatteryNotification() {
    stopService(new Intent(getBaseContext(), BatteryStatusNotification.class));
}

我还有一个WifiNotification,它会被闹钟刷新。 WifiNotification工作得很好但我的BatteryNotification没有。

编辑@Sreekumar R:

public void enableWifiNotification() {

    SharedPreferences sharedPref = getSharedPreferences("FileName", MODE_PRIVATE);
    int numberSP3 = sharedPref.getInt("numberSP2", 1);
    int unitSP3 = sharedPref.getInt("unitSP2", 1);

    startService = new Intent(this, WifiNotificationService.class);
    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    pendingIntent = PendingIntent.getService(this, 0, startService, 0);

    Calendar calendar = Calendar.getInstance();
    calendar.setTimeInMillis(System.currentTimeMillis());

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * numberSP3 * unitSP3 , pendingIntent);
}

你能解释为什么我不打电话:

getBaseContext().startService(startService);

这里吗?

1 个答案:

答案 0 :(得分:0)

您还需要致电

getBaseContext().startService(startService);

或更改行startService = new Intent(this,BatteryStatusNotification.class);到

startService(new Intent(this, BatteryStatusNotification.class));

启动服务。