0

我的應用程序在通知欄中顯示電池電量的通知。通知的作品,但當偏好設置中的複選框被點擊並且通知出現時,我嘗試拉下通知欄並且它滯後。我不知道的方式,但我認爲,這是因爲該通知檢查每一秒,電池電量,但我不知道。我張貼代碼:當發出通知時,通知欄滯後

@SuppressLint("NewApi") 
    private void checkPref(Intent intent){ 
      this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED)); 
      SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this); 
      boolean pref_opt1 = myPref.getBoolean("firstDependent", false); 
      int level= intent.getIntExtra(BatteryManager.EXTRA_LEVEL,-1); 
      if (pref_opt1){ 
       NotificationManager notifi = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
       Notification notification = new Notification.Builder(getApplicationContext()) 
       .setContentTitle("Battery Informations") 
       .setContentText("Battery level"+" "+level+"%") 
       .setSmallIcon(R.drawable.icon_small_not) 
       //.setLargeIcon(aBitmap) 
       .setTicker(level+"%") 
       .build(); 

       notification.flags = Notification.FLAG_ONGOING_EVENT; 
       Intent i = new Intent(MainActivity.this, MainActivity.class); 
       PendingIntent penInt = PendingIntent.getActivity(getApplicationContext(), 0 , i , 0); 
       notifi.notify(215,notification); 
       } else { 
       NotificationManager notifi = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
       notifi.cancel(215); 
       } 
     } 

也許問題是這樣的一個this.registerReceiver(this.batteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));。但我知道只有這樣才能在電池電量變化時更新通知。有些幫助嗎?

回答

0

檢查「如果情況」代碼是否顯示通知得到重複執行。如果是這樣,請嘗試通過標記限制顯示通知一次,並在notifi.cancel()過程中重置該標誌。

+0

那麼,如何編輯我的代碼呢?對不起,這是我的第一個應用程序:-) –