OnActivityResult called prematurely with Settings menu - android

In my Application, before going into the App, I have to check my wifi connection and take the user to the wifi settings if wifi is not enabled.
I dont want to use WifiManager.setWifiEnabled(); as I want to give the user the opportunity to set it.
I have referred the link, onActivityResult() called prematurely
and also, onActivityResult and the Settings Menu
But it is not working for me. The OnActivityResult() and onResume() is called almost at the same time I get into the Settings menu.
Here is my code,
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage("You are not currently connected to any network. Please turn on the network connection to continue.")
alert.setPositiveButton("Settings", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int arg1)
{
Intent intent = new Intent(android.provider.Settings.ACTION_WIRELESS_SETTINGS);
startActivityForResult(intent,SETTINGSCODE);
dialog.cancel();
}
});
alert.show();
In the onActivityResult(), I am checking the network state again which is called before changing the settings.
What can i do so that OnActivityResult()
will be called only after coming back from the settings menu?
Please help me with this issue..!!

This is how I solved this issue.
In reference to the answer posted for a similar question, I changed startActivityForResult() to startActivity() as the order of the action calls is like
startActivityForResult()
onActivityResult()
onCreate() (new activity)
setResult() or finish()
The control is taken to the settings page where the user can switch on/off the Wi-Fi and later come back to the app. :)

Related

Debugging in Android Studio, Intent only runs if I have a breakpoint after

This is very strange - I'm trying to programmatically open another app.
I found this link which I followed : Stackoverflow link
So my code is as follows - note it is being run inside a dialog.
Intent intentToResolve = new Intent(Intent.ACTION_MAIN);
intentToResolve.addCategory(Intent.CATEGORY_HOME);
intentToResolve.setPackage("com.android.launcher3");
intentToResolve.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
ResolveInfo ri = getPackageManager().resolveActivity(intentToResolve, 0);
if (ri != null)
{
Intent intent = new Intent(intentToResolve);
intent.setClassName(ri.activityInfo.applicationInfo.packageName, ri.activityInfo.name);
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
startActivity(intent);
}
This seems to only "close" my app and go to the home screen if I put a breakpoint in the code. If I just let it run with no breakpoint then nothing happens.
I have no idea why it would do this? Any ideas?
Thanks.
Edit: I've uploaded a video of it happening to YouTube so you can see exactly what I mean.
You'll see the first time I run it, it hits the breakpoint and the device goes to the home screen.
The second time I run it I have removed the breakpoint and nothing happens.
YouTube link
The fact that it works if you set a breakpoint would seem to indicate that there's some sort of timing problem.
You mention that you run this code from inside a dialog, which to me, reinforces the idea that you have a timing issue.
Try running this code from the Activity, after the dialog is closed.
I'd be very surprised if that doesn't fix the issue.
I assume that you are using the dialog to let the user pick what to launch.
So, instead of attempting to launch the other app from the dialog, communicate that info to it's parent activity, and have the Activity run this code after the dialog is closed.
When you show the dialog, you are doing so from an Activity - the dialog is displayed on top of your activity.
You are probably using a Dialog Builder to build the dialog, and then calling builder.create() to show the dialog.
In the builder code, you probably do something like:
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int id) {
// User clicked OK
}
})
In the onClick handler, the second parameter is the id of the item that was clicked. Use this info to decide what you want to launch. I'd suggest a separate method in the Activity to do the launching, and then call that from the onClick handler.
First thing is make sure do you have the app which belongs to ri.activityInfo.applicationInfo.packageName packagename. Code looks fine, the problem is the package name and the class you give inside setClassName()

How to close an app after showing a dialog?

I have almost completed my app development and I have even allowed a way to show up a toast message if there is no internet connection. I need to know how to close an app after showing a dialog if there is no internet connection?
My app is a webview app. So when user turn on the app, the app must check for internet connection. and display a dialog box if no network and the app must close after showing dialog.
OR
I don't want users to see the "webpage not available" page, so if there is no internet connection, the app must close after showing a dialog box with one button 'close'. Or is there any way to redirect users to a text in directory which shows no internet connection?
I need those code only; all the other codes have been done and are working properly.
Just invoke finish() to destroy activity in the onClick() function of dialog. Like:
...
builder.setMessage('There is no connection!! Please close the activity!')
.setPositiveButton('close', new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
finish();
}
})
...
You can popup a dialog after checking the internet connectivity as follows
new AlertDialog.Builder(this)
.setTitle("Connection Error")
.setMessage("You are not connected to Internet.")
.setPositiveButton("Close", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// finish the activity here or,
// redirect to another activity
}
})
.show();
You can check your internet connectivity before setting the view to the activity.
Like :
if(connnected){
setContentView(layoutId);
}else{
show a tosat with information no internet;
finish activity.
}
call finish() method on your activity once user clicks on dialogue

Best UI design to handle no internet connection

