我想从两个按钮启动和停止广播接收器。 我已经在两个按钮监听器中为此编写了代码。
代码如下: -
在startButton中,我编写了注册接收器的代码,如下所示
startCallBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
startCallBtn.setVisibility(View.INVISIBLE);
stopCallBtn.setVisibility(View.VISIBLE);
//register call receiver.
registerReceiver(callReceiver, new IntentFilter(
"android.intent.action.CALL"));
System.out.println("Registered Call Receiver Perfectly");
}
});
在停止按钮中,我已将停止接收器的呼叫写为
stopCallBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
stopCallBtn.setVisibility(View.INVISIBLE);
startCallBtn.setVisibility(View.VISIBLE);
stopService(new Intent(MainActivity.this, SpeakOut.class));
FileOutputStream fos;
//Unregister sms receivers
unregisterReceiver(callReceiver);
System.out.println("Unregistered Call Broadcast Receiver");
}
});
当新的通话正在接收时,听众仍然在呼叫
答案 0 :(得分:10)
您可以针对enable
和disable
BroadcastReceiver
试用此代码。我希望这会对您有所帮助..
public void enableBroadcastReceiver(View view)
{
ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Enabled broadcast receiver", Toast.LENGTH_SHORT).show();
}
/**
* This method disables the Broadcast receiver registered in the AndroidManifest file.
* @param view
*/
public void disableBroadcastReceiver(View view){
ComponentName receiver = new ComponentName(this, AlarmManagerBroadcastReceiver.class);
PackageManager pm = this.getPackageManager();
pm.setComponentEnabledSetting(receiver,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(this, "Disabled broadcst receiver", Toast.LENGTH_SHORT).show();
}
答案 1 :(得分:3)
<receiver android:name="your receiver name">
主要活动
BroadcastReceiver br = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.w("Check", "Inside On Receiver");
Toast.makeText(getApplicationContext(), "received", Toast.LENGTH_SHORT).show();
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter();
filter.addAction(BROADCAST_ACTION);
filter.addCategory(Intent.CATEGORY_DEFAULT);
registerReceiver(br, filter);
}
@Override
protected void onPause() {
super.onPause();
unregisterReceiver(br);
}
}
答案 2 :(得分:1)
确保您呼叫的unregisterReceiver()
receiver
对象已调用registerReceiver()
。如果您在释放它之前为同一个接收器创建新对象,那么注册的旧接收器对象将不再被注册,因为您已经为其分配了新的内存块。
例如,执行此操作:
MyBroadcastReceiver receiver = new MyBroadCastReceiver();
registerReceiver(receiver);
unregisterReceiver(receiver);
receiver = new MyBraodCastReceiver();