In an application I am developing I have some code that attempts to submit information to the internet. If the connection can not be made, I pop up a toast message instructing the user to check the network connection.
Toast.makeText(getApplicationContext(), "Check network connection.", Toast.LENGTH_SHORT).show();
The problem I have is the toast message comes up no matter what the user is looking at! Even if the user is in a different app and my app is running in the background! This is not the desired behavior as I send a notification to the user if network activity fails. I only want the toast message to appear if the user is in the activity that is generating the network activity. Is there a way to do this?
If this is not possible my idea was to just put some kind of visual element in my activity - rather than display a toast message.
Thank You!
You can use a boolean class member in order to keep track of activity state changes.
public class YourClass extends Activity {
private boolean mIsResumed = false;
#Override
public void onResume() {
super.onResume();
mIsResumed = true;
}
#Override
public void onPause() {
super.onPause();
mIsResumed = false;
}
public boolean isResumed() {
return mIsResumed;
}
}
Then you can use something like this:
if (isResumed()) {
//show Toast
}
Use a dynamic BroadcastReceiver. Your background service will broadcast an Intent when something happens. All of your app's activities will register a dynamic BroadcastReceiver which will listen for these events. When such event occurs it will show a toast. When none of your activities are running nothing will happen.
Inside your service
public static final ACTION_SOMETHING = BuildConfig.APPLICATION_ID + ".ACTION_SOMETHING";
public void doSomething() {
// ...
// Show toast if app is running. Or let the app react however you please.
LocalBroadcastManager.getInstance(this).sendBroadcast(new Intent(ACTION_SOMETHING));
// ...
}
Of course you can put additional information in the Intent as extras and access them in the BroadcastReceiver.
Inside your activities
private final IntentFilter onSomethingIntentFilter = new IntentFilter(MyService.ACTION_SOMETHING);
private final BroadcastReceiver onSomething = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// This check seems redundant but it's not. Google it.
if (MyService.ACTION_SOMETHING.equals(intent.getAction()) {
// Show toast here.
}
}
};
public void onResume() {
super.onResume();
// Start listening for events when activity is in foreground.
LocalBroadcastManager.getInstance(this).registerReceiver(onSomething, onSomethingIntentFilter);
}
public void onPause() {
super.onPause();
// Stop listening as soon as activity leaves foreground.
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(onSomething);
} catch (IllegalArgumentException ex) {}
}
You may want to pull this code to a common activity parent, a BaseActivity, so you don't repeat yourself.
This is a common case of Provider-Subscriber pattern. Another implementation would be an EventBus.
Keeping it simple, try adding a boolean flag in Activity and set its value as true in onResume & false in onPause. Then display the toast if the boolean flag is true.
Related
I am making an android app in java in which I need to trigger some database requests whenever an activity is completely destroyed which would probably happen if the user presses the back button or leaves the app itself... But the onDestroy() function in my app is randomly getting triggered even when the user is still on the activity... I guess the probable reason for this is configuration changes but I am not able to figure out a proper solution for this.
Is there a way we could exactly detect when an activity is left by a user avoiding any in-page configuration changes??
The onDestroy() that I am using is this:
#Override
protected void onDestroy() {
/// do smthng
super.onDestroy();
}
Any help would be appreciated!!
Solved:
Thank you for the answer guys... For me onStop() worked out perfectly and it is working in every case whether it might be pressing the back button or exiting the activity or the app itself!!
If you want to check if the user ended the activity, meaning pressed back, do this:
#override
public void onBackPressed(){
//do something before we finish the activity
super.onBackPressed();
}
If you want to check when user, goes to next activity, then resturns to the same activity:
#override
public void onResume(){
//do something when return back to this activity
super.onResume();
}
#override
public void onPause(){
//do something before going to another activity
super.onPause();
}
onDestroy is called when the activity is destroyed or finished and not guaranteed to be called always, don't depend on it
We can check on whether our application is foreground or background based on the activity entering and exiting the foreground by implementing ActivityLifecycleCallbacks.
Good reference : https://medium.com/#iamsadesh/android-how-to-detect-when-app-goes-background-foreground-fd5a4d331f8a
Quoting from the above article,
#Override
public void onActivityStarted(Activity activity) {
if (++activityReferences == 1 && !isActivityChangingConfigurations) {
// App enters foreground
}
}
and,
#Override
public void onActivityStopped(Activity activity) {
isActivityChangingConfigurations = activity.isChangingConfigurations();
if (--activityReferences == 0 && !isActivityChangingConfigurations) {
// App enters background
}
}
by which we can make sure that our app is in foreground or not. Here you always have the control of what activity is in foreground based on which you can check and execute the logic.
I've made an app that is receiving some data from a TCP Client to my TCP Server that store the data in SQlite DB, and actually i've made a recyclerView where to visualize all that data but now my issue is what i'm trying like 2 weeks to refresh the recyclerView in real Time, i mean if a TCP Client will send a new package to my TCP Server and if i'm in the activity with the recyclerView the data have to be added dynamically.
I will also accept any type of tips and suggestions on how to improve my app.
Actually it's my 1st app i've ever created in Android.
HERE you can find my Server(TCPServer),RecyclerViewAdapter,Adapter(constructor),allert.java(class where i invoke the RecyclerViewAdapter.
Hope someone will be able to help me and ill be very grateful.
Try sending broadcast method. Here are the steps :
Make a inner class that extends BroadcastReceiver in your activity.
private class ExampleBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//do stuffs here, e.g. getting extras from intent
}
Declare a instance of the class outside any methods.
public class MainActivity extends AppCompatActivity {
private ExampleBroadcastReceiver exampleBroadcastReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
//stuffs
}
}
Override onResume method. Initialize the instance you just made in this method. Then, register it with a intent-filter. This will make sure that your broadcast receiver ready when user open the activity.
#Override
protected void onResume() {
super.onResume();
IntentFilter filter = new IntentFilter();
filter.addAction("com.example.MainActivity");
exampleBroadcastReceiver = new ExampleBroadcastReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(exampleBroadcastReceiver, filter);
}
Override onPause method and unregister your receiver.
#Override
protected void onPause() {
super.onPause();
try {
LocalBroadcastManager.getInstance(this).unregisterReceiver(exampleBroadcastReceiver);
} catch (IllegalArgumentException e) {
if (!e.getMessage().contains("Receiver not registered")) {
// unexpected, re-throw
throw e;
}
Make sure you use ArrayList for dynamic data.
Whenever you receive data from server, after you store them in your database, send a broadcast with extras contains data you want to display in your activity.
EDITED
I registered the receiver using an instance of LocalBroadcastManager.
I want to make a cloud synchronization everytime my app is brought to front and a second time if the app disappears in background.
So I overwrote the onStart and onStop event methods of my activity:
#Override
protected void onStart() {
super.onStart();
doSync();
}
#Override
protected void onStop() {
doSync();
super.onStop();
}
Ok, that works fine for me but I found out that these methods are also called if I start a new activity (f.e. SettingsActivity.class) within my app (onStop) and come back to the main activity (onStart).
Is there a good way to ignore the calls of my own activities and only react on calls from "outside", f.e. I only want to synchronize if the user stops the app by pressing the home button and I also want to synchronize only if the user returns to the app by starting it from the app dreawer or app switcher?
+++ SOLUTION +++
Now I found a solution for my problem and I want to share it. Maybe it's not the best way because it's no SDK-based functionality but it works and it's quite simple.
I declared a flag, set it to false when the activity is created. Everytime I start another activity in the same app, I will set the flag to true and check its state in onPause and onResume.
public class MainActivity extends Activity {
private boolean transition;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
transition = false;
}
private void startSettingsActivity() {
transition = true;
Intent intent = new Intent(this, SettingsActivity.class);
startActivity(intent);
}
private void doSync() {
// all steps for the cloud synchronization
}
#Override
protected void onResume() {
super.onResume();
if (!transition) {
// this is the case the user returns from
// the app drawer or app switcher or starts
// the app for the first time, so do sync
doSync();
} else {
// this is the case the user returns from another
// activity, so don't sync but reset the flag
transition = false;
}
}
#Override
protected void onPause() {
if (!transition) {
// this is the case the user presses the home button or
// navigate back (leaves the app), so do final sync
doSync();
} else {
// this is the case the user starts another activity, but
// stays in the app, so do nothing
}
super.onPause();
}
}
I have a outGoingCall broadcast receiver.
basically I want it to intercept any outgoing call and show a dialog for certain pre-defined numbers.
so I made this broadcast init an activity which inits an FragmentDialog which init a AlertDialog.
When the user click "no"
I want to stop the call from happening.
I know setResultData(null); in the broadcast should do it.
But how can I pass the dialog result to the broadcast ?
there is no onActivityResult() in a broadcast.
I know how to pass it till the activity only.
fragmentDialog code:
public class YesNoDialogFragment extends DialogFragment {
private YesNoDialogFragmentListener mListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
// Instantiate the NoticeDialogListener so we can send events to the
// host
mListener = (YesNoDialogFragmentListener) activity;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(activity.toString()
+ " must implement NoticeDialogListener");
}
}
here is my activity code:
public class MainActivity extends FragmentActivity implements
YesNoDialogFragmentListener {
public static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
showYesNoDialog();
}
#Override
public void onDialogPositiveClick() {
// how to send result to receiver ??
finish();
}
here is my receiver code:
#Override
public void onReceive(final Context context, final Intent intent) {
Log.v(Constants.LOGTAG, "OutgoingCallReceiver onReceive");
if (intent.getAction()
.equals(OutgoingCallReceiver.OUTGOING_CALL_ACTION)) {
Log.v(Constants.LOGTAG,
"OutgoingCallReceiver NEW_OUTGOING_CALL received");
// get phone number from bundle
String phoneNumber = intent.getExtras().getString(
OutgoingCallReceiver.INTENT_PHONE_NUMBER);
if ((phoneNumber != null)
&& phoneNumber
.equals(OutgoingCallReceiver.ABORT_PHONE_NUMBER)) {
Toast.makeText(
context,
"NEW_OUTGOING_CALL intercepted to number 123-123-1234 - aborting call",
Toast.LENGTH_LONG).show();
Intent i = new Intent(context, MainActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
SharedPreferences sharedPreferences = context
.getSharedPreferences(Constants.SHARED_PREF_NAME,
Context.MODE_PRIVATE);
boolean isBloacked = sharedPreferences.getBoolean(
Constants.IS_NUMBER_BLOCKED, true);
if (isBloacked) {
// dialog and then:
setResultData(null);
}
}
as you can see i tried to share the activity result via shared preferences, how come the code is async and the setResultData(null); is called before the dialog is shown?
from what I know there is no way to end the call besides setResultData(null);
You have to go through an activity (or a fragment) and then pass it to the receiver. Whenever you start a dialog, it has a parent activity, and that is where the result is sent. Just add something to your activity that passes the result on to your receiver.
You might actually consider altering your design to put more of your logic into the activity. Receivers are generally intended to be pretty lightweight objects that receive notification of something, pass it on to somewhere else. and then go away. Anyway, I obviously don't know your code, so maybe this doesn't make sense.
EDIT
Sorry, I understand your problem better now. I'm used to only working with setResultData when one activity has launched another activity, and the 2nd one wants to send something back to the 1st one. But you are using it to stop an ordered broadcast, right?
Unfortunately, Android does now allow you to do what you are trying to do. This section of the doc specifically says that you cannot show a dialog from within a broadcast:
http://developer.android.com/reference/android/content/BroadcastReceiver.html#ReceiverLifecycle
I think what you need to do is always return setResultData(null) right after starting your activity. If the user then clicks "no" in your dialog, then you are done. But if the user clicks "yes" (I'm assuming there is a "yes") then you would have to go ahead and make the call, and make sure you don't catch it again in your receiver.
Does that make sense? Sorry for my confusion earlier.
What I want to create is a popup style application.
I have a service in the background - something arrives on the queue and i want an activity to start to inform the user - very very similar to the functionality of SMSPopup app.
So I have the code where something arrives on the queue and it calls my activity.
However for some reason the activity always shows on top of the originally started activity instead of just appearing on the main desktop of the android device.
As an example:
I have the main activity which is shown when the application is run
I have the service which checks queue
I have a popup activity.
When i start the main activity it starts the service - I can now close this.
I then have something on the queue and it creates the popup activity which launches the main activity with the popup on top of it :S How do I stop this and have it behave as i want...
The popup class is :
public class SMSPopup extends Activity implements OnClickListener{
public static String msg;
#Override
public void onCreate(Bundle bundle){
super.onCreate(bundle);
// Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_LONG).show();
this.setContentView(R.layout.popup);
TextView tv = (TextView)findViewById(R.id.txtLbl);
Intent intent = getIntent();
if (intent != null){
Bundle bb = intent.getExtras();
if (bb != null){
msg = bb.getString("com.andy.tabletsms.message");
}
}
if(msg == null){
msg = "LOLOLOL";
}
tv.setText(msg);
Button b = (Button)findViewById(R.id.closeBtn);
b.setOnClickListener(this);
}
#Override
public void onClick(View v) {
this.finish();
}
}
and I call the activity from a broadcast receiver which checks the queue every 30 seconds or so :
if(main.msgs.size()>0){
Intent testActivityIntent = new Intent(context.getApplicationContext(), com.andy.tabletsms.work.SMSPopup.class);
testActivityIntent.putExtra("com.andy.tabletsms.message", main.msgs.get(0));
testActivityIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(testActivityIntent);
}
The layout is here : http://pastebin.com/F25u6wdM
This is against the design practice suggested by Android. See http://developer.android.com/guide/topics/ui/notifiers/notifications.html
A background Service should never launch an Activity on its own in order to receive user interaction.
You could show the message in a Toast and/or notification. From the notification, you could start a new intent.