Updating TextView in Activity on receiving data from Broadcast receiver - android

Although I was able to accomplish this task but in opinion the approach is not good,Since am creating instance of the Activity inside Broadcast Receiver. Is there any better way to accomplish it?
#Override
public void onReceive(Context context, Intent intent) {
String receivedIntent = intent.getAction();
MainActivity inst = MainActivity.instance();
setPref(context);
if(m_Accactive){
if (receivedIntent.equals(IntentManager.ACCELEROMETER_DATA_FILTER)) {
Log.d("Accel", "acc data");
recAcc = (AccelerometerClass) intent
.getSerializableExtra(Constants.ACC_DATA_KEY);
recData = recAcc;
if (inst != null) {
m_AccRate = inst.getM_AccFreq();
m_AccRetrieveTxtForm = FormatToString(recAcc);
inst.textViewSettings(inst.m_AcceleroReading, R.id.AccData,
m_AccRetrieveTxtForm);
}
}
}

Related

How to check if a receiver is registered or not? [duplicate]

I need to check if my registered receiver is still registered if not how do i check it any methods?
There is no API function to check if a receiver is registered. The workaround is to put your code in a try catch block as done below.
try {
//Register or UnRegister your broadcast receiver here
} catch(IllegalArgumentException e) {
e.printStackTrace();
}
I am not sure the API provides directly an API, if you consider this thread:
I was wondering the same thing.
In my case I have a BroadcastReceiver implementation that calls
Context#unregisterReceiver(BroadcastReceiver) passing itself as the argument after handling the Intent that it receives.
There is a small chance that the receiver's onReceive(Context, Intent) method is called
more than once, since it is registered with multiple IntentFilters, creating the potential for an IllegalArgumentException being thrown from Context#unregisterReceiver(BroadcastReceiver).
In my case, I can store a private synchronized member to check before calling Context#unregisterReceiver(BroadcastReceiver), but it would be
much cleaner if the API provided a check method.
simplest solution
in receiver:
public class MyReceiver extends BroadcastReceiver {
public boolean isRegistered;
/**
* register receiver
* #param context - Context
* #param filter - Intent Filter
* #return see Context.registerReceiver(BroadcastReceiver,IntentFilter)
*/
public Intent register(Context context, IntentFilter filter) {
try {
// ceph3us note:
// here I propose to create
// a isRegistered(Contex) method
// as you can register receiver on different context
// so you need to match against the same one :)
// example by storing a list of weak references
// see LoadedApk.class - receiver dispatcher
// its and ArrayMap there for example
return !isRegistered
? context.registerReceiver(this, filter)
: null;
} finally {
isRegistered = true;
}
}
/**
* unregister received
* #param context - context
* #return true if was registered else false
*/
public boolean unregister(Context context) {
// additional work match on context before unregister
// eg store weak ref in register then compare in unregister
// if match same instance
return isRegistered
&& unregisterInternal(context);
}
private boolean unregisterInternal(Context context) {
context.unregisterReceiver(this);
isRegistered = false;
return true;
}
// rest implementation here
// or make this an abstract class as template :)
...
}
in code:
MyReceiver myReceiver = new MyReceiver();
myReceiver.register(Context, IntentFilter); // register
myReceiver.unregister(Context); // unregister
ad 1
-- in reply to:
This really isn't that elegant because you have to remember to set the
isRegistered flag after you register. – Stealth Rabbi
-- "more ellegant way" added method in receiver to register and set flag
this won't work If you restart the device or if your app got killed by
OS. – amin 6 hours ago
#amin - see lifetime of in code (not system registered by manifest entry) registered receiver :)
I am using this solution
public class ReceiverManager {
private WeakReference<Context> cReference;
private static List<BroadcastReceiver> receivers = new ArrayList<BroadcastReceiver>();
private static ReceiverManager ref;
private ReceiverManager(Context context) {
cReference = new WeakReference<>(context);
}
public static synchronized ReceiverManager init(Context context) {
if (ref == null) ref = new ReceiverManager(context);
return ref;
}
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter intentFilter) {
receivers.add(receiver);
Intent intent = cReference.get().registerReceiver(receiver, intentFilter);
Log.i(getClass().getSimpleName(), "registered receiver: " + receiver + " with filter: " + intentFilter);
Log.i(getClass().getSimpleName(), "receiver Intent: " + intent);
return intent;
}
public boolean isReceiverRegistered(BroadcastReceiver receiver) {
boolean registered = receivers.contains(receiver);
Log.i(getClass().getSimpleName(), "is receiver " + receiver + " registered? " + registered);
return registered;
}
public void unregisterReceiver(BroadcastReceiver receiver) {
if (isReceiverRegistered(receiver)) {
receivers.remove(receiver);
cReference.get().unregisterReceiver(receiver);
Log.i(getClass().getSimpleName(), "unregistered receiver: " + receiver);
}
}
}
You have several options
You can put a flag into your class or activity. Put a boolean variable into your class and look at this flag to know if you have the Receiver registered.
Create a class that extends the Receiver and there you can use:
Singleton pattern for only have one instance of this class in your project.
Implement the methods for know if the Receiver is register.
You have to use try/catch:
try {
if (receiver!=null) {
Activity.this.unregisterReceiver(receiver);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
You can do it easy....
1) create a boolean variable ...
private boolean bolBroacastRegistred;
2) When you register your Broadcast Receiver, set it to TRUE
...
bolBroacastRegistred = true;
this.registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
....
3) In the onPause() do it...
if (bolBroacastRegistred) {
this.unregisterReceiver(mReceiver);
bolBroacastRegistred = false
}
Just it, and now, you will not receive more exception error message on onPause().
Tip1: Always use the unregisterReceiver() in onPause() not in onDestroy()
Tip2: Dont forget to set the bolBroadcastRegistred variable to FALSE when run the unregisterReceive()
Success!
If you put this on onDestroy or onStop method. I think that when the activity has been created again the MessageReciver wasn't being created.
#Override
public void onDestroy (){
super.onDestroy();
LocalBroadcastManager.getInstance(context).unregisterReceiver(mMessageReceiver);
}
Personally I use the method of calling unregisterReceiver and swallowing the exception if it's thrown. I agree this is ugly but the best method currently provided.
I've raised a feature request to get a boolean method to check if a receiver is registered added to the Android API. Please support it here if you want to see it added:
https://code.google.com/p/android/issues/detail?id=73718
I used Intent to let Broadcast Receiver know about Handler instance of main Activity thread and used Message to pass a message to Main activity
I have used such mechanism to check if Broadcast Receiver is already registered or not. Sometimes it is needed when you register your Broadcast Receiver dynamically and do not want to make it twice or you present to the user if Broadcast Receiver is running.
Main activity:
public class Example extends Activity {
private BroadCastReceiver_example br_exemple;
final Messenger mMessenger = new Messenger(new IncomingHandler());
private boolean running = false;
static class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
running = false;
switch (msg.what) {
case BroadCastReceiver_example.ALIVE:
running = true;
....
break;
default:
super.handleMessage(msg);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter();
filter.addAction("pl.example.CHECK_RECEIVER");
br_exemple = new BroadCastReceiver_example();
getApplicationContext().registerReceiver(br_exemple , filter); //register the Receiver
}
// call it whenever you want to check if Broadcast Receiver is running.
private void check_broadcastRunning() {
/**
* checkBroadcastHandler - the handler will start runnable which will check if Broadcast Receiver is running
*/
Handler checkBroadcastHandler = null;
/**
* checkBroadcastRunnable - the runnable which will check if Broadcast Receiver is running
*/
Runnable checkBroadcastRunnable = null;
Intent checkBroadCastState = new Intent();
checkBroadCastState .setAction("pl.example.CHECK_RECEIVER");
checkBroadCastState .putExtra("mainView", mMessenger);
this.sendBroadcast(checkBroadCastState );
Log.d(TAG,"check if broadcast is running");
checkBroadcastHandler = new Handler();
checkBroadcastRunnable = new Runnable(){
public void run(){
if (running == true) {
Log.d(TAG,"broadcast is running");
}
else {
Log.d(TAG,"broadcast is not running");
}
}
};
checkBroadcastHandler.postDelayed(checkBroadcastRunnable,100);
return;
}
.............
}
Broadcast Receiver:
public class BroadCastReceiver_example extends BroadcastReceiver {
public static final int ALIVE = 1;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle extras = intent.getExtras();
String action = intent.getAction();
if (action.equals("pl.example.CHECK_RECEIVER")) {
Log.d(TAG, "Received broadcast live checker");
Messenger mainAppMessanger = (Messenger) extras.get("mainView");
try {
mainAppMessanger.send(Message.obtain(null, ALIVE));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
.........
}
}
i put this code in my parent activity
List registeredReceivers = new ArrayList<>();
#Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
registeredReceivers.add(System.identityHashCode(receiver));
return super.registerReceiver(receiver, filter);
}
#Override
public void unregisterReceiver(BroadcastReceiver receiver) {
if(registeredReceivers.contains(System.identityHashCode(receiver)))
super.unregisterReceiver(receiver);
}
I get your problem, I faced the same problem in my Application. I was calling registerReceiver() multiple time within the application.
A simple solution to this problem is to call the registerReceiver() in your Custom Application Class. This will ensure that your Broadcast receiver will be called only one in your entire Application lifecycle.
public class YourApplication extends Application
{
#Override
public void onCreate()
{
super.onCreate();
//register your Broadcast receiver here
IntentFilter intentFilter = new IntentFilter("MANUAL_BROADCAST_RECIEVER");
registerReceiver(new BroadcastReciever(), intentFilter);
}
}
This is how I have done it, it is a modified version of the answer given by ceph3us and edited by slinden77 (among other things I have removed return values of methods which I did not need):
public class MyBroadcastReceiver extends BroadcastReceiver{
private boolean isRegistered;
public void register(final Context context) {
if (!isRegistered){
Log.d(this.toString(), " going to register this broadcast receiver");
context.registerReceiver(this, new IntentFilter("MY_ACTION"));
isRegistered = true;
}
}
public void unregister(final Context context) {
if (isRegistered) {
Log.d(this.toString(), " going to unregister this broadcast receiver");
context.unregisterReceiver(this);
isRegistered = false;
}
}
#Override
public void onReceive(final Context context, final Intent intent) {
switch (getResultCode()){
//DO STUFF
}
}
}
Then on an Activity class:
public class MyFragmentActivity extends SingleFragmentActivity{
MyBroadcastReceiver myBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
registerBroacastReceiver();
}
#Override
protected Fragment createFragment(){
return new MyFragment();
}
//This method is called by the fragment which is started by this activity,
//when the Fragment is done, we also register the receiver here (if required)
#Override
public void receiveDataFromFragment(MyData data) {
registerBroacastReceiver();
//Do some stuff
}
#Override
protected void onStop(){
unregisterBroacastReceiver();
super.onStop();
}
void registerBroacastReceiver(){
if (myBroadcastReceiver == null)
myBroadcastReceiver = new MyBroadcastReceiver();
myBroadcastReceiver.register(this.getApplicationContext());
}
void unregisterReceiver(){
if (MyBroadcastReceiver != null)
myBroadcastReceiver.unregister(this.getApplicationContext());
}
}
For me the following worked:
if (receiver.isOrderedBroadcast()) {
requireContext().unregisterReceiver(receiver);
}
Here's what I did to check if the Broadcaster is already registered, even if you close you application (finish())
Firstime running your application, send a broadcast first it will return true/false depends on if your broadcaster in still running or not.
My Broadcaster
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getExtras() != null && intent.getStringExtra("test") != null){
Log.d("onReceive","test");
return;
}
}
}
My MainActivity
// init Broadcaster
private NotificationReceiver nr = new NotificationReceiver();
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("test", "testing");
boolean isRegistered = LocalBroadcastManager.getInstance(this).sendBroadcast(msgrcv);
if(!isRegistered){
Toast.makeText(this,"Starting Notification Receiver...",Toast.LENGTH_LONG).show();
LocalBroadcastManager.getInstance(this).registerReceiver(nr,new IntentFilter("Msg"));
}
if( receiver.isOrderedBroadcast() ){
// receiver object is registered
}
else{
// receiver object is not registered
}
Just check NullPointerException. If receiver does not exist, then...
try{
Intent i = new Intent();
i.setAction("ir.sss.smsREC");
context.sendBroadcast(i);
Log.i("...","broadcast sent");
}
catch (NullPointerException e)
{
e.getMessage();
}