My app like many others needs an internet connection constantly. In my main activity I have:
#Override
public void onStart() {
if (!isOnline()) {
Intent disconnected = new Intent(this, Disconnected.class);
startActivity(disconnected);
}
else {
...
}
}
The Disconnected activity displays a TextView with a message and a retry Button.
Now the problem with this is that if the user presses back he immediately ends up in the Disconnected activity again and isn't able to exit the application using back.
What's an elegant way to handle no internet connection? My main activity is a ListView, should I just have hidden Views that only appear when there's no connection? (I don't feel this is the right way though).
There can be several options
Option 1:
Use AlertDialog to show the disconnection. Set it to non cancelable and with two buttons like retry and exit.
Option 2:
start disconnection activity using start activity for result if the network disconnection occurs. In the new activity there is a retry button. If retry is set the set OK and finish. And if back button press set CANCEL. now in first activity in onActivityResult if you get RESULT_OK then retry connection.
If your starting Activity is just the if statement, and only meant for checking if the user have an internet connection, you could simply finish that Activity when you enter the Disconnected Activity
You do this by calling StartActivity with the FLAG_ACTIVITY_CLEAR_TOP flag set.
#Override
public void onStart() {
if (!isOnline()) {
Intent disconnected = new Intent(this, Disconnected.class);
disconencted.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(disconnected);
}
else {
... // Here you would want to do the same thing;
// if not, the user could navigate back to this activity as well
}
}
I couldn't test this, but I think it should work.

Ask user to turn on Wi-Fi

I have an app which almost always needs to know the user location.
When I need to access a location, I do this:
final AlertDialog.Builder builder = new AlertDialog.Builder(
MapScreen.this);
builder.setTitle("MyAppName");
builder.setMessage("The location service is off. Do you want to turn it on?");
builder.setPositiveButton("Enable location",
new DialogInterface.OnClickListener() {
#Override
public void onClick(
final DialogInterface dialogInterface,
final int i) {
startActivity(new Intent(
android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
}
});
builder.setNegativeButton("Continue without location", null);
builder.create().show();
However, the GPS gives me some info that isn't always precise enough. Wi-Fi always gives me enough precission, so I want to ask the user to turn on the Wi-Fi the same way I ask them to turn on the location. I do not want to just turn it on, I want the user to be notified about it, and to manually enable it.
Is there any Intent to bring the WiFi menu to the user?
Following intent shows the wireless settings such as Wi-Fi, Bluetooth and Mobile networks:
startActivity(new Intent(Settings.ACTION_WIRELESS_SETTINGS));
For the complete list of Settings: https://developer.android.com/reference/android/provider/Settings.html
For the documentation on the startActivity method:
https://developer.android.com/reference/android/app/Activity.html#startActivity(android.content.Intent)
(keep in mind startActivity is just throw and forget, if you want to capture the response of what the user did out there you could instead call startActivityForResult, probably not needed in this case)
You can try
Intent i = new Intent(Settings.ACTION_WIRELESS_SETTINGS);
startActivity(i);
The previous answers were quotting the "Settings.ACTION_WIRELESS_SETTINGS", but it is too general, as it is going to open the settings of the general wireless connection while the question is about wifi only.
I'm using "Settings.ACTION_WIFI_SETTINGS" as follows
Intent turnWifiOn = new Intent(Settings.ACTION_WIFI_SETTINGS);
startActivity(turnWifiOn);
Note: It's not going to open just a dialog, but an activity instead.

How to finish an android application?

I need to finish an android application. For that i wrote
#Override
public void onBackPressed() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure You want to exit")
.setCancelable(false)
.setPositiveButton("YES"),
new DialogInterface.OnClickListener() {
// On
// clicking
// "Yes"
// button
public void onClick(DialogInterface dialog,int id) {
System.out.println(" onClick ");
closeApplication(); // Close Application method called
}
})
.setNegativeButton("NO"),
new DialogInterface.OnClickListener() {
// On
// clicking
// "No"
// button
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
private void closeApplication() {
System.out.println("closeApplication ");
this.finish();
}
}
But if any activity is not finished in the application, when i tried to exit the application that activity is finished first and the application is not exiting.. i tried 2 times to exit this application... How i can finish all the activities in an application when i need to exit... or is there any way to finish the entire application
To close application just call:
android.os.Process.killProcess(android.os.Process.myPid());
Otherwise due-to specific life-cycling of Android activities you can't be sure that application is closed/killed.
whenever you are starting a new activity use
myintent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(myintent);
and in manifest file mention that activity as
<activity android:name=".<Activity Name>" >
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
Put this into your onClick or in onBackPressed:
moveTaskToBack(true);
finish()
Please read first this post from Google Android Developer Advocate Reto Meier :
When to Include an Exit Button in Android Apps (Hint: Never)
What is th symptom that make you want to add an exit button ? If you need to clear the activity stack and always restart with a specific Activity, maybe you just have to tweak your activity manifest declaration with attributes like : android:clearTaskOnLaunch
Android is made in such a way that virtually NO application that was once opened, is closed.
Before mis-interpreting the statement, understand this.
"Whenever you exit your app, Android saves all the things the app was doing (called its state) and pushes the app in the background, calling the onStop() method. this is the new state of the application then, where the app isn't running, but isn't flushed out of the memory too. whenever you start the app again, it is resumed from the frozen state. Only when the memory, where frozen apps are kept, starts getting full, the Android GC flushes the app."
So conceptually, nothing goes out. when you hit "back" button while ur on the first activity, Android bundles the app and data, and freezes it.
according to this answer,
just write this.finishAffinity(); and done!
I have an application with several Activities. I extended my Application class, and included a variable numActive. This is initialized to 0. Within each activity's onStart(), numActive is incremented, and in onStop() it is decremented. If the count reaches zero, the user has left my application entirely, and I close down my background tasks.
Shameless copy of NeTeInStEiN's answer as I found it so useful (please up-vote his answer): Sending a running application to background programmatically
You can use either:
boolean sentAppToBackground = moveTaskToBack(true);
if(!sentAppToBackground){
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
}
More information here: http://developer.android.com/reference/android/app/Activity.html#moveTaskToBack(boolean)
Or simply:
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
this.startActivity(i);
According to Romain Guy a Android Framework Engineer, "You cannot simulate a press on the Home key.". So beware...
Check: http://osdir.com/ml/Android-Developers/2010-03/msg01887.html
Updated this answer according to: moveTaskToBack(true) returns false always
To Close the Application, you can also take "System.exit(0)" 0 is standard or use any exit code.

Categories

Resources