Enable and disable a Broadcast Receiver
Well, what you basically have seems OK. I have the following code in one of my projects:
boolean enabled=prefs.getBoolean(key, false);
int flag=(enabled ?
PackageManager.COMPONENT_ENABLED_STATE_ENABLED :
PackageManager.COMPONENT_ENABLED_STATE_DISABLED);
ComponentName component=new ComponentName(EditPreferences.this, OnBootReceiver.class);
getPackageManager()
.setComponentEnabledSetting(component, flag,
PackageManager.DONT_KILL_APP);
I use this to disable a BOOT_COMPLETED
receiver when I don't have any active alarms that need to be scheduled.
My guess is that your ComponentName
is not set up properly (e.g., your leading .
). Try the constructor that I am using, that takes a Context
and a Class
as parameters.
how do I enable or disable a button from BroadCast onReceive() method
Main Activity
package com.checkisonline;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.view.Menu;
import android.widget.Button;
public class MainActivity extends Activity {
Button wifiState;
private IntentFilter intfilt;
private boolean enableOrDisable=false;
BroadcastReceiver enableDisableBrodcastRecr = new BroadcastReceiver()
{
@Override
public void onReceive(Context arg0, Intent arg1) {
enableOrDisable=arg1.getExtras().getBoolean("enableordisable");//enableordisable is Key which is passed inside onReceive method of Wifi
handler.sendEmptyMessage(0);
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
intfilt = new IntentFilter();
intfilt.addAction("EnableDisableAction");
registerReceiver(enableDisableBrodcastRecr, intfilt);
wifiState=(Button)findViewById(R.id.state);
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
if(checkWifiState()==true)
{
wifiState.setText("Wifi-ON");
wifiState.setTextColor(Color.GREEN);
}else
{
wifiState.setText("Wifi-OFF");
wifiState.setTextColor(Color.RED);
}
}
@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
unregisterReceiver(enableDisableBrodcastRecr);
}
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
if(enableOrDisable==true)
{
wifiState.setText("Wifi-ON");
wifiState.setTextColor(Color.GREEN);
}else
{
wifiState.setText("Wifi-OFF");
wifiState.setTextColor(Color.RED);
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public boolean checkWifiState()
{
boolean wifistate;
ConnectivityManager connectivityManager =
(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
if (activeNetInfo != null
&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
wifistate=true;
} else {
wifistate=false;
}
return wifistate;
}
}
Wifi Receiver
package com.checkisonline;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class WifiReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
ConnectivityManager connectivityManager =
(ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetInfo = connectivityManager.getActiveNetworkInfo();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("EnableDisableAction");
if (activeNetInfo != null
&& activeNetInfo.getType() == ConnectivityManager.TYPE_WIFI) {
broadcastIntent.putExtra("enableordisable", true);
} else {
broadcastIntent.putExtra("enableordisable", false);
}
context.sendBroadcast(broadcastIntent);
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<Button
android:id="@+id/state"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="176dp"
android:textSize="20dp"
/>
</RelativeLayout>
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.checkisonline"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.checkisonline.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name="com.checkisonline.WifiReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
</application>
</manifest>
Now as you required use ActionBar object wherever I used Button.
Enjoy....
enable and disable broadcast receiver on button click
Try this
b1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
PackageManager pm = Re_editActivity.this.getPackageManager();
ComponentName componentName = new ComponentName(currentActivity.this, name_of_your_receiver.class);
pm.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(getApplicationContext(), "activated", Toast.LENGTH_LONG).show();
}
});
b2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
PackageManager pm = Re_editActivity.this.getPackageManager();
ComponentName componentName = new ComponentName(currentActivity.this, name_of_your_receiver.class);
pm.setComponentEnabledSetting(componentName,PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Toast.makeText(getApplicationContext(), "cancelled", Toast.LENGTH_LONG).show();
}
});
here button1 is used to activate broadcast receiver and button2 to deactivate it
Also u need to register your broadcast receiver in manifest file and set
<receiver android:name="name_of_your_receiver" android:enabled="false">
<intent-filter >
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
Disable/Enable BroadcastReceiver when needed
You can call registerReceiver and unregisterReceiver in your activity. Here is an example of it :
registerReceiver(receiver, filter);
unregisterReceiver(receiver);
where receiver is your broadcast receiver class and filter will be
private IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
incase of sms receiver.
You can call registerReceiver once you require to receive a sms and call unregisterReceiver to stop listening for incoming sms.
How to disable the broadcast Receiver to stop receiving the incoming calls?
Try this, the below code could solve your problem,
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();
}
}
});
Disabling BroadcastReceiver for Oreo?
Since Library's code is not in your control, any approach won't work. You should ask the library provider to comply with latest OS.
You can try following work around:
Register
BOOT_COMPLETED
in your app with high priority as follows:<action android:name="android.intent.action.BOOT_COMPLETED" android:priority="999"/>
Start a Foreground Service immediately
This might allow your library to start background service.
Alternatively, If you have access to the BootReceiver class of the library, you can disable it as follows:
PackageManager pm = getPackageManager();
ComponentName compName =
new ComponentName(getApplicationContext(),
<library_broadcastreceiver>.class);
pm.setComponentEnabledSetting(
compName,
PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
Related Topics
Why Do I Get "Unresolved Reference" Error for My View's Name/Id When I Type It in Kotlin
Build and Install Unsigned APK on Device Without the Development Server
Android Studio Error "Installed Build Tools Revision 31.0.0 Is Corrupted"
How to Sign an Already Compiled APK
Android Emulator Not Able to Access the Internet
How to Record Phone Calls in Android
Create Blurry Transparent Background Effect
Why Is My Button Text Forced to All Caps on Lollipop
Referencing a String in a String Array Resource with Xml
Better Way to Format Currency Input Edittext
Phonegap - Add a Splash Screen for Android App
Windowsoftinputmode="Adjustresize" Not Working with Translucent Action/Navbar
How to Draw Free Hand Polygon in Google Map V2 in Android
How to Keep/Exclude a Particular Package Path When Using Proguard
HTML List Tag Not Working in Android Textview. What How to Do