1
大家好,我的代碼,以顯示電池電量多少通知有一個小問題。我已經插入偏好代碼insid的onReceive
,如:爲什麼當我點擊複選框時,通知在10秒後出現?
private BroadcastReceiver batteryInfoReceiver = new BroadcastReceiver() {
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
@Override
public void onReceive(Context context, Intent intent) {
// prefer
setPref.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(MainActivity.this,settings.class);
startActivityForResult(intent, 0);
}});
checkPref();
}
@SuppressLint("NewApi")
private void checkPref() {
SharedPreferences myPref = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
boolean pref_opt1 = myPref.getBoolean("pref_opt1", 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("Batteria al"+" "+level+"%")
.setSmallIcon(R.drawable.icon_small_not)
.setTicker(level+"%")
.build();
notification.flags = Notification.FLAG_ONGOING_EVENT;
Intent i = new Intent(context, 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);
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
checkPref();
}
}
一切順利,但是當我檢查框通知大約10秒後出現。爲什麼?
我應該補充說,在代碼中使用所有這些註釋並不是一個好習慣。你有一個特定的原因,或者你只是使用你從某個地方得到的代碼,並且做了日食希望你做的事情,以便使黃色的小波浪消失? – Travis
那麼,我想要它只是顯示電池電量通知,如果首選項中的複選框被選中。這是錯誤的方式? –
您希望它將電池級別添加到通知欄中,因爲您選中該框(馬上就會,而不是稍後),對吧? – Travis