嘿伙计们,我希望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();
}
}
答案 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参考。