How to update ListView with BroadcastReceiver?

I want update ListView from BroadcastReceiver in onReceiver event.
How to initialized ListView in this class then update to ListView:
public class CallBroadcast extends BroadcastReceiver {
private static int pState = TelephonyManager.CALL_STATE_IDLE;
#Override
public void onReceive(final Context context, final Intent intent) {
TelephonyManager telManager = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
telManager.listen(new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
callDAO = new CallDAO(context);
if (configPreferenceManager.getAutoRecord()) {
if (state != pState) {
if (state == TelephonyManager.CALL_STATE_OFFHOOK && callInfoPreferenceManager.getCallState()) {
uri = Uri.withAppendedPath(
ContactsContract.PhoneLookup.CONTENT_FILTER_URI,
Uri.encode(callInfoPreferenceManager.getPhoneNumber()));
projection = new String[]{ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME
, ContactsContract.Contacts.PHOTO_ID
};
// START SERVICES TO RECORD CALL. AFTER IT, I WANT UPDATE MY LIST
sIntent = new Intent(context.getApplicationContext(),
CallRecordService.class);
context.startService(sIntent);
} else if (state == TelephonyManager.CALL_STATE_RINGING && callInfoPreferenceManager.getCallState()) {
callInfoPreferenceManager.setPhoneNumber(incomingNumber);
callInfoPreferenceManager.setSending(String.valueOf(false));
} else if (state == TelephonyManager.CALL_STATE_IDLE && callInfoPreferenceManager.getCallState() == CALLING) {
callDAO.insert(callInfoPreferenceManager.getName(),
callInfoPreferenceManager.getPhoneNumber(),
callInfoPreferenceManager.getStartDate()
+ configPreferenceManager.getPathFormat());
callDAO.close();
// Record call start service
sIntent = new Intent(context.getApplicationContext(),
CallRecordService.class);
context.stopService(sIntent);
callInfoPreferenceManager.setCallState(IDLE);
}
pState = state;
}
}
}
}, PhoneStateListener.LISTEN_CALL_STATE);
}//onReceive
}
In the code I posted is BroadcastReceiver class.
And I can't using getActivity() class or findViewById(a, b) when extends BroadcastReceiver.
How to fix this problem?
Start the activity that will populate the listview using Intents.
Intent intent = new Intent(context,Myactivity.class)
startactivity(intent);
To avoid multiple instances of same 'Myactivity', use appropriate flags in the Manifest file.
If you want to transfer data between your broadcastReceiver and 'Myactivity', either use intent.putExtra() or store the data into sharedPreferences

