2014-07-18 3 views
0

BatteryState가 변경 될 때마다 배터리 상태에 대한 정보를 표시하고 자체를 새로 고침하는 알림을 보내려고합니다. BatteryStateChangeBroadcastReceiver 및 알림이 작동하지 않는 서비스

은 우선은 Manifest.xml에 서비스를 등록 :
<service android:name=".BatteryStatusNotification"/> 

는 다음 나는 클래스를 만들어 서비스에 대한 방법을 구현했습니다. 그 후 NotificationBuilder 및 BatteryStateChange BroadcastReceiver를 작성했습니다. 내 MainActivity에서

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); 
    } 
} 

나는 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; 
    } 

:

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

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

I을 또한 경보로 새로 고침되는 WifiNotification이 있습니다. WifiNotification은 완벽하게 작동하지만 내 BatteryNotification은 그렇지 않습니다. @Sreekumar R에 대한

편집 : 여기

getBaseContext().startService(startService); 

을 : 내가 호출 할 필요는 없습니다 이유

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); 
} 

당신이 설명 할 수 있습니까?

+0

logcat에서 뭔가 보이나요? 귀하의 BroadcastReceiver가 ACTION_BATTERY_CHANGED을 (를) 듣고 있는지 알고 있습니까? –

+0

@axl 코더는 도움을 주셔서 감사하지만 Sreekumar R이 내 문제를 해결했습니다. –

답변

0

는 또한 startService = 새로운 의도를 (이, BatteryStatusNotification.class)

getBaseContext().startService(startService); 

전화하거나 라인을 변경해야합니다; ~

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

으로 서비스를 시작하십시오.

+0

나는 둘 다했고 이것은 트릭을했다. 다른 질문으로 내 질문을 편집했는데 설명해 주시겠습니까? –

+0

댓글 권한이 없습니다. 그래서 내 자신의 대답에 대해 언급. startService()는 실제 서비스가 시작되고 registerReceiver()가 브로드 캐스트를 등록하는 곳입니다. 의도 첫 번째 경우 등록은 서비스가 시작될 때만 호출되는 onStartCommand에서 수행됩니다. 두 번째 경우에는 이것이 작동한다고 언급 한 이후로 다른 곳에서 수행되었다고 가정합니다. –

관련 문제