启动和停止广播接收器3

时间:2013-07-12 10:46:34

标签: android broadcastreceiver

在电池电量低的时间,我需要停止广播接收器。我写了代码,但我无法得到正确的答案。这里总是布尔变量返回false.Code。请帮帮我。

package example.broadcast;



import android.os.Bundle;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {
    Button btn1;    


BroadcastReceiver  alarmreceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            // TODO Auto-generated method stub

            Boolean batteryLow = intent.getAction().equals(Intent.ACTION_BATTERY_LOW);

            if(batteryLow==false){
            System.out.println("**********************hello***********************************");
            }else{

                PackageManager pm = context.getPackageManager();
                ComponentName passiveLocationReceiver = new ComponentName(context, MainActivity.class);
                pm.setComponentEnabledSetting(passiveLocationReceiver,
                  batteryLow ? PackageManager.COMPONENT_ENABLED_STATE_DISABLED : PackageManager.COMPONENT_ENABLED_STATE_DEFAULT, 
                  PackageManager.DONT_KILL_APP);
            }
        }
    };
    public static final String ACTION_NAME = "example.alarm.Alarmactivity.alarmreceiver";
    private IntentFilter myFilter = new IntentFilter(ACTION_NAME);






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


        btn1=(Button) findViewById(R.id.button1);
        btn1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub



                 registerReceiver(alarmreceiver, myFilter);
                 AlarmManager am=(AlarmManager)getSystemService(MainActivity.this.ALARM_SERVICE);      
                 Intent i = new Intent( ACTION_NAME);
                 PendingIntent pi = PendingIntent.getBroadcast(MainActivity.this, 0, i, 0);
                 am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000  * 15, pi);


            }


        });







    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

}

0 个答案:

没有答案