How to get data from service in android

Hi just a newbie with android. I am trying to create a service which will constantly fetch location and update the an activity exp: Dashboard map. I have been following Android service
Now my problem is how to
- Constantly notify Dashboard activity ( was trying to simulate with while loop to notify data) from service
- I was able to print logs on connect and onBind, but i was wondering how to constantly watch for notification from service and retrieve the notified data from the Activity ie.Dashboard. Hope I am able convey my issue. I am searching for the latest api.
You should use BroadcastReceiver in your Dashboard activity. to do this follow this step:
Add a inner class to Dashboard activity like this:
public class ActionCompleteReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
String state = "disconnected";
if(intent != null)
state = intent.getStringExtra("State");
//Your Code
}
}
Add this code to Dashboard activity:
private ActionCompleteReceiver mActionReceiver;
public static final String ACTION_SERVICE_COMPLETE = "YUOR_PACKAGE_NAME.ACTION_SERVICE_COMPLETE";
Register receiver in onResume method in Dashboard activity like this
#Override
protected void onResume()
{
super.onResume();
if(mActionReceiver = null)
mActionReceiver= new ActionCompleteReceiver();
registerReceiver(mActionReceiver, new IntentFilter(ACTION_SERVICE_COMPLETE));
}
Unregister receiver onPause and onDestroy:
#Override
protected void onPause()
{
super.onPause();
if (mActionReceiver != null)
{
try
{
unregisterReceiver(mActionReceiver );
}
catch (Exception ignored)
{
}
}
}
#Override
public void onDestroy()
{
super.onDestroy();
if (mActionReceiver != null)
{
try
{
unregisterReceiver(mActionReceiver );
}
catch (Exception ignored)
{
}
}
}
In your service where you need to notify Dashboard activity add this:
Intent intent = new Intent(DashboardActivity.ACTION_SERVICE_COMPLETE);
intent.putExtra("State", "Connected");
sendBroadcast(intent);

How to Start Activity from IntentService and passing the Class<T> from another class?

I want to start an activity through IntentService, but the catch is the activty name or the class name will be passed as parameter to the IntentService.
Following are my code blocks...
public class Runner {
Context context;
public void startActivity() {
Intent intent = new Intent(context, ActivityLauncher.class);
intent.putExtra("caller", "Runner");
//CameraActivity is my activity which i want to start
// I will be giving other activities also in other parts of my code
intent.putExtra("class",CameraActivity.class);
context.startService(intent);
}
}
Now the code for ActivityLauncher Service is as follows.....
public class ActivityLauncher extends IntentService {
public ActivityLauncher(String name) {
super("ActivityLauncher");
}
protected void onHandleIntent(Intent intent) {
try{
Bundle b = intent.getExtras();
Class<?> c = (Class<?>) b.get("class");
Intent mainActivityIntent = new Intent(getBaseContext(), c.getClass());
mainActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
String intentType = intent.getExtras().getString("caller");
if(intentType == null)
return;
if(intentType.equals("Runner"))
getApplication().startActivity(mainActivityIntent);
} catch (Exception localException) {
Log.d("TAG", localException.getMessage());
}
}
}
Please tell me how can i improve my code. and how can i get the solution.

How to check if Receiver is registered in Android?

I need to check if my registered receiver is still registered if not how do i check it any methods?
There is no API function to check if a receiver is registered. The workaround is to put your code in a try catch block as done below.
try {
//Register or UnRegister your broadcast receiver here
} catch(IllegalArgumentException e) {
e.printStackTrace();
}
I am not sure the API provides directly an API, if you consider this thread:
I was wondering the same thing.
In my case I have a BroadcastReceiver implementation that calls
Context#unregisterReceiver(BroadcastReceiver) passing itself as the argument after handling the Intent that it receives.
There is a small chance that the receiver's onReceive(Context, Intent) method is called
more than once, since it is registered with multiple IntentFilters, creating the potential for an IllegalArgumentException being thrown from Context#unregisterReceiver(BroadcastReceiver).
In my case, I can store a private synchronized member to check before calling Context#unregisterReceiver(BroadcastReceiver), but it would be
much cleaner if the API provided a check method.
simplest solution
in receiver:
public class MyReceiver extends BroadcastReceiver {
public boolean isRegistered;
/**
* register receiver
* #param context - Context
* #param filter - Intent Filter
* #return see Context.registerReceiver(BroadcastReceiver,IntentFilter)
*/
public Intent register(Context context, IntentFilter filter) {
try {
// ceph3us note:
// here I propose to create
// a isRegistered(Contex) method
// as you can register receiver on different context
// so you need to match against the same one :)
// example by storing a list of weak references
// see LoadedApk.class - receiver dispatcher
// its and ArrayMap there for example
return !isRegistered
? context.registerReceiver(this, filter)
: null;
} finally {
isRegistered = true;
}
}
/**
* unregister received
* #param context - context
* #return true if was registered else false
*/
public boolean unregister(Context context) {
// additional work match on context before unregister
// eg store weak ref in register then compare in unregister
// if match same instance
return isRegistered
&& unregisterInternal(context);
}
private boolean unregisterInternal(Context context) {
context.unregisterReceiver(this);
isRegistered = false;
return true;
}
// rest implementation here
// or make this an abstract class as template :)
...
}
in code:
MyReceiver myReceiver = new MyReceiver();
myReceiver.register(Context, IntentFilter); // register
myReceiver.unregister(Context); // unregister
ad 1
-- in reply to:
This really isn't that elegant because you have to remember to set the
isRegistered flag after you register. – Stealth Rabbi
-- "more ellegant way" added method in receiver to register and set flag
this won't work If you restart the device or if your app got killed by
OS. – amin 6 hours ago
#amin - see lifetime of in code (not system registered by manifest entry) registered receiver :)
I am using this solution
public class ReceiverManager {
private WeakReference<Context> cReference;
private static List<BroadcastReceiver> receivers = new ArrayList<BroadcastReceiver>();
private static ReceiverManager ref;
private ReceiverManager(Context context) {
cReference = new WeakReference<>(context);
}
public static synchronized ReceiverManager init(Context context) {
if (ref == null) ref = new ReceiverManager(context);
return ref;
}
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter intentFilter) {
receivers.add(receiver);
Intent intent = cReference.get().registerReceiver(receiver, intentFilter);
Log.i(getClass().getSimpleName(), "registered receiver: " + receiver + " with filter: " + intentFilter);
Log.i(getClass().getSimpleName(), "receiver Intent: " + intent);
return intent;
}
public boolean isReceiverRegistered(BroadcastReceiver receiver) {
boolean registered = receivers.contains(receiver);
Log.i(getClass().getSimpleName(), "is receiver " + receiver + " registered? " + registered);
return registered;
}
public void unregisterReceiver(BroadcastReceiver receiver) {
if (isReceiverRegistered(receiver)) {
receivers.remove(receiver);
cReference.get().unregisterReceiver(receiver);
Log.i(getClass().getSimpleName(), "unregistered receiver: " + receiver);
}
}
}
You have several options
You can put a flag into your class or activity. Put a boolean variable into your class and look at this flag to know if you have the Receiver registered.
Create a class that extends the Receiver and there you can use:
Singleton pattern for only have one instance of this class in your project.
Implement the methods for know if the Receiver is register.
You have to use try/catch:
try {
if (receiver!=null) {
Activity.this.unregisterReceiver(receiver);
}
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
You can do it easy....
1) create a boolean variable ...
private boolean bolBroacastRegistred;
2) When you register your Broadcast Receiver, set it to TRUE
...
bolBroacastRegistred = true;
this.registerReceiver(mReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
....
3) In the onPause() do it...
if (bolBroacastRegistred) {
this.unregisterReceiver(mReceiver);
bolBroacastRegistred = false
}
Just it, and now, you will not receive more exception error message on onPause().
Tip1: Always use the unregisterReceiver() in onPause() not in onDestroy()
Tip2: Dont forget to set the bolBroadcastRegistred variable to FALSE when run the unregisterReceive()
Success!
If you put this on onDestroy or onStop method. I think that when the activity has been created again the MessageReciver wasn't being created.
#Override
public void onDestroy (){
super.onDestroy();
LocalBroadcastManager.getInstance(context).unregisterReceiver(mMessageReceiver);
}
Personally I use the method of calling unregisterReceiver and swallowing the exception if it's thrown. I agree this is ugly but the best method currently provided.
I've raised a feature request to get a boolean method to check if a receiver is registered added to the Android API. Please support it here if you want to see it added:
https://code.google.com/p/android/issues/detail?id=73718
I used Intent to let Broadcast Receiver know about Handler instance of main Activity thread and used Message to pass a message to Main activity
I have used such mechanism to check if Broadcast Receiver is already registered or not. Sometimes it is needed when you register your Broadcast Receiver dynamically and do not want to make it twice or you present to the user if Broadcast Receiver is running.
Main activity:
public class Example extends Activity {
private BroadCastReceiver_example br_exemple;
final Messenger mMessenger = new Messenger(new IncomingHandler());
private boolean running = false;
static class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
running = false;
switch (msg.what) {
case BroadCastReceiver_example.ALIVE:
running = true;
....
break;
default:
super.handleMessage(msg);
}
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
IntentFilter filter = new IntentFilter();
filter.addAction("pl.example.CHECK_RECEIVER");
br_exemple = new BroadCastReceiver_example();
getApplicationContext().registerReceiver(br_exemple , filter); //register the Receiver
}
// call it whenever you want to check if Broadcast Receiver is running.
private void check_broadcastRunning() {
/**
* checkBroadcastHandler - the handler will start runnable which will check if Broadcast Receiver is running
*/
Handler checkBroadcastHandler = null;
/**
* checkBroadcastRunnable - the runnable which will check if Broadcast Receiver is running
*/
Runnable checkBroadcastRunnable = null;
Intent checkBroadCastState = new Intent();
checkBroadCastState .setAction("pl.example.CHECK_RECEIVER");
checkBroadCastState .putExtra("mainView", mMessenger);
this.sendBroadcast(checkBroadCastState );
Log.d(TAG,"check if broadcast is running");
checkBroadcastHandler = new Handler();
checkBroadcastRunnable = new Runnable(){
public void run(){
if (running == true) {
Log.d(TAG,"broadcast is running");
}
else {
Log.d(TAG,"broadcast is not running");
}
}
};
checkBroadcastHandler.postDelayed(checkBroadcastRunnable,100);
return;
}
.............
}
Broadcast Receiver:
public class BroadCastReceiver_example extends BroadcastReceiver {
public static final int ALIVE = 1;
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Bundle extras = intent.getExtras();
String action = intent.getAction();
if (action.equals("pl.example.CHECK_RECEIVER")) {
Log.d(TAG, "Received broadcast live checker");
Messenger mainAppMessanger = (Messenger) extras.get("mainView");
try {
mainAppMessanger.send(Message.obtain(null, ALIVE));
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
.........
}
}
i put this code in my parent activity
List registeredReceivers = new ArrayList<>();
#Override
public Intent registerReceiver(BroadcastReceiver receiver, IntentFilter filter) {
registeredReceivers.add(System.identityHashCode(receiver));
return super.registerReceiver(receiver, filter);
}
#Override
public void unregisterReceiver(BroadcastReceiver receiver) {
if(registeredReceivers.contains(System.identityHashCode(receiver)))
super.unregisterReceiver(receiver);
}
I get your problem, I faced the same problem in my Application. I was calling registerReceiver() multiple time within the application.
A simple solution to this problem is to call the registerReceiver() in your Custom Application Class. This will ensure that your Broadcast receiver will be called only one in your entire Application lifecycle.
public class YourApplication extends Application
{
#Override
public void onCreate()
{
super.onCreate();
//register your Broadcast receiver here
IntentFilter intentFilter = new IntentFilter("MANUAL_BROADCAST_RECIEVER");
registerReceiver(new BroadcastReciever(), intentFilter);
}
}
This is how I have done it, it is a modified version of the answer given by ceph3us and edited by slinden77 (among other things I have removed return values of methods which I did not need):
public class MyBroadcastReceiver extends BroadcastReceiver{
private boolean isRegistered;
public void register(final Context context) {
if (!isRegistered){
Log.d(this.toString(), " going to register this broadcast receiver");
context.registerReceiver(this, new IntentFilter("MY_ACTION"));
isRegistered = true;
}
}
public void unregister(final Context context) {
if (isRegistered) {
Log.d(this.toString(), " going to unregister this broadcast receiver");
context.unregisterReceiver(this);
isRegistered = false;
}
}
#Override
public void onReceive(final Context context, final Intent intent) {
switch (getResultCode()){
//DO STUFF
}
}
}
Then on an Activity class:
public class MyFragmentActivity extends SingleFragmentActivity{
MyBroadcastReceiver myBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
registerBroacastReceiver();
}
#Override
protected Fragment createFragment(){
return new MyFragment();
}
//This method is called by the fragment which is started by this activity,
//when the Fragment is done, we also register the receiver here (if required)
#Override
public void receiveDataFromFragment(MyData data) {
registerBroacastReceiver();
//Do some stuff
}
#Override
protected void onStop(){
unregisterBroacastReceiver();
super.onStop();
}
void registerBroacastReceiver(){
if (myBroadcastReceiver == null)
myBroadcastReceiver = new MyBroadcastReceiver();
myBroadcastReceiver.register(this.getApplicationContext());
}
void unregisterReceiver(){
if (MyBroadcastReceiver != null)
myBroadcastReceiver.unregister(this.getApplicationContext());
}
}
For me the following worked:
if (receiver.isOrderedBroadcast()) {
requireContext().unregisterReceiver(receiver);
}
Here's what I did to check if the Broadcaster is already registered, even if you close you application (finish())
Firstime running your application, send a broadcast first it will return true/false depends on if your broadcaster in still running or not.
My Broadcaster
public class NotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if(intent.getExtras() != null && intent.getStringExtra("test") != null){
Log.d("onReceive","test");
return;
}
}
}
My MainActivity
// init Broadcaster
private NotificationReceiver nr = new NotificationReceiver();
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("test", "testing");
boolean isRegistered = LocalBroadcastManager.getInstance(this).sendBroadcast(msgrcv);
if(!isRegistered){
Toast.makeText(this,"Starting Notification Receiver...",Toast.LENGTH_LONG).show();
LocalBroadcastManager.getInstance(this).registerReceiver(nr,new IntentFilter("Msg"));
}
if( receiver.isOrderedBroadcast() ){
// receiver object is registered
}
else{
// receiver object is not registered
}
Just check NullPointerException. If receiver does not exist, then...
try{
Intent i = new Intent();
i.setAction("ir.sss.smsREC");
context.sendBroadcast(i);
Log.i("...","broadcast sent");
}
catch (NullPointerException e)
{
e.getMessage();
}

Categories

Resources