Android BroadcastReceiver called multiple times - android

I'm new to android and i am trying to implement a broadcast receiver which will receive the broadcast whenever the hotspot is changed:
public class HotspotChangeReceiver extends BroadcastReceiver implements Configurable {
public static boolean isEnabled = false;
#Override
public void onReceive(Context context, Intent intent) {
//TODO handle properly
String action = intent.getAction();
if ("android.net.wifi.WIFI_AP_STATE_CHANGED".equals(action)) {
Intent intent1 = new Intent();
int state = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
// if (WifiManager.WIFI_STATE_ENABLED == state % 10) {
if(state == 13){
intent1.setAction("net.wecodelicious.intent.action.HOTSPOT_ENABLED");
context.sendBroadcast(intent1);
}
else{
intent1.setAction("net.wecodelicious.intent.action.HOTSPOT_DISABLED");
context.sendBroadcast(intent1);
}
Toast.makeText(context, "HOTSPOT Changed ", Toast.LENGTH_LONG).show();
}
}
public static void enable() {
if(!isEnabled) {
MainActivity.getMpackageManager().setComponentEnabledSetting(new ComponentName(MainActivity.getMcontext(), HotspotChangeReceiver.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
isEnabled = true;
}
}
public static void disable() {
if(isEnabled) {
MainActivity.getMpackageManager().setComponentEnabledSetting(new ComponentName(MainActivity.getMcontext(), HotspotChangeReceiver.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
isEnabled = false;
}
}
}
also i've following classes to receive custom broadcasts:
public class HotspotEnabledReceiver extends BroadcastReceiver implements Configurable {
public static boolean isEnabled = false;
#Override
public void onReceive(Context context, Intent intent) {
//TODO handle properly
if("net.wecodelicious.intent.action.HOTSPOT_ENABLED".equals(intent.getAction())) {
Toast.makeText(context, "Hotspot Enabled ", Toast.LENGTH_LONG).show();
}
}
public static void enable() {
if(!isEnabled) {
HotspotChangeReceiver.enable();
MainActivity.getMpackageManager().setComponentEnabledSetting(new ComponentName(MainActivity.getMcontext(), HotspotEnabledReceiver.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
isEnabled = true;
}
}
public static void disable() {
if(isEnabled) {
HotspotChangeReceiver.disable();
MainActivity.getMpackageManager().setComponentEnabledSetting(new ComponentName(MainActivity.getMcontext(), HotspotEnabledReceiver.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
isEnabled = false;
}
}
}
and broadcastreceiver when hotspot is disabled is following:
public class HotspotDisabledReceiver extends BroadcastReceiver implements Configurable {
public static boolean isEnabled = false;
#Override
public void onReceive(Context context, Intent intent) {
//TODO handle properly
if("net.wecodelicious.intent.action.HOTSPOT_DISABLED".equals(intent.getAction())) {
Toast.makeText(context, "Hotspot Disabled ", Toast.LENGTH_LONG).show();
}
}
public static void enable() {
if(!isEnabled) {
HotspotChangeReceiver.enable();
MainActivity.getMpackageManager().setComponentEnabledSetting(new ComponentName(MainActivity.getMcontext(), HotspotDisabledReceiver.class), PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
isEnabled = true;
}
}
public static void disable() {
if(isEnabled) {
HotspotChangeReceiver.disable();
MainActivity.getMpackageManager().setComponentEnabledSetting(new ComponentName(MainActivity.getMcontext(), HotspotDisabledReceiver.class), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);
isEnabled = false;
}
}
}
also I'm enabling all receiver components in ManiActivity as followed:
public class MainActivity extends AppCompatActivity {
public static boolean isF = true;
#Override
protected void onCreate(Bundle savedInstanceState) {
...
enableall();
}
public static void enableall(){
if(isF) {
HotspotChangeReceiver.enable();
HotspotEnabledReceiver.enable();
HotspotDisabledReceiver.enable();
isF=false;
}
}
I've registered them in manifest file:
<receiver android:name=".HotspotChangeReceiver" android:enabled="false">
<intent-filter>
<action android:name="android.net.wifi.WIFI_AP_STATE_CHANGED"/>
</intent-filter>
</receiver>
<receiver android:name=".HotspotEnabledReceiver" android:enabled="false">
<intent-filter>
<action android:name="net.wecodelicious.intent.action.HOTSPOT_ENABLED"/>
</intent-filter>
</receiver>
<receiver android:name=".HotspotDisabledReceiver" android:enabled="false">
<intent-filter>
<action android:name="net.wecodelicious.intent.action.HOTSPOT_DISABLED"/>
</intent-filter>
</receiver>
But when i run the app and turn the hotspot on Toasts are displayed in following sequence:
Hotspot Changed
Hotspot Disabled
Hotspot Enabled
also when i turn the hotspot off following Toasts are displayed:
Hotspot Changed
Hotspot Disabled
Hotspot Changed
Hotspot Disabled
I hope someone recognizes the strange behavior and has a quick solution for it.I tried to find the solution but was unable to come up with any.Any help will be appreciated.

When you Enable and Disable, it is a State Change at the same time isn't it. I would either register Enable and Disable, or just State Change by itself only.

Related

android.intent.action.ALARM_CHANGED

I need to set alarm icon in status bar, without a notification. It works when application is running, but after finishing an application, the receiver does not respond on "ALARM_CHANGED", only on "BOOT_COMPLETED".
Need to set alarm icon after user turns off alarms in build-in Alarm Clock.
Thanks.
manifest:
<receiver android:name=".Alarm.AlarmInitReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.ALARM_CHANGED" />
</intent-filter>
</receiver>
AlarmInitReceiver.java:
public class AlarmInitReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Toast.makeText(context, "BOOT-completed", Toast.LENGTH_LONG).show();
}
if (intent.getAction().equals("android.intent.action.ALARM_CHANGED")) {
Toast.makeText(context, "Alarm on", Toast.LENGTH_SHORT).show();
setStatusBarIcon(true);
}
}
}
}
MainActivity:
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
setStatusBarIcon(true);
enableReceiver(true);
}
protected void enableReceiver(boolean enable) {
ComponentName receiver = new ComponentName(mContext, AlarmInitReceiver.class);
PackageManager pm = mContext.getPackageManager();
pm.setComponentEnabledSetting(receiver,
(enable) ? PackageManager.COMPONENT_ENABLED_STATE_ENABLED : PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
PackageManager.DONT_KILL_APP);
}
public static void setStatusBarIcon(boolean enabled)
{
Intent alarmChanged = new Intent("android.intent.action.ALARM_CHANGED");
alarmChanged.putExtra("alarmSet", enabled);
mContext.sendBroadcast(alarmChanged);
}
}
The solution is:
public class AlarmInitReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Toast.makeText(context, "BOOT-completed", Toast.LENGTH_LONG).show();
}
if (intent.getAction().equals("android.intent.action.ALARM_CHANGED")) {
if (intent.getExtras().getBoolean("alarmSet") == false) {
Intent alarmChanged = new Intent("android.intent.action.ALARM_CHANGED");
alarmChanged.putExtra("alarmSet", true);
context.sendBroadcast(alarmChanged);
}
}
}
}

Check Android Network continuously

I want to verify the Android system networks continuously in this way, but i think that in this form is not correct, my service should update if the connection on wifi or other network is available.
public class ObjService extends Service{
private final static int NOTIFICATION=1;
public static boolean process;
private NotificationManager state;
private NotificationCompat.Builder objBuilder;
public void onCreate(){
process=true;
state=(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
objBuilder = new NotificationCompat.Builder(this)
.setContentTitle("Title")
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.launchimg))
.setSmallIcon(R.drawable.notification_img);
Thread checker=new Thread(){//1
public void run(){//2
while (process){//3
if (verifyConnection()){//4
updateNotificationService("Service is available");
}else{
updateNotificationService("Service is not available");
}//4
try{
Thread.sleep(6000);
}catch(InterruptedException e){
//..printLog..
}
}//3
};//2
};//1
checker.start();
.
.
.
my function verifyConnection() is:
public boolean verifyConnection() {
boolean flag = true;
ConnectivityManager connec = (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo[] net = connec.getAllNetworkInfo();
if (!net[0].isAvailable() && !net[1].isAvailable())
{
flag = false;
}
return flag;
}
updateNotificationService() is:
public void updateNotificacionService(String arg){
objBuilder.setContentText(arg)
.setWhen(System.currentTimeMillis());
state.notify(NOTIFICATION, objBuilder.build());
}
Try this code below to listen whether the connection exist, if the connection state changes it notifies the change,
public class NetworkStateReceiver extends BroadcastReceiver {
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.d("app","Network connectivity change");
if(intent.getExtras()!=null) {
NetworkInfo ni=(NetworkInfo) intent.getExtras().get(ConnectivityManager.EXTRA_NETWORK_INFO);
if(ni!=null && ni.getState()==NetworkInfo.State.CONNECTED) {
Log.i("app","Network "+ni.getTypeName()+" connected");
}
}
if(intent.getExtras().getBoolean(ConnectivityManager.EXTRA_NO_CONNECTIVITY,Boolean.FALSE)) {
Log.d("app","There's no network connectivity");
}
}
}
Then for manifest,
<receiver android:name=".NetworkStateReceiver">
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Reference: Internet listener Android example
Android 7.0 (API level 24) placed limitations on broadcasts, as
described in Background Optimization. Android 8.0 (API level 26) makes
these limitations more stringent.
Apps can use Context.registerReceiver() at runtime to register a
receiver for any broadcast, whether implicit or explicit.
Documentation reference.
So, here is a utility class that utilizes a context registered BroadcastReceiver , and LifeCycleObserver for achieving Single-responsibility principle
class ConnectionUtil implements LifecycleObserver {
private ConnectivityManager mConnectivityMgr;
private Context mContext;
private NetworkStateReceiver mNetworkStateReceiver;
interface ConnectionStateListener {
void onAvailable(boolean isAvailable);
}
ConnectionUtil(Context context) {
mContext = context;
mConnectivityMgr = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
((AppCompatActivity) mContext).getLifecycle().addObserver(this);
}
void onInternetStateListener(ConnectionStateListener listener) {
mNetworkStateReceiver = new NetworkStateReceiver(listener);
IntentFilter intentFilter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
// Registering the Context Registered Receiver
mContext.registerReceiver(mNetworkStateReceiver, intentFilter);
}
#OnLifecycleEvent(Lifecycle.Event.ON_DESTROY)
public void onDestroy() {
// Removing lifecycler owner observer
((AppCompatActivity) mContext).getLifecycle().removeObserver(this);
// Unregistering the Context Registered Receiver
if (mNetworkStateReceiver != null)
mContext.unregisterReceiver(mNetworkStateReceiver);
}
public class NetworkStateReceiver extends BroadcastReceiver {
ConnectionStateListener mListener;
public NetworkStateReceiver(ConnectionStateListener listener) {
mListener = listener;
}
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getExtras() != null) {
NetworkInfo activeNetworkInfo = mConnectivityMgr.getActiveNetworkInfo();
if (activeNetworkInfo != null && activeNetworkInfo.getState() == NetworkInfo.State.CONNECTED) {
// Connected to the internet
mListener.onAvailable(true);
} else if (intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, Boolean.FALSE)) {
// Not connected to the internet
mListener.onAvailable(false);
}
}
}
}
}
Manifest permission
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Usage:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectionUtil mConnectionMonitor = new ConnectionUtil(this);
mConnectionMonitor.onInternetStateListener(new ConnectionUtil.ConnectionStateListener() {
#Override
public void onAvailable(boolean isAvailable) {
if(isAvailable)
Toast.makeText(MainActivity.this, "Connected", Toast.LENGTH_SHORT).show();
else
Toast.makeText(MainActivity.this, "Disconnected", Toast.LENGTH_SHORT).show();
}
});
}
}
Note: NetworkInfo is deprecated as of API 29, and you can use ConnectivityManager.NetworkCallback with its onAvailable() & onLost() callbacks for the same purpose instead of using a BroadcastReceiver. This answer can guide to target this purpose.

