电池电量不足的通知

时间:2015-06-03 20:04:15

标签: java android eclipse android-activity

我试图在设备剩余电量不足15%时弹出通知。 但它每次都显示通知,当我超过15%时也是如此。

这是我的代码:

public class MainActivity extends Activity {

public int battery, level;
private static final int DIALOG_EXIT=1;
Button Hscore,ToInfo,ToProj;
ImageView Easter,EXIT,Help,Info;

private TextView contentTxt;    
public BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
        @Override
        public void onReceive(Context arg0, Intent intent) {
          // TODO Auto-generated method stub
          level = intent.getIntExtra("level", 0);   

          contentTxt.setText(String.valueOf(level) + "%  Battery");      

        }
      };



@Override
protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    this.registerReceiver(this.mBatInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));

    contentTxt = (TextView) this.findViewById(R.id.txtbattery);

    if(level <= 15)
    {
        Intent Charge = new Intent(MainActivity.this,ChargeActivity.class);
        //  Intent st =new Intent(android.provider.Settings.ACTION_SETTINGS);       
            String title="you have low battery", message="charge your phone";
            int icon = R.raw.duck_yellow;    
            int mNotificationId = 001;

            PendingIntent resultPendingIntent =
                    PendingIntent.getActivity(
                            getBaseContext(),
                            0,
                            Charge,
                            PendingIntent.FLAG_CANCEL_CURRENT
                    );   
            NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
                    getBaseContext());
            Notification notification = mBuilder.setSmallIcon(icon).setTicker(title).setWhen(0)
                    .setAutoCancel(true)
                    .setContentTitle(title)
                    .setStyle(new NotificationCompat.BigTextStyle().bigText(message))
                    .setContentIntent(resultPendingIntent)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                    .setLargeIcon(BitmapFactory.decodeResource(getBaseContext().getResources(), R.raw.duck_yellow))
                    .setContentText(message).build();

            NotificationManager notificationManager = (NotificationManager) getBaseContext().getSystemService(Context.NOTIFICATION_SERVICE);
            notificationManager.notify(mNotificationId, notification);
    }

我该怎么做才能解决这个问题? 我认为它与私人/公共变量有关

0 个答案:

没有答案