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();
}
Related
Good Day, So I have this program where the user will scan a QR code and get the value of it in the SQLite database but before I get the value the dialog box pops-up messaging me that "there is no participant found". Below is my code:
This is my onStart override.
#Override
protected void onStart()
{
super.onStart();
getparticipantid = tvParticipantID.getText().toString();
etparticipantidvalue.setText(getparticipantid);
getParticipantIbeam();
}
This is my activity where it will load the data from the database once the user scans the QR code.
private void getParticipantIbeam()
{
SQLiteFunctionUlitity.GameIBeamParticipant memberInfo = SQLiteFunctionUlitity.getparticipantIbeam(getparticipantid, mDbHelper.getSqliteObjectWithReadable());
if (memberInfo != null)
{
tvParticipantName.setText(memberInfo.getParticipantName());
tvParticipantNation.setText(memberInfo.getParticipant_nationality());
tvParticipantCategory.setText(memberInfo.getCategory());
tvWave.setText(memberInfo.getWave_number());
tvCategory.setText(memberInfo.getCategory());
}
else
{
Context context = this;
AlertDialog.Builder builder1 = new AlertDialog.Builder(context);
builder1.setMessage("No Participant found in the Game.");
builder1.setCancelable(true);
builder1.setPositiveButton("Scan Again", new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
Intent intent = new Intent(GameiBeamLineTracing.this, ScanGameIbeam.class);
startActivity(intent);
finish();
}
});
builder1.setNegativeButton("Close", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which)
{
onStop();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
}
As you can see I call the getParticipantIbeam activity in onStart method but when I call it, it reads the else statement rather than the if statement.
I know this is a simple if else statement and lifecycle but I am desperate to know the answer.
I have used the library for scanning QR code, its very simple it may help you.
QR Code implementation library for android, Click here (blikoon)
Definitely this library will solve your all QR Code related issue and dont forget to implement run time permissions like photo , gallery etc.
When I login to my android application for the first time, its works perfectly, after I logout, when I try to login its doesn't open the activity,
I have cleared FragmentStack and saved preferences below.
clearFragmentStack();
clearSavedPrefs();
But When i disable or destroy the application from recent apps or delete data from settings. its working normally.
How can I solve this issue. Please find the code below.
builder.setPositiveButton(android.R.string.ok,new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User clicked OK button
httpClientService.canCanLogout(new ResponseCallBack<BaseDao>() {
#Override
public void onDataReceived(
HttpResponseHolder<BaseDao> responseHolder) {
if (responseHolder.getErrReason() != null) {
generalProperListener.showShortToastMessage(responseHolder.getErrReason());
} else {
startUserLoginFragment();
ct.event.push("Logout");
}
}
});
}
});
I have cleared the answer.
Where I have concat the previous string value.
//old
UserAddress.ADDR_URL +="?".concat(paramsString);
//new
UserAddress.ADDR_URL =URL+"?".concat(paramsString);
New to Android... I understand Dialogs are asynchronous. But I really can't get my head around the flow for confirming an action. Can someone please explain the flow?
I want to save a file on the sdcard. The Activity prompts the used for the filename. Then it checks to see if the file exists. If it exists, it needs to prompt the user to confirm if they want to overwrite it. Then it proceeds to erase and write the file.
I know you can't hold execution waiting for the response. How then would this common flow work in Android?
Thanks
I am not 100% it is what you are looking for, but here is a link to the Android documentation explaining how we should display Confirmation and Acknowledgement popups using the "Android standard way":
http://developer.android.com/design/patterns/confirming-acknowledging.html
I do not know the exact flow, I suppose it would depend on how the application was written. I would check for the file if it existed call the dialog windows then if the Ok/Yes/Confirm is pressed overwrite the file.
Dialogs | Android Developers - Has an excellent code example
public class FireMissilesDialogFragment 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.dialog_fire_missiles)
.setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// FIRE ZE MISSILES! AKA Overwrite your file.
}
})
.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog AKA do nothing
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
I know it's slightly silly example but basically check for the file (if exist) > Call Dialog (if yes)> Overwrite.
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?)
How can I implement a Preference that displays a simple yes/no confirmation dialog?
For an example, see Browser->Setting->Clear Cache.
That is a simple alert dialog, Federico gave you a site where you can look things up.
Here is a short example of how an alert dialog can be built.
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Do you really want to whatever?")
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Toast.makeText(MainActivity.this, "Yaay", Toast.LENGTH_SHORT).show();
}})
.setNegativeButton(android.R.string.no, null).show();
Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.
Unfortunately, it is in the com.android.internal.preference package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).
Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).
You can then add it to your preferences.xml like any other Preference. Example:
<com.example.myapp.YesNoPreference
android:dialogMessage="Are you sure you want to revert all settings to their default values?"
android:key="com.example.myapp.pref_reset_settings_key"
android:summary="Revert all settings to their default values."
android:title="Reset Settings" />
Which looks like this:
Use Intent Preference if you are using preference xml screen or you if you are using you custom screen then the code would be like below
intentClearCookies = getPreferenceManager().createPreferenceScreen(this);
Intent clearcookies = new Intent(PopupPostPref.this, ClearCookies.class);
intentClearCookies.setIntent(clearcookies);
intentClearCookies.setTitle(R.string.ClearCookies);
intentClearCookies.setEnabled(true);
launchPrefCat.addPreference(intentClearCookies);
And then Create Activity Class somewhat like below, As different people as different approach you can use any approach you like this is just an example.
public class ClearCookies extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
showDialog();
}
/**
* #throws NotFoundException
*/
private void showDialog() throws NotFoundException {
new AlertDialog.Builder(this)
.setTitle(getResources().getString(R.string.ClearCookies))
.setMessage(
getResources().getString(R.string.ClearCookieQuestion))
.setIcon(
getResources().getDrawable(
android.R.drawable.ic_dialog_alert))
.setPositiveButton(
getResources().getString(R.string.PostiveYesButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
})
.setNegativeButton(
getResources().getString(R.string.NegativeNoButton),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog,
int which) {
//Do Something Here
}
}).show();
}}
As told before there are number of ways doing this. this is one of the way you can do your task, please accept the answer if you feel that you have got it what you wanted.