How to Lock/Unlock screen programmatically?

I am doing an application which Locks the screen on shake. Now it is locking and from there it going to a broadcast receiver from there if the screen is off its entering into a service which has to turn the screen on.
Below is the broadcast receiver:
public class ScreenReceiver extends BroadcastReceiver {
public static boolean wasScreenOn = true;
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("Entered Broadcaste Reciever");
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// DO WHATEVER YOU NEED TO DO HERE
System.out.println("SCREEN_OFF"+wasScreenOn);
wasScreenOn = false;
Intent i = new Intent(context, UpdateService.class);
i.putExtra("screen_state", wasScreenOn);
context.startService(i);
System.out.println("jrkejhr keh");
}
else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// AND DO WHATEVER YOU NEED TO DO HERE
wasScreenOn = true;
System.out.println("SCREEN_ON"+wasScreenOn);
}
}
And its entering to a service where i had written the intent action to go home is...
ShakeListener mShaker;
int amountOfTime = 0;
Context context1;
#Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
System.out.println("Enterd Service");
final Vibrator vibe = (Vibrator)getSystemService(Context.VIBRATOR_SERVICE);
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener () {
public void onShake() {
vibe.vibrate(100);
Intent goHome = new Intent();
goHome.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
goHome.setAction("android.intent.action.MAIN");
goHome.addCategory("android.intent.category.HOME");
startActivity(goHome);
}
});
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
It is entering into the service. But home screen is not displaying. When the service is invoked the the screen is locked.
Edit:
As some folks needs help in Unlocking device after locking programmatically,
I came through post Android screen lock/ unlock programatically, please have look, may help you.
Original Answer was:
You need to get Admin permission and you can lock phone screen
please check below simple tutorial to achive this one
Lock Phone Screen Programmtically
also here is the code example..
LockScreenActivity.java
public class LockScreenActivity extends Activity implements OnClickListener {
private Button lock;
private Button disable;
private Button enable;
static final int RESULT_ENABLE = 1;
DevicePolicyManager deviceManger;
ActivityManager activityManager;
ComponentName compName;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
deviceManger = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
activityManager = (ActivityManager)getSystemService(
Context.ACTIVITY_SERVICE);
compName = new ComponentName(this, MyAdmin.class);
setContentView(R.layout.main);
lock =(Button)findViewById(R.id.lock);
lock.setOnClickListener(this);
disable = (Button)findViewById(R.id.btnDisable);
enable =(Button)findViewById(R.id.btnEnable);
disable.setOnClickListener(this);
enable.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if(v == lock){
boolean active = deviceManger.isAdminActive(compName);
if (active) {
deviceManger.lockNow();
}
}
if(v == enable){
Intent intent = new Intent(DevicePolicyManager
.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
compName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
"Additional text explaining why this needs to be added.");
startActivityForResult(intent, RESULT_ENABLE);
}
if(v == disable){
deviceManger.removeActiveAdmin(compName);
updateButtonStates();
}
}
private void updateButtonStates() {
boolean active = deviceManger.isAdminActive(compName);
if (active) {
enable.setEnabled(false);
disable.setEnabled(true);
} else {
enable.setEnabled(true);
disable.setEnabled(false);
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case RESULT_ENABLE:
if (resultCode == Activity.RESULT_OK) {
Log.i("DeviceAdminSample", "Admin enabled!");
} else {
Log.i("DeviceAdminSample", "Admin enable FAILED!");
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
MyAdmin.java
public class MyAdmin extends DeviceAdminReceiver{
static SharedPreferences getSamplePreferences(Context context) {
return context.getSharedPreferences(
DeviceAdminReceiver.class.getName(), 0);
}
static String PREF_PASSWORD_QUALITY = "password_quality";
static String PREF_PASSWORD_LENGTH = "password_length";
static String PREF_MAX_FAILED_PW = "max_failed_pw";
void showToast(Context context, CharSequence msg) {
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
}
#Override
public void onEnabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: enabled");
}
#Override
public CharSequence onDisableRequested(Context context, Intent intent) {
return "This is an optional message to warn the user about disabling.";
}
#Override
public void onDisabled(Context context, Intent intent) {
showToast(context, "Sample Device Admin: disabled");
}
#Override
public void onPasswordChanged(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw changed");
}
#Override
public void onPasswordFailed(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw failed");
}
#Override
public void onPasswordSucceeded(Context context, Intent intent) {
showToast(context, "Sample Device Admin: pw succeeded");
}
}
The androidmanifest.xml and policies.xml files on the sample page are invisible in my browser due to it trying to format the XML files as HTML. I'm only posting this for reference for the convenience of others, this is sourced from the sample page.
Thanks all for this helpful question!
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.kns"
android:versionCode="1"
android:versionName="1.0">
<uses-sdk android:minSdkVersion="8" />
<application android:icon="#drawable/icon" android:label="#string/app_name">
<activity android:name=".LockScreenActivity"
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=".MyAdmin"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin"
android:resource="#xml/policies" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</application>
</manifest>
policies.xml
<?xml version="1.0" encoding="utf-8"?>
<device-admin xmlns:android="http://schemas.android.com/apk/res/android">
<uses-policies>
<limit-password />
<watch-login />
<reset-password />
<force-lock />
<wipe-data />
</uses-policies>
</device-admin>
Use Activity.getWindow() to get the window of your activity; use Window.addFlags() to add whichever of the following flags in WindowManager.LayoutParams that you desire:
FLAG_DISMISS_KEYGUARD
FLAG_SHOW_WHEN_LOCKED
FLAG_TURN_SCREEN_ON

Android 4.0 Device Admin Receiver not working

I'm trying to build a really simple app to wipe all the user data off a ICS device.
I've tried to create the app using the source code on http://developer.android.com/guide/topics/admin/device-admin.html
and
http://marakana.com/s/post/1291/android_device_policy_administration_tutorial
But I'm having an issue, no matter what I do, the broadcast receiver for prompting the user to allow admin does not appear!
Heres what I got so far if anyone can help with this issue.
Manifest:
<uses-sdk android:minSdkVersion="15" />
<application android:icon="#drawable/ic_launcher"
android:label="#string/app_name">
<activity android:name="com.CheckActivityService.CheckActivityServiceActivity"
android:label="#string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<receiver android:name=".mDeviceAdminReceiver"
android:label="device_admin" android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data android:name="android.app.device_admin"
android:resource="#xml/policies" />
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED" />
</intent-filter>
</receiver>
</manifest>
Activity:
public class CheckActivityServiceActivity extends Activity implements OnCheckedChangeListener{
/** Called when the activity is first created. */
static final int ACTIVATION_REQUEST = 1; // identifies our request id
DevicePolicyManager devicePolicyManager;
ComponentName deviceAdmin;
ToggleButton toggleButton;
static final String TAG = "DevicePolicyActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
toggleButton = (ToggleButton) super
.findViewById(R.id.toggle_device_admin);
toggleButton.setOnCheckedChangeListener(this);
Button btn = (Button) findViewById(R.id.wipeDataBtn);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
wipeData();
}
});
devicePolicyManager = (DevicePolicyManager) getSystemService(Context.DEVICE_POLICY_SERVICE);
deviceAdmin = new ComponentName(CheckActivityServiceActivity.this, mDeviceAdminReceiver.class);
}
/**
* Called when the state of toggle button changes. In this case, we send an
* intent to activate the device policy administration.
*/
public void onCheckedChanged(CompoundButton button, boolean isChecked) {
if (isChecked) {
// Launch the activity to have the user enable our admin.
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "My Boss told me to do this!!");
startActivityForResult(intent, ACTIVATION_REQUEST);
}
Log.d(TAG, "onCheckedChanged to: " + isChecked);
}
public void wipeData(){
devicePolicyManager.wipeData(ACTIVATION_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case ACTIVATION_REQUEST:
if (resultCode == Activity.RESULT_OK) {
Log.i(TAG, "Administration enabled!");
toggleButton.setChecked(true);
} else {
Log.i(TAG, "Administration enable FAILED!");
toggleButton.setChecked(false);
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
}
Reciever:
public class mDeviceAdminReceiver extends DeviceAdminReceiver {
static final String TAG = "DeviceAdminReceiver";
void showToast(Context context, String msg) {
String status = "TEST";
Toast.makeText(context, status, Toast.LENGTH_SHORT).show();
}
/** Called when this application is approved to be a device administrator. */
#Override
public void onEnabled(Context context, Intent intent) {
super.onEnabled(context, intent);
Toast.makeText(context, "Admin Enabeled",
Toast.LENGTH_LONG).show();
Log.d(TAG, "onEnabled");
}
/** Called when this application is no longer the device administrator. */
#Override
public void onDisabled(Context context, Intent intent) {
super.onDisabled(context, intent);
Toast.makeText(context, "Admin Disabled",
Toast.LENGTH_LONG).show();
Log.d(TAG, "onDisabled");
}
#Override
public void onPasswordChanged(Context context, Intent intent) {
super.onPasswordChanged(context, intent);
Log.d(TAG, "onPasswordChanged");
}
#Override
public void onPasswordFailed(Context context, Intent intent) {
super.onPasswordFailed(context, intent);
Log.d(TAG, "onPasswordFailed");
}
#Override
public void onPasswordSucceeded(Context context, Intent intent) {
super.onPasswordSucceeded(context, intent);
Log.d(TAG, "onPasswordSucceeded");
}
}
If anyone can help me to get this to work, as I really can't figure out why the broadcast receiver isn't firing.
Figured out problem, kind of stupid of me.
needed to put the receiver in the element.

how to use android broadcast receiver

Here below is an example of service, activity and broadcast receiver. An activity is a setting that make changes to a service. The broadcast receiver listens to changes in settings and update service. learner2learner
public class xService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public static void setEnableNotification(int command) {
Log.i("EnableNotification","Updated");
if (command == 0)
enableNotification = true;
...
}
}
The method below is a part of an activity that sends broadcast:
#Override
protected void onCreate(Bundle savedInstanceState) {
....
IntentFilter filter = new IntentFilter();
filter.addAction(NotifyServiceReceiver.ACTION);
registerReceiver(receiver,filter);
}
final String ACTION="broadcast_settings";
public void onClick(View view) {
Intent intent = new Intent(ACTION);
switch (view.getId()) {
case R.id.switchNotification:
if(switchNotification.isChecked()==true)
{
intent.putExtra("EnableNotification", 0);
Log.i("Security365","Notification is enabled.");
}
else if ....
sendBroadcast(intent);
break;
}
The part below is my broadcast receiver:
public class xReceiver extends BroadcastReceiver {
final String ACTION="broadcast_settings";
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals(ACTION)){
int enableNotification = intent.getIntExtra("EnableNotification", 0);
if (enableNotification == 0)
Serurity365Service.setEnableNotification(0);
...
}
}
}
Mainfest
<receiver android:name=".xReceiver" android:enabled="true"></receiver>
If I understand your code correctly, the block
if(switchNotification.isChecked()==true)
{
intent.putExtra("EnableNotification", 1);
Log.i("Security365","Notification is enabled.");
}
is setting the EnableNotification to 1 in the intent used from sendBroadcast
In your broadcast receiver, you have
int enableNotification = intent
.getIntExtra("EnableNotification", 1);
if (enableNotification == 0)
Serurity365Service.setEnableNotification(0);
So it says to retrieve the extra EnableNotification and if no value, return the default value of 1 and then you never enter your if (enableNotification == 0) statement.
To be sure your broadcast receiver works correctly, add a log statement at the beginning of your receiver in the onReceive method.
EDIT:
Also the AndroidMANIFEST.xml has a tag <manifest> that declares a package.
For example
<manifest package="com.hello.world" ...
When you declare the receiver in the manifest, the . like in .xReceiver means that xReceiver.java should be located in the package com.hello.world.
If you have in a different package, specify the full name or relatiive to the package declared in <manifest
More info here
you are sending broadcast in a wrong way. You should send it as below:
public void onClick(View view) {
Intent intent = new Intent("your_action");
switch (view.getId()) {
case R.id.switchNotification:
if(switchNotification.isChecked()==true)
{
intent.putExtra("EnableNotification", 1);
Log.i("Security365","Notification is enabled.");
}
else if ....
sendBroadcast(intent);
break;
}
}
and receive it as:
public class xReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getACtion().equals("your_action"){
int enableNotification = intent
.getIntExtra("EnableNotification", 1);
if (enableNotification == 0)
Serurity365Service.setEnableNotification(0);
...
}
}
}
update you Androidmanifest.xml too:
<receiver android:name=".xReceiver" android:enabled="true">
<intent-filter>
<action android:name="your_action" />
</intent-filter>
</receiver>

Categories

Resources