只有在选中切换按钮时,BroadcastReceiver类才能工作

时间:2014-03-10 12:43:10

标签: android broadcastreceiver

嘿伙计们,我希望BroadcastReceiver只有在ToggleButton被检查时才能工作.... 我使用的代码是......

manifest.xml档案中......

<receiver 
            android:name="Start">

        <intent-filter>
            <action android:name="android.intent.action.PHONE_STATE" />
        </intent-filter>
            </receiver> 

Activity班级......

ToggleButton tgl;
    String prefs="app_preference";
    SharedPreferences sharedPrefs;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tgl=(ToggleButton)findViewById(R.id.toggleButton1);
        tgl.setOnCheckedChangeListener(this);
        sharedPrefs = getSharedPreferences(prefs,MODE_PRIVATE);
        tgl.setChecked(sharedPrefs.getBoolean("IS_RECEIVER_ENABLED", false));

public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        // TODO Auto-generated method stub

        if(tgl.isChecked()){
             SharedPreferences.Editor editor = sharedPrefs.edit();
             editor.putBoolean("IS_RECEIVER_ENABLED", true);
                editor.commit();

        }else{
            SharedPreferences.Editor editor = sharedPrefs.edit();
            editor.putBoolean("IS_RECEIVER_ENABLED", false);
            editor.commit();
        }

BroadcastReceiver班级......

public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub
        boolean isEnabled = context.getSharedPreferences("app_preference",
                Context.MODE_PRIVATE).getBoolean("IS_RECEIVER_ENABLED",
                false);
        if (isEnabled) {

            Toast.makeText(context,"Intent detected", Toast.LENGTH_LONG).show();
        }


    }

2 个答案:

答案 0 :(得分:2)

只有在使用

在活动级别(非Manifest)注册接收器时才可以这样做

禁用切换按钮时

registerReceiver(BroadcastReceiver, IntentFilter)

当切换按钮被禁用时,您可以使用..

取消注册
unregisterReceiver(BroadcastReceiver receiver)

答案 1 :(得分:0)

接收方需要READ_PHONE_STATE权限。添加到AndroidManifest.xml文件:

<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

有关详细信息,请参阅TelephonyManager参考。