Prevent offline mode or reroute to URL - android

I would like my android app to be only available online.
If user has no internet connection, I would like to prevent the user from using any content from it, and to show him a popup with a quick message and a browser link to the play store.
I have seen other questions with answer about checking connection status, but I am not sure
1) where in my app to put this code
2) how to prevent the user from reaching any content at all if he is offline
2) what is the best solution to display a popup with a short text message and a link to the playstore
Thanks for your help

For your first question, you could easily close the app on startup:
ConnectivityManager connectivityManager
= (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
if(activeNetworkInfo == null){
finish();
}
This wouldn't give the user any indication that your app was restricted without WiFi but it'd do the job, you could easily add dialog before closing. This would need to be placed in onCreate() of your main launcher activity.
Secondly:
AlertDialog.Builder builder = new AlertDialog.Builder(mActivity)
.setTitle(title)
.setMessage(message)
.setPositiveButton("Play Store", new Dialog.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
final Intent MyIntent = new Intent(Intent.ACTION_VIEW,
Uri.parse("market://details?id=myid"));
startActivity(MyIntent);
}
})
.setNeutralButton("No thanks!", new Dialog.OnClickListener(){
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
});
builder.create().show();
This will give a small popup and when clicked will take the user to the market.

Related

Android Toast text on next activity

I have an intent and I want a toast to show as soon as we get to that intent. Code:
Toast.makeText(this,"Please enable internet connection",Toast.LENGTH_LONG).show;
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
As you can see im going to the android setting, and I want it to prompt them to activate WiFi. Any ideas or better ways to do this?
I would rather recommend to show a dialog which asks the user to enable the wifi connection for him and then call WifiManager.setWifiEnabled() to switch on wifi.
This way, you don't have to leave your app. It is not possible to show an toast from an external activity.
Quick alternate approach:
Don't show a toast. Display a dialog saying "Please enable internet connection" and when the user presses the "OK" button fire the intent to send him to the settings page.
You could use a dialog, here's an example
AlertDialog.Builder builder = new AlertDialog.Builder(context);
builder.setTitle("WiFi Settings");
builder.setMessage("Please enable internet connection");
builder.setCancelable(false);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
// Launch settings activity
startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS)););
}
});
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
dialog.cancel();
}
});
builder.create().show();

Forcing the users to update my app

how can i force user to update my app by going to Google play store? if there's a new update a dialog will show which will have 2 buttons either update app or exit app.
Wont allow app to run unless latest version.
I am using eclipse and i cant migrate to android studio because of some project issues .
please help
Use Dialogs when your main Activity starts. Just redirect the user to the URL of your app on the PlayStore if he accepts, and exit the app (here are examples on how doing it).
Took from Anrdoid documentation :
public class YourDialogFragment extends DialogFragment {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.please_update)
.setPositiveButton(R.string.Ok, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// launch a browser with your PlayStore APP URL
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// Exit the app
android.os.Process.killProcess(android.os.Process.myPid());
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
Now, when you create an instance of this class and call show() on that object, the dialog appears as shown in figure 1.
Just create an instance of it and use the show() method in your onCreateDialog from your MainActivity.
Note that Dialogs uses Fragments, which requieres API level 11. (You should be able to check the API level you're building to in your build.gradle file)
Use dialogs as mentioned by Noafix. Call an alert dialog when your version mismatches.
Also set dialog cancelable to false so that user cant remove dialog by pressing back!
private void showDialog()
{
final android.app.AlertDialog.Builder alertDialogBuilder = new android.app.AlertDialog.Builder(this);
alertDialogBuilder.setTitle("Update");
alertDialogBuilder.setMessage("Please update to continue?");
alertDialogBuilder.setIcon(R.drawable.warning);
alertDialogBuilder.setCancelable(false)
alertDialogBuilder.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface arg0, int arg1) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + appPackageName)));
}
});
// Add a negative button and it's action. In our case, just hide the dialog box
alertDialogBuilder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finishAffinity();
}
});
// Now, create the Dialog and show it.
final android.app.AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.show();
}
You could get your version name as:
versionName = getApplicationContext().getPackageManager().getPackageInfo(getApplicationContext().getPackageName(), 0).versionName;
Now get your current version from your server using any rest client http calls and check with your version:
if(!versionName.equals(version)){showDialog();}
Note: For this you should implement a version file in server in which you must add new version in that file so that using http calls your app can get the new version name and check with app version!
Implement a way for the app to check if it is the latest version or not.
You can do this by hosting an update file that contains information on what the latest version is. This file is commonly in json format but can also be in any format you prefer. The app would have to query this update file and if the current version of the app is less than the version indicated in the update file, then it would show the update prompt.
If the app determines that an update is needed, open a dialog prompt then open the app's play store page
To launch a dialog prompt refer to the official Dialogs guide. Given that the question is not "how to launch a dialog" I will focus on discussing how to update the app.
To open google play store to a particular app page you must launch an intent with the View action and Market scheme uri like so
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=" + appPackageName)));
Be wary that if the device does not have google play store installed, then this will throw an exception. It is also possible for other apps to receive this type of intent and in the case where multiple apps can receive the intent, an app picker dialog will appear.
Challenges:
If the app must check for updates and can only run if it is the latest version, then the app cannot run if the device is not connected to the internet.
The app will have a hard dependency on google play store and cannot run if an update is needed and there is no play store on the device
If the update file is unavailable for any reason then the app will not run as well
You absolutely need the users to update to continue using the app, you could provide a simple versioning API. The API would look like this:
versionCheck API:
->Request parameters:
int appVersion
-> Response
boolean forceUpgrade
boolean recommendUpgrade
When your app starts, you could call this API that pass in the current app version, and check the response of the versioning API call.
If forceUpgrade is true, show a popup dialog with options to either let user quit the app, or go to Google Play Store to upgrade the app.
Else if recommendUpgrade is true, show the pop-up dialog with options to update or to continue using the app.
Even with this forced upgrade ability in place, you should continue to support older versions, unless absolutely needed.
try this: First you need to make a request call to the playstore link, fetch current version from there and then compare it with your current version.
String currentVersion, latestVersion;
Dialog dialog;
private void getCurrentVersion(){
PackageManager pm = this.getPackageManager();
PackageInfo pInfo = null;
try {
pInfo = pm.getPackageInfo(this.getPackageName(),0);
} catch (PackageManager.NameNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
currentVersion = pInfo.versionName;
new GetLatestVersion().execute();
}
private class GetLatestVersion extends AsyncTask
{
private ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected JSONObject doInBackground(String... params) {
try {
Document doc = Jsoup.connect(urlOfAppFromPlayStore).get();
latestVersion = doc.getElementsByAttributeValue
("itemprop","softwareVersion").first().text();
}catch (Exception e){
e.printStackTrace();
}
return new JSONObject();
}
#Override
protected void onPostExecute(JSONObject jsonObject) {
if(latestVersion!=null) {
if (!currentVersion.equalsIgnoreCase(latestVersion)){
if(!isFinishing()){
showUpdateDialog();
}
}
}
else
background.start();
super.onPostExecute(jsonObject);
}
}
private void showUpdateDialog(){
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("A New Update is Available");
builder.setPositiveButton("Update", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse
("market://details?id=yourAppPackageName")));
dialog.dismiss();
}
});
builder.setNegativeButton("Cancel", new
DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
background.start();
}
});
builder.setCancelable(false);
dialog = builder.show();
}

android dialog wont close after opening system location settings

I have a dialog that prompts users to enable gps location if it's not enabled.
After opening the settings, and the user enableing gps, and pressing the back button from the location settings screen they come back to the app, but the dialog is still visible.
Here is the code for the button clicked.
// On pressing Settings button
alertDialog.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
mContext.startActivity(intent);
dialog.dismiss();
}
});
My question is why does the dialog.dismiss() not close the dialog, I have also tried dialog.cancel() with same result. Is there something I should be doing after opening the settings screen?
Thanks,
I have exactly this code in my Activity:
private void showLocationDisabledInfo() {
final Context c = this;
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setMessage("TEST");
builder.setPositiveButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
c.startActivity(intent);
}
});
builder.setNeutralButton(R.string.cancel, null);
builder.create().show();
}
and it does close the dialog automatically, no matter what button I click. It's from my application, and it was tested on devices with APIs 8 and 10, and emulator running API 17. The only difference (possibly) between our codes is the value of mContext. Please provide the whole code responsible for setting up the dialog and the environment in which you've seen described behavior.

Start activity from another activity?

I want in my application this functionality:
When i start my app
-check if there is interne access : if yes {
start LogInActivity { if login is succesfull
dialog:"synced!" for 3second
else
dialog:"no synced!" for 3second
}
}
dialog:"no synced!"
startMainActivity
I want the first activity just to performs checks.Not to be visible and if there is internet
then forward to login Activity else login to Main activity
This is because i want my app to be used without interner.But for the logged users it will download from web service some information to be stored in Shared Preferences.Any help?
The best way is to create a small function which checks both for wifi and mobile net as follows :-
/**
* Function to check whether internet connection is available or not
*
* #return true - if net is available
*/
public boolean haveNetworkConnection() {
mHaveConnectedWifi = false;
mHaveConnectedMobile = false;
mConnectivityManager = (ConnectivityManager) mContext
.getSystemService(Context.CONNECTIVITY_SERVICE);
mNetworkInfo = mConnectivityManager.getAllNetworkInfo();
for (NetworkInfo mNetInfo : mNetworkInfo) {
if (mNetInfo.getTypeName().equalsIgnoreCase("WIFI"))
if (mNetInfo.isConnected())
mHaveConnectedWifi = true;
if (mNetInfo.getTypeName().equalsIgnoreCase("MOBILE"))
if (mNetInfo.isConnected())
mHaveConnectedMobile = true;
}
return mHaveConnectedWifi || mHaveConnectedMobile;
}
Now in your code just do :-
if(haveNetworkConnection){
// do something
}else{
// no internet
}
The advantage is that we are checking for both wifi and mobile net...
Hope the explanation was useful....
Just create a third activity that starts first and on the onCreate of that activity you run your code and call other activity.
Also you could show a splash screen on this third activity, while you decide which activity to show.
You'll want to either use startActivity() or startActivityForResult().
The advantage of startActivityForResult() is that you can receive data back from the activity you started, upon its completion.
To launch your other activity:
if(connection/login fails){
Intent loginfailed = new Intent(MainActivity.this, loginfailedactivity.class);
startActivity(loginfailed);
}
else {.....}
Here is what I did to make sure there was a wifi connection:
private void checkWifiConnection(String menuUrl){
ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(mWifi.isConnected()){
LoadJSON lJs = new LoadJSON();
lJs.execute(menuUrl);
} else {
AlertDialog.Builder ab = new AlertDialog.Builder(context);
ab.setCancelable(true);
ab.setTitle("No Connection");
ab.setMessage("Your device is currently not connected to the Internet, please check your connection and launch the app again.");
ab.setInverseBackgroundForced(true);
ab.setPositiveButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
MainActivity.this.finish();
}
});
AlertDialog alert = ab.create();
alert.show();
}
You could insert an Intent call in the if statement that launches your Activity

Force Close trying to launch a market page from and alert box

Can anyone figure out why this causes a force close??
void failbox(){
// Create the alert box
AlertDialog.Builder alertbox = new AlertDialog.Builder(this);
// Set the message to display
alertbox.setMessage(R.string.fail);
alertbox.setPositiveButton("Get Busybox", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse("market://details?id=stericson.busybox"));
}
});
// set a negative/no button and create a listener
alertbox.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
// do something when the button is clicked
public void onClick(DialogInterface arg0, int arg1) {
}
});
// show the alert box
alertbox.show();
}
Thanks in advance!
If you're getting the forced close in the emulator, that's just how it is, as best I can tell. You cannot access the market through the market app from an emulator.
Does your app still crash when run on a real Android device?
(Of course, some folks have figured out sneaky ways to get to the market from an emulator. See How to install Android Market App on the emulator?)

Categories

Resources