1

嗨,我的代码显示有关电池电量的通知有一个小问题。我在里面插入了首选项的代码onReceive

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 秒后出现。为什么?

4

1 回答 1

0

每次收到广播时,您都会检查复选框是否已选中(在 checkPref() 中),发生的情况是您正在选中该框,然后您收到广播,然后发布通知。你想让它做什么?

于 2013-07-09T11:41:06.233 回答