我在禁用广播接收器方面遇到了问题。广播接收器接收呼入和呼出呼叫。 在我的情况下,当开关接通时,接收器应该在开关处于关闭状态时接收数据,接收器应该停止接收数据。
switches.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
// sharedPreferences = getApplicationContext().getSharedPreferences("enableApp", Context.MODE_PRIVATE);
// SharedPreferences.Editor editor = sharedPreferences.edit();
// editor.putBoolean(getString(R.string.enable), isChecked);
// editor.commit();
if(isChecked)
{
Toast.makeText(getApplicationContext(), "Enabled", Toast.LENGTH_SHORT).show();
}
else
{
PackageManager pm = DashBoardActivity.this.getPackageManager();
ComponentName componentName = new ComponentName(DashBoardActivity.this, CallReceiver.class);
pm.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(getApplicationContext(), "cancelled", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Disabled", Toast.LENGTH_SHORT).show();
}
}
});
这是我尝试过的代码,我尝试使用包管理器来禁用广播接收器。
The broadcast receiver registered in manifestfile
<receiver android:name=".receiver.CallReceiver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.NEW_OUTGOING_CALL" />
</intent-filter>
</receiver>
我想在我的活动中禁用接收器。如何禁用接收器?
答案 0 :(得分:1)
试试这个,下面的代码可以解决你的问题,
switches.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
sharedPreferences = getApplicationContext().getSharedPreferences("enableApp", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putBoolean(getString(R.string.enable), isChecked);
editor.commit();
if(isChecked)
{
PackageManager pm = DashBoardActivity.this.getPackageManager();
ComponentName componentName = new ComponentName(DashBoardActivity.this, CallReceiver.class);
int status = getApplicationContext().getPackageManager().getComponentEnabledSetting(componentName);
pm.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Log.e("Broadcast status",status + "");
Toast.makeText(getApplicationContext(), "Enabled", Toast.LENGTH_SHORT).show();
}
else
{
PackageManager pm = DashBoardActivity.this.getPackageManager();
ComponentName componentName = new ComponentName(DashBoardActivity.this, CallReceiver.class);
int status = getApplicationContext().getPackageManager().getComponentEnabledSetting(componentName);
pm.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Log.e("Broadcast status",status + "");
Toast.makeText(getApplicationContext(), "cancelled", Toast.LENGTH_LONG).show();
Toast.makeText(getApplicationContext(), "Disabled", Toast.LENGTH_SHORT).show();
}
}
});