Passing events from a non-activity class to an Activity class - android

I have an activity class A for the layout and a non-activity class B for Location Request; the class B triggers some events like onConnectionSuspended and i want to get these back in the classe A. How can i do that ?
Thank you for the previous answers, i worked on it but i add some details.
I want to separate the Activity code from the GoogleApi.Connection code. To do that i made a non-activity class (maybe a service is better ?) with Connection code (see the structure code below).
1) Is it a good idea ?
2) If it is not, what is better to do (maybe put all in the same Activity ?) ?
3) If it is yes, i don't think that i can put some "Toast" in the connections events of my non-activity code so how can i get back the connections events in the Activity to display some messages ?
Thank you for the answers
import android.os.Bundle;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
public class SATlocation implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener{
#Override
public void onConnected(Bundle bundle) {
}
#Override
public void onConnectionSuspended(int i) {
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
}
}

As an alternative to broadcast receivers, if you have access to your class B instance from your Activity, you can also create an interface for listening to those events.
public interface LocationRequestEventListener {
void onConnectionSuspended();
...
}
public class SomeActivity extends Activity implements LocationRequestEventListener {
private ClassB classB;
#Override
public void onCreate() {
...
classB.setListener(this);
}
...
#Override
void onConnectionSuspended() {
//react to the event here
}
}
public class ClassB {
private LocationRequestListener listener;
....
public void setListener(LocationRequestListener listener) {
this.listener = listener;
}
private void connectionSuspended() {
// suppose this is where your class fire the event of interest
if (listener != null) {
listener.onConnectionSuspended();
}
}
}

use Local broadcast receiver add receiver in your activity as below
private BroadcastReceiver onNotice = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// intent can contain anydata
}
}
inside onresume register receiver as below
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter(MyIntentService.ACTION);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, intentFilter);
}
unRegister receiver in onPause
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
}
In your location service add following code to send local broadcast
Intent intent = new Intent("custom-event-name");
// You can also include some extra data.
intent.putExtra("message", "This is my message!");
LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

Related

How to know if activity is at the top of stack

How could I know if an activity is the top of stack? I thought about using onResume/onPause, but this is not exactly, as it would fail once the app goes to background.
The fact is that I'm sending a broadcast receiver that is received for all activities (I have a BaseActivity that is extended by all activities and that registers to the broadcast). So, only the activity that is at the top of the stack must react to the broadcast. If I use the isResumed() then it would work always but when the app goes to background. Any idea?
Thanks in advance!
in base activity you register the broadcast Receiver and in receiver function you call one abstract function which one is implemented by all child activities.
The activity which is on top will automatically receive that function call.
Edit sample code:
public abstract class BaseActivity extends AppCompatActivity {
private static final String NOTIFICATION_ARRIVED = "arrived";
public abstract void receivedFunction(Intent intent);
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
displayToast(" received in Base");
receivedFunction(intent);
}
};
public void displayToast(String s) {
Toast.makeText(this,s,Toast.LENGTH_SHORT).show();
}
#Override
public void onResume() {
super.onResume();
registerReceiver(mMessageReceiver, new IntentFilter(BaseActivity.NOTIFICATION_ARRIVED));
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(mMessageReceiver);
}
}
public class MainActivity extends BaseActivity {
#Override
public void receivedFunction(Intent intent) {
displayToast(" received in child");
}
// do whetever you want . if you ovveride onpause and onResume then call super as well
}
or any other child
public class MainActivity2 extends BaseActivity {
#Override
public void receivedFunction(Intent intent) {
displayToast(" received in child");
}
// do whetever you want . if you ovveride onpause and onResume then call super as well
}
// to broadcast
Intent intent = new Intent(BaseActivity.NOTIFICATION_ARRIVED);
sendBroadcast(intent);

do something inside mainActivity whenever a push notification is received

In my app, whenever I receive a push notification, I will perform a check if my mainActivity is visible to the user to do something...
I have a static boolean value that is set true inside onResume of mainActivity, and false inside it's onPause.
What should I do inside the onMessage
#Override
protected void onMessage(Context context, Intent intent)
{
if(mainActivity == visible)
//do something inside mainactivity.. change text inside edittext
else
//do something else
}
any insights ?
I'm not a fan of keeping static references to activities. I think they're a can of worms ready to explode on you. So you'll suggest an alternative to #TeRRo answer:
on your global BroadcastReceiver onMessage you'll send a LocalBroadcast that your activity will be listening to. Like this:
private static final String ACTION_PUSH_RECEIVED = "com.myapp.mypackage.action.pushReceived";
public static final IntentFilter BROADCAST_INTENT_FILTER = new IntentFilter(ACTION_PUSH_RECEIVED);
#Override
protected void onMessage(Context context, Intent intent) {
Intent i = new Intent(ACTION_PUSH_RECEIVED);
i.putExtra( ... add any extra data you want... )
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
}
and now we make the activity listen to it:
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(context)
.registerReceiver(mBroadcastReceiver, BroadcastReceiverClass.BROADCAST_INTENT_FILTER);
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(context)
.unregisterReceiver(mBroadcastReceiver);
super.onPause();
}
private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver(){
#Override
public void onReceive(Context context, Intent intent){
// read any data you might need from intent and do your action here
}
}
To avoid this, you should manage activities references. Add the name of the application in the manifest file:
<application
android:name=".MyApp"
....
</application>
Your application class :
public class MyApp extends Application {
public void onCreate() {
super.onCreate();
}
private Activity mCurrentActivity = null;
public Activity getCurrentActivity(){
return mCurrentActivity;
}
public void setCurrentActivity(Activity mCurrentActivity){
this.mCurrentActivity = mCurrentActivity;
}
}
Create a new Activity :
public class MyBaseActivity extends Activity {
protected MyApp mMyApp;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mMyApp = (MyApp)this.getApplicationContext();
}
protected void onResume() {
super.onResume();
mMyApp.setCurrentActivity(this);
}
protected void onPause() {
clearReferences();
super.onPause();
}
protected void onDestroy() {
clearReferences();
super.onDestroy();
}
private void clearReferences(){
Activity currActivity = mMyApp.getCurrentActivity();
if (currActivity != null && currActivity.equals(this))
mMyApp.setCurrentActivity(null);
}
}
So, now instead of extending Activity class for your activities, just extend MyBaseActivity. Now, you can get your current activity from application or Activity context like that :
Activity currentActivity = ((MyApp)context.getApplicationContext()).getCurrentActivity();
Or why don't you use the Local broadcasts when you receive the push notification, and receive it in your activity, and do respective changes or actions.
And if they are UI intensive tasks, bind your activity to a service, and receive the push notification and perform the action in this service and use the result in the activity.

Calling a Activity method from BroadcastReceiver in Android

Here I am creating an online application that depends only on Internet.
So whenever there is a network error it must notify user. For that, I have created a BroadcastReciver that receives call when network connection gets lost(Internet).
All this works perfectly. Now what I need is that I have to call a method of Activity from this Broadcast Receiver, where I have created an Alert Dialogue.
I have read many answers on stack-overflow.com that I can declare that method static and call by using only Activity name,
e.g MyActivityName.myMethod()
But I can't declare my method static, because I am using Alert Dialogue there and it shows me error on line,
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
that Cannot use this in a static context.
So, how can I call a method of Activity(must not static and without starting that activity) from a Broadcast Receiver ?
And can I get Activity(or fragment) name from Broadcast Receiver which is currently running?
try this code :
your broadcastreceiver class for internet lost class :
public class InternetLostReceiver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
context.sendBroadcast(new Intent("INTERNET_LOST"));
}
}
in your activity add this for calling broadcast:
public class TestActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
registerReceiver(broadcastReceiver, new IntentFilter("INTERNET_LOST"));
}
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// internet lost alert dialog method call from here...
}
};
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(broadcastReceiver);
}
}
INTERFACE: Keep BroadCastReceiver and Activity code separate!
You can make a CallBackListener interface. The interface will work as a bridge between BroadcastReceiver and Activity.
1) Create a CallbackListener
interface ConnectionLostCallback{
public void connectionLost();
}
2) Provide ConnectionLostCallback in your BroadcastReceiver
public class MyBroadcastReceiver extends BroadcastReceiver{
private ConnectionLostCallback listener;
public MyBroadcastReceiver(ConnectionLostCallback listener ){
this.listener = listener //<-- Initialze it
}
#Override
public void onReceive(Context context, Intent intent) {
listener.connectionLost();
}
}
3) Implement the ConnectionLostCallback in your Activity and override the method
YourActvity extends AppcompatActivity implements ConnectionLostCallback{
// Your Activity related code //
// new MyBroadcastReceiver(this); <-- create instance
private void showAlertMessage(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
}
#Override
public void connectionLost(){
showAlertMessage(); //<--- Call the method to shoe alert dialog
}
}
Relevant link:
If you want to know how to make a BroadcastReceiver independent of any
activity ie How can you reuse the same BroadCastReceiver with
different Activities? Then READ THIS
Add a boolean variable in you activity from where you are open alertdialog
boolean isDialogOpened = false;
// in broadcast recever check
if(isDialogOpened) {
alertDialog();
}
And replace your code for alertdialog with this one
public void alertDialog() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setMessage("Network not found.");
alertDialog.setPositiveButton("Check Setting",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
alertDialog.setOnDismissListener(new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
isDialogOpened = false;
}
});
alertDialog.setOnCancelListener(new OnCancelListener() {
#Override
public void onCancel(DialogInterface dialog) {
isDialogOpened = false;
}
});
alertDialog.show();
}
Pass your Activity's context to BroadcastReceiver's contructor.
public class ResponseReceiver extends BroadcastReceiver{
MainActivity ma; //a reference to activity's context
public ResponseReceiver(MainActivity maContext){
ma=maContext;
}
#Override
public void onReceive(Context context, Intent intent) {
ma.brCallback("your string"); //calling activity method
}
}
and in your MainActivity
public class MainActivity extends AppCompatActivity {
...
public void onStart(){
...
ResponseReceiver responseReceiver = new ResponseReceiver(this); //passing context
LocalBroadcastManager.getInstance(this).registerReceiver(responseReceiver,null);
...
}
public void brCallback(String param){
Log.d("BroadcastReceiver",param);
}
}
hope it helps
Use lambdas. A Consumer would do.
protected void onCreate(Bundle savedInstanceState) {
...
receiver = new LocationBroadcastReceiver((whatever) -> doSomething(whatever));
registerReceiver(receiver, new IntentFilter("YOUR_MESSAGE"));
}
Where doSomething will be a method in your Activity.
...
class YourBroadcastReceiver extends BroadcastReceiver {
private Consumer<Whatever> callback;
public LocationBroadcastReceiver(Consumer<Whatever> callback) {
this.callback = callback;
}
#RequiresApi(api = Build.VERSION_CODES.N)
#Override
public void onReceive(Context context, Intent intent) {
this.callback.accept(new Whatever());
}
}
Is the alternative to all the other:
declare that method static and call by using only Activity name.
Apart from what you explained, that's a way of coupling.
pass your Activity's context to BroadcastReceiver's contructor.
That wouldn't work because you want to call a method that's not part of AppCompatActivity. And yeah, you could downcast, but then you end up coupled to your activity.
using another Broadcast or a Local Broadcasts instead
Well, you can only pass a bunch of primitives that way. What if you want to pass an object? Also, declaring a new BroadcastReceiver get quite verbose and maybe hard to follow.
Same as Vijju' s answer but using Local Broadcasts instead
public class SampleReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent intentToBroadcast = new Intent("YOUR_ACTION_HERE");
LocalBroadcastManager.getInstance(context).sendBroadcast(intentToBroadcast);
}
}
In your activity add this
public class SampleActivity extends Activity {
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(this).registerReceiver(mSampleReceiver, new IntentFilter(YOUR_ACTION_HERE));
}
#Override
protected void onPause() {
LocalBroadcastManager.getInstance(this).unregisterReceiver(mSampleReceiver);
super.onPause();
}
private SampleReceiver mSampleReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// your code here
}
};
}
Note Move the register/unregister calls to onCreate/onDestroy is you want to be notified even when your activity is in the background.

Android, calling class method AFTER receiving message from service

Well, I have a service, I have an Activity. They communicate via messages (It must communicate with messages so don't tell me about Intents or other things, please).
I receive a Bundle from the Service, all ok.
Now with the Bundle i've received I want to do something. I want to call a method from "SomeClass", but I can't, because I'm inside of "IncomingHandler" class.
What's the best way to call SomeClass from inside IncomingHandler?
Thanks in advance
class SomeClass implements ServiceConnection {
class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case MyService.MS_GET_SOMETHING:
Bundle received=msg.getData();
...
If you really want the activity to be calling methods on the service, its time to learn about AIDL, which allows an Activity to make function calls on a bound service via an RPC mechanism. Documentation found here.
I have implemented the feature (Service calls method in activity) like this:
Service sends a broadcast-message.
Activity has a local nested broadcastreceiver that can call a method in the parent activity.
public class MainActivity extends Activity {
private BroadcastReceiver myReceiver = null;
class _RemoteTimeTrackerReceiver extends BroadcastReceiver {
#Override
public void onReceive (Context context, Intent intent) {
// call method in activity
reloadGui();
}
}
#Override
public void onResume() {
super.onResume();
if (myReceiver == null)
{
myReceiver = new _RemoteTimeTrackerReceiver();
IntentFilter filter = new IntentFilter(Global.REFRESH_GUI);
registerReceiver(myReceiver, filter);
}
reloadGui();
}
#Override
public void onPause() {
if (myReceiver != null)
{
unregisterReceiver(myReceiver);
myReceiver = null;
}
super.onPause();
}
void reloadGui() {}

Communication between C2DM BroadcastReceiver and multiple activities

I have an Android application which uses C2DM services (aka push).
I have a separate class which implements the registration process and which receives the data (and extends BroadcastReceiver).
I want to communicate this data to the activity which currently is in the foreground. The activity currently in the foreground may differ depending on user action.
What's the best way to communicate in between the receiver and the current activity?
Thanks.
I solved this problem by sending out a new broadcast from the C2DMReceiver class, which looked something like this.
The C2DMReceiver class:
public class C2DMReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("com.google.android.c2dm.intent.REGISTRATION")) {
handleRegistration(context, intent);
} else if (intent.getAction().equals("com.google.android.c2dm.intent.RECEIVE")) {
handleMessage(context, intent);
}
}
private void handleRegistration(Context context, Intent intent) {
// handle registration
}
private void handleMessage(Context context, Intent intent) {
Intent i = new Intent("push");
i.putExtras(intent);
// context.sendOrderedBroadcast(i, null);
context.sendBroadcast(i);
}
}
Another class I called PushReceiver. This is the class that will extend BroadcastReceiver and receive the broadcast sent by C2DMReceiver.
public class PushReceiver extends BroadcastReceiver {
public PushReceiver() {
}
#Override
public void onReceive(Context context, Intent intent) {
// do stuff
abortBroadcast();
}
public static class PushFilter extends IntentFilter {
private static final int DEFAULT_PUSH_PRIORITY = 1;
public PushFilter() {
this(DEFAULT_PUSH_PRIORITY);
}
public PushFilter(int priority) {
super("push");
setPriority(priority);
}
}
}
And the activity class, in this case called MyActivity. This should work well if you are using a base activity class that all other activities extend. That way every activity registers the receiver. By doing the register/unregister in onResume/onPause, you should be able to guarantee that only the current activity receives the broadcast. If not, you can send an ordered broadcast from C2DMReceiver and use priority in the PushFilter.
public class MyActivity extends Activity {
private PushReceiver pushReceiver;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// your onCreate method
pushReceiver = new PushReceiver();
}
public void onResume() {
super.onResume();
// your onResume method
registerReceiver(pushReceiver, new PushReceiver.PushFilter());
}
public void onPause() {
super.onPause();
// your onPause method
unregisterReceiver(pushReceiver);
}
}
In my case, I wrote the PushReceiver constructor to take a View and then "did stuff" with the view in the onReceive method. Without knowing more about what your trying to do, I can't elaborate on this, but hopefully this can provide a decent template to work from.

Categories

Resources