Back button functionality not working while running my Android program - android

My program is working properly, but in the middle of the program running, user clicks on the BACK button, and the functionality of the back button does not work. But after completing the executing, BACK button functionality is working.
please observe my code here.
package com.sampleexample;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class SampleExample extends Activity {
static final int PROGRESS_DIALOG = 0;
Button button;
TextView download;
ProgressThread progressThread;
ProgressDialog progressDialog;
/** Called when the activity is first created. */
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Log.d("SampleExample", "======= onCreate()====Start====");
// Setup the button that starts the progress dialog
download = (TextView) findViewById(R.id.download);
button = (Button) findViewById(R.id.progressDialog);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Log.d("SampleExample", "======= onClick()==Start======");
showDialog(PROGRESS_DIALOG);
Log.d("SampleExample", "======= onClick()===End=====");
}
});
Log.d("SampleExample", "======= onCreate()====End====");
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Ask the user if they want to quit
Log.d("SampleExample", " ------- Back Button onKeyDown()----Start--");
new AlertDialog.Builder(this).setIcon(
android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to leave?")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Exit the activity
SampleExample.this.finish();
}
}).show();
// Say that we've consumed the event
Log.d("SampleExample", " ------BackButton-onKeyDown()----End--");
return true;
}
return super.onKeyDown(keyCode, event);
}
// Toast.makeText(SampleExample.this, "U have pressed the Back Button",
// Toast.LENGTH_SHORT).show();
// Log.d(this.getClass().getName(),
// "*********back button pressed----------");
protected Dialog onCreateDialog(int id) {
Log.d("SampleExample", "99999 onCreateDialog () 999 Start");
switch (id) {
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(SampleExample.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
download.setText("Now downloading.......");
progressThread = new ProgressThread(handler);
progressThread.start();
return progressDialog;
default:
return null;
}
}
// Define the Handler that receives messages from the thread and update the
// progress
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
Log.d("SampleExample", "8888 handleMessage () 8888 Start");
int total = msg.getData().getInt("total");
progressDialog.setProgress(total);
if (total >= 100) {
// Toast.makeText(SampleExample.this, "Download is completed",
// Toast.LENGTH_SHORT).show();
download.setText(" download is completed.");
dismissDialog(PROGRESS_DIALOG);
progressThread.setState(ProgressThread.STATE_DONE);
}
}
};
/** Nested class that performs progress calculations (counting) */
private class ProgressThread extends Thread {
Handler mHandler;
final static int STATE_DONE = 0;
final static int STATE_RUNNING = 1;
int mState;
int total;
ProgressThread(Handler h) {
mHandler = h;
}
public void run() {
mState = STATE_RUNNING;
total = 0;
Log.d("SampleExample", "7777 run () 7777 Start");
while (mState == STATE_RUNNING) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.e("ERROR", "Thread Interrupted");
}
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
total++;
}
Log.d("SampleExample", "6666 run () 6666 End");
}
/*
* sets the current state for the thread, used to stop the thread
*/
public void setState(int state) {
mState = state;
}
}
}

You haven't really explained the symptoms of your problem clearly, but from your code it appears that you are kicking off a background thread and popping up a ProgressDialog. I am assuming that it is while this is running that you are attempting to press the BACK key. The reason that this does not appear to do anything is that a Dialog is by default not cancelable using the BACK key. You have to call setCancelable(true) to enable this behaviour.
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(SampleExample.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
progressDialog.setCancelable(true);
...
return progressDialog;
This will allow the ProgressDialog to be cancelled with the BACK button. However your background Thread will continue to run, even if the Dialog has been cancelled.

// handle phone back button
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
return quitWithPID();
}
return super.onKeyDown(keyCode, event);
}
// reusable method (modifier may be public..)
private boolean quitWithPID() {
new AlertDialog.Builder(this).setIcon(
android.R.drawable.ic_dialog_alert).setTitle("Exit Boot Options?")
.setMessage("Are you sure you want to exit?")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Exit the activity
MainActivity.this.finish();
// Terminate the process ;)
android.os.Process.killProcess(android.os.Process.myPid());
}
}).show();
return true;
}

chandu Did you checked your logic before posting the question
Recheck the below code in your handler
if (total >= 100) {
download.setText(" download is completed.");
dismissDialog(PROGRESS_DIALOG);
progressThread.setState(ProgressThread.STATE_DONE);
}
your code won't reach dismissDialog until total >= 100 & hence even whilst the program you are unable to useyour BACK's Action
& also please stop posting multiple questions

Related

What is the most proper way to handle last back click before closing an app

I am trying to implement confirm message to exit from my app. I need this, because someone can accidentally click back button more than one time and this will close the app and in case of low memory it will be killed after that because now it is not in foreground.
I have tried different approaches, but some of them required a lot of checks, others doesn't work at all.
I have tried to use onKeyDown event, onBackPressed ...
The problem because I am working not with only with activities, but also with nested fragments (inside activities).
I need to handle the last on back pressed click before exit, so it means that all fragments of current activity have to be popped up from the stack, than activity has to be popped up also and that if this is not last activity do the same for the preceding activity until this is not last activity and all fragments are popped up in it.
How can I implement this ? I have tried to do this using backstack, but unfortunately haven't succeed.
Please suggest what is the best to handle such type of event. I guess that there is an easy way to do this.
Thanks everyone for answers and suggestions.
I have reached the desired result by using fragment count in the stack.
As far as my Main Activity will be the first activity and the last before exit, I can override onBackPressed method inside it.
So solution is simple.
public class MainActivity extends BaseSingleFragmentActivity {
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle(R.string.title_exit_message)
.setMessage(R.string.message_exit)
.setPositiveButton(R.string.button_text_yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
MainActivity.super.onBackPressed();
}
})
.setNegativeButton(R.string.button_text_no, null)
.show();
} else {
MainActivity.super.onBackPressed();
}
}
}
So this will work only if your activity is last in Activity Stack , so you have to override it your launcher activity, not in some base activity class or other.
A little bit improved solution to my mind.
package com.crosp.solutions.qrcodereader.dialogs;
import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.DialogFragment;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import com.crosp.solutions.qrcodereader.R;
import com.crosp.solutions.qrcodereader.constants.FragmentConstants;
/**
* Created by crosp on 7/9/15.
*/
public class ConfirmationDialog extends DialogFragment implements DialogInterface.OnClickListener {
private OnConfirmDialogClickListener mOnConfirmDialogListener;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mOnConfirmDialogListener = (OnConfirmDialogClickListener) activity;
} catch (ClassCastException ex) {
Log.e(getString(R.string.error_tag), "Activty has to implement " + OnConfirmDialogClickListener.class.getSimpleName() + " interface");
}
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity())
.setPositiveButton(R.string.button_text_yes, this)
.setNegativeButton(R.string.button_text_no, this);
Bundle bundle = getArguments();
String message = getString(R.string.message_exit);
String title = getString(R.string.title_exit_message);
int iconId = android.R.drawable.ic_dialog_alert;
if (bundle != null) {
String argumentMessage = bundle.getString(FragmentConstants.Arguments.DIALOG_MESSAGE_ARGUMENT);
String argumentTitle = bundle.getString(FragmentConstants.Arguments.DIALOG_TITLE_ARGUMENT);
int argumentIconId = bundle.getInt(FragmentConstants.Arguments.DIALOG_ICON_ID_ARGUMENT);
message = argumentMessage != null ? argumentMessage : message;
title = argumentTitle != null ? argumentTitle : title;
iconId = argumentIconId != 0 ? argumentIconId : iconId;
}
builder.setIcon(iconId);
builder.setMessage(message);
builder.setTitle(title);
return builder.create();
}
#Override
public void onClick(DialogInterface dialog, int which) {
if (which == DialogInterface.BUTTON_POSITIVE) {
mOnConfirmDialogListener.onConfirmClick();
} else if (which == DialogInterface.BUTTON_NEGATIVE) {
mOnConfirmDialogListener.onCancelClick();
}
}
public interface OnConfirmDialogClickListener {
void onConfirmClick();
void onCancelClick();
}
}
And in activity
public class MainActivity extends BaseSingleFragmentActivity implements ExitConfirmDialogFactory.OnExitDialogClickListener {
#Override
public void onBackPressed() {
if (getSupportFragmentManager().getBackStackEntryCount() == 0) {
Bundle arguments = new Bundle();
if(mExitDialog==null) {
arguments.putInt(FragmentConstants.Arguments.DIALOG_ICON_ID_ARGUMENT, android.R.drawable.ic_dialog_alert);
arguments.putString(FragmentConstants.Arguments.DIALOG_MESSAGE_ARGUMENT, getString(R.string.message_exit));
arguments.putString(FragmentConstants.Arguments.DIALOG_TITLE_ARGUMENT, getString(R.string.title_exit_message));
DialogFragment exitDialog = new ConfirmationDialog();
exitDialog.setArguments(arguments);
mExitDialog = exitDialog;
}
mExitDialog.show(getSupportFragmentManager(),FragmentConstants.Tags.EXIT_DIALOG_TAG);
} else {
super.onBackPressed();
}
}
#Override
public void onConfirmClick() {
super.onBackPressed();
}
#Override
public void onCancelClick() {
}
Basically override onBackPressed() in the Main Activity and avoid calling the parent super.onBackPressed() if the user selects "No" to exiting the app.
Code suggestion:
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setTitle("Exiting app?")
.setPositiveButton("Yes", new OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// user really do want to exit
MainActivity.super.onBackPressed();
}
}).create().show();
// If negative, show a Fragment or do nothing
}
I am not sure but I think you can use an integer to count your fragments, increase it on adding a new fragment and decrease on every back press. It may be like that:
#Override public void onBackPressed() {
if( fragCount > 0) {
--fragCount;
super.onBackPressed();
return;
}
new AlertDialog.Builder(this) .setTitle("Exiting app?") .setPositiveButton("Yes", new OnClickListener() { public void onClick(DialogInterface arg0, int arg1) { // user really do want to exit
MainActivity.super.onBackPressed(); } }).create().show();
}
Note: Sorry for bad typing I am on phone.

Change textColor of textswitcher/viewswitcher based on int value?

I have a countdown timer starting at 60000 milliseconds and want to change the text color from Color.BLUE to Color.RED once the time is at and below 10000 milliseconds. I've tried the following without any success; attempted to setTextColor of TextSwitcher and add IF statement that would change color based on int value timerState.. I can't figure out how to make it work besides possibly stopping the timer and creating another one once the millisecondsUntilFinished hits 10000 which actually lead to my second issue where:
I click on an imageButton that initiates a dialog fragment (PauseFragment) and calling cancel() on my CountDownTimer via timerCDT.cancel(). I ran into some nullpointer issues hence the if statements checking for null in my code, but now once the PauseFragment dismisses my new timer starts back at 60000 rather than where it last left off. I was hoping that long timerState = 60000 would get updated to whatever millisUntilFinished is everytime onTick() was called but I'm not sure where I went wrong!
Therefore, can someone please assist me with changing TextSwitcher text color dynamically and assist in figuring out why my CountDownTimer isn't starting at the expected value. Any assistance is greatly appreciated.
THANKS in advance!
public class GameActivity extends FragmentActivity implements PauseFragment.FragmentCommunicator,{
public static long timerState = 60000;
public static boolean isTimerOn = false;
private String modeChoice = ModesActivity.mode;
private TextSwitcher timerTextSwitcher;
CountDownTimer timerCDT;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//...more code
timerTextSwitcher = (TextSwitcher) findViewById(R.id.timerTextSwitcher);
timerTextSwitcher.setFactory(new ViewSwitcher.ViewFactory() {
public View makeView() {
// Create a new TextView and set properties
TextView textView = new TextView(getApplicationContext());
textView.setLayoutParams(new TextSwitcher.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setTextSize(20);
textView.setTextColor(Color.BLUE);
if (timerState < 10001) {
textView.setTextColor(Color.RED);
}
return textView;
}
});
// Declare the animations and initialize them
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
// set the animation type to textSwitcher
timerTextSwitcher.setInAnimation(in);
timerTextSwitcher.setInAnimation(out);
}
timerCDT = new CountDownTimer(timerState, 1000) {
public void onTick(long millisUntilFinished) {
isTimerOn = true;
timerTextSwitcher.setText(String.valueOf(millisUntilFinished / 1000));
timerState = millisUntilFinished;
}
//TODO: assign highscores for players to beat
public void onFinish() {
timerTextSwitcher.post(new Runnable() {
#Override
public void run() {
createToast("GAME OVER!");
}
});
isTimerOn = false;
DialogFragment endDialog = new EndGameFragment();
endDialog.show(getSupportFragmentManager(), "EndGameDialogFragment");
}
};
timerCDT.start();
#Override
public void onPause() {
super.onPause();
Bundle args = new Bundle();
args.putInt(ARG_SCORE, scoreINT);
args.putLong(ARG_TIMER, timerState);
args.putString(GameActivity.ARG_MODE, modeChoice);
if (timerCDT != null) {
timerCDT.cancel();
}
else{
createToastExtended("onPause() - timerCDT is null; attempt to cancel");
}
}
//.!.other fun code here.!.
#Override
protected void onStop() {
super.onStop();
if (timerCDT != null) {
timerCDT.cancel();
}
else{
createToastExtended("onStop() - timerCDT is null; attempt to cancel");
}
}
//Player Response information
#Override
public void pauseFragmentResponse() {
if (timerCDT != null) {
timerCDT.start();
}
else{
createToastExtended("pauseFragmenResponse() - timerCDT is null; attempt to start");
}
}
public void pauseStartFrag(View view) {
DialogFragment dialog = new PauseFragment();
if (timerCDT != null) {
timerCDT.cancel();
}
else{
createToastExtended("pauseStartFrag() - timerCDT is null;attempt to cancel");
}
dialog.show(getSupportFragmentManager(), "PauseDialogFragment");
}
// Code for PauseFragment
//TODO: remove unuses imports on all files within project;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.view.LayoutInflater;
public class PauseFragment extends DialogFragment {
public static boolean isPaused = false;
public FragmentCommunicator fComm;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
fComm = (FragmentCommunicator) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement FragmentCommunicator");
}
}
#Override
public void onDetach() {
super.onDetach();
fComm = null;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
isPaused = true;
// Use the Builder class for convenient dialog construction
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.fragment_pause, null))
.setMessage(R.string.dialog_pause)
.setPositiveButton(R.string.action_main_menu, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i4 = new Intent(getActivity(), StartActivity.class);
startActivity(i4);
}
})
.setNeutralButton(R.string.action_restart, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent i4 = new Intent(getActivity(), ModesActivity.class);
startActivity(i4); }
})
.setNegativeButton(R.string.action_resume, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
// User cancelled the dialog
fComm.pauseFragmentResponse();
dismiss();
}
});
// Create the AlertDialog object and return it
return builder.create();
}
#Override
public void onDismiss(DialogInterface dialog) {
super.onDismiss(dialog);
isPaused = false;
}
public interface FragmentCommunicator {
public void pauseFragmentResponse();
}
}
Lastly, Idk if it's of any help but I also tried starting the CountDownTimer timerCDT without the FragmentCommunicator interface but the system couldn't find the timer? If someone could shine light on why this happened I'd appreciate it as well.
Seriously, one last thing, if the timer is for a game and needs to be stopped and updated frequently, is it best to use CountDownTimer, TimerTask, a newThread that implements Runnable or a handler or some sort? I've tried them all but as I add components and features to the app I need more and more flexibility with changing the time and not quite sure if I'm headed down the right path. Hope this post isn't too vague. Please let me know if I need to separate into multiple posts or something...
Thanks as always!
just had a look on the developer website here http://developer.android.com/reference/android/os/CountDownTimer.html and it looks like you should probably be placing that if statement in the onTick method, so for every tick you do the check.
EDIT
ok this works perfectly for me
private TextSwitcher TextSw;
private TextView TextSwTextView;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(com.game.test.R.layout.sample);
TextSw = (TextSwitcher) findViewById(R.id.TextSwitchView);
TextSw.setFactory(new ViewSwitcher.ViewFactory()
{
public View makeView()
{
// Create a new TextView and set properties
TextView textView = new TextView(getApplicationContext());
textView.setLayoutParams(new TextSwitcher.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
textView.setTextSize(20);
textView.setTextColor(Color.BLUE);
return textView;
}
});
mtimer = new CountDownTimer(60000, 1000)
{
public void onTick(long millisUntilFinished)
{
TextSwTextView = (TextView) TextSw.getChildAt(0);
if(millisUntilFinished < 10001)
TextSwTextView.setTextColor(Color.RED);
TextSwTextView.setText("seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish()
{
TextSwTextView.setText("done!");
}
}.start();
}
so the above is a simple version of yours, the text that is displaying the timer will change to Red when the timer hit 1000. You should be able to build this into yours.
But the main thing you have to do here is to check how much the timer has left in the in the onTick method and also change the text color in here to - see above
This thread helped me solve my problem more easily:
https://groups.google.com/forum/#!topic/android-developers/jdlUp_RlP2w
Your get a handle on the textviews within the textSwitcher like this:
TextView t1 = (TextView) mSwitcher.getChildAt(0);
TextView t2 = (TextView) mSwitcher.getChildAt(1);
Then you set whatever color you need based on your code logic.
TextView t1, t2;
textSwitcher = (TextSwitcher) findViewById(R.id.textView99);
textSwitcher.setInAnimation(this, R.anim.slide_in_right);
textSwitcher.setOutAnimation(this, R.anim.slide_out_left);
t1 = new TextView(this);
t2 = new TextView(this);
t1.setTextSize(20);
t2.setTextSize(20);
textSwitcher.addView(t1);
textSwitcher.addView(t2);

Mobile Number Verification during registration by message from api like that in "viber" for android

I have the url, username and password of my Message API. and i am a beginner. i have tried certain codes but it failed. i want the working code for integrating this api with the parameters i have and also a receiver code for reading the message that is received by the Message API.
the process is as follows..
during user registration the user enters a number.
the number is sent to the url of API and the user receives a message with a random code.
the application verifies if the random code is same as that which
was sent.
if it is same the user gets registers and sees the application
content.
this activity only happens one for registration.
Do help me i am in a serious confusion...thank you alot in advance
Try this code which worked for me..
Here, I'm asking the user to enter the phone number once during installation and a random number is sent as an sms from his phone itself. This process will be done only once, ie for registration only(if the entered code and the random code sent is matched.if not, it will not be activated and again the registration screen is shown)..
Here is the code..
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.text.Html;
import android.text.InputType;
import android.util.Log;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
public class SplashActivity extends Activity {
private int splashTime = 3000;
private Thread thread;
private ProgressBar mSpinner;
Boolean number_confirmation=false;
String randomcode;
String deviceimei;
String phonenumber;
String sent_code,activation;
boolean isactivated;
ProgressDialog progressDialog;
TextView tv_loading;
public EditText input;
SharedPreferences wmbPreference1,wmbPreference2;
SharedPreferences.Editor editor;
RandomCodeGenerator rc;
boolean isInternetPresent=false;
AlertDialogManager alert;
ConnectionDetector cd;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
try
{
alert=new AlertDialogManager();
cd=new ConnectionDetector(SplashActivity.this);
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent)
{
//wmbPreference for Shared Prefs that lasts forever
wmbPreference1 = PreferenceManager.getDefaultSharedPreferences(this);
//installsp for Shared Prefs that lasts only just once each time program is running
wmbPreference2 = getApplicationContext().getSharedPreferences("install_code_prefs", Activity.MODE_PRIVATE);
boolean isActivated=wmbPreference1.getBoolean("ISACTIVATED", false);
boolean isFirstRun = wmbPreference1.getBoolean("FIRSTRUN", true);
boolean isPhonenumberEntered=wmbPreference1.getBoolean("PHONENUMBERENTERED", false);
number_confirmation=wmbPreference1.getBoolean("NUMBER_CONFIRMATION", false);
deviceimei=wmbPreference1.getString("IMEI", "");
if (isFirstRun||!isActivated)
{
// Code to run once
//code to get next random number
rc=new RandomCodeGenerator();
//code to set wmbPreference with FIRSTRUN flag
editor = wmbPreference1.edit();
editor.putBoolean("FIRSTRUN", false);
editor.commit();
// Showing Alert Message
//code to create alert dialog
if(isPhonenumberEntered==false)
phonenumberDialog();
else
passwordDialog();
}
super.onCreate(savedInstanceState);
if(isActivated)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
mSpinner = (ProgressBar) findViewById(R.id.Splash_ProgressBar);
tv_loading=(TextView) findViewById(R.id.tv_loading);
mSpinner.setIndeterminate(true);
// runOnUiThread(new Runnable() {
//
// #Override
// public void run() {
// // TODO Auto-generated method stub
//
// }
// });
thread = new Thread(runable);
thread.start();
}
else
{
editor = wmbPreference2.edit();
editor.putBoolean("FRESHRUN", true);
editor.commit();
}
}
else
{
// Internet Connection is not present
alert.showAlertDialog(SplashActivity.this, "xxxxxx",
"Please connect to working Internet connection", false);
}
}
catch(Exception e)
{
Toast.makeText(SplashActivity.this, e.toString(), Toast.LENGTH_LONG).show();
}
}
public Runnable runable = new Runnable() {
public void run() {
try {
Thread.sleep(splashTime);
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
tv_loading.setText("Completing..");
mSpinner.setIndeterminate(true);
}
});
startActivity(new Intent(SplashActivity.this,HomeActivity.class));
finish();
} catch (Exception e) {
// TODO: handle exception
}
}
};
public void passwordDialog()
{
//code to create alert dialog
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SplashActivity.this);
alertDialog.setTitle("xxxxx");
//alertDialog.setIcon(R.drawable.logo);
// Setting Dialog Message
alertDialog.setMessage(Html.fromHtml("<b>PASSWORD</b><br/>Enter 6 digit password sent to your phone"));
input = new EditText(SplashActivity.this);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
// bt_resend=new Button(HomeActivity.this);
// bt_resend.setText("Resend");
// bt_resend.setLayoutParams(lp);
alertDialog.setView(input);
// alertDialog.setView(bt_resend);
alertDialog.setCancelable(false);
alertDialog.setNeutralButton("Resend", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
phonenumberDialog();
}
});
alertDialog.setPositiveButton("YES",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// Write your code here to execute after dialog
deviceimei=getIMEI();
checkPassword();
saveIMEI();
// Toast.makeText(SplashActivity.this,"IMEI:"+deviceimei, Toast.LENGTH_SHORT).show();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("NO",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// code to execute after dialog
dialog.cancel();
//code to finish app
finish();
}
});
alertDialog.show();
}
public void phonenumberDialog()
{
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SplashActivity.this);
alertDialog.setTitle("xxxxx");
alertDialog.setIcon(R.drawable.logo);
// Setting Dialog Message
alertDialog.setMessage(Html.fromHtml("<b>PHONE NUMBER</b><br/>Enter Your Phone Number for verification<br/><small>*standard SMS rates apply</small>"));
input = new EditText(SplashActivity.this);
input.setInputType(InputType.TYPE_CLASS_NUMBER);
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);
input.setLayoutParams(lp);
alertDialog.setView(input);
alertDialog.setCancelable(false);
alertDialog.setPositiveButton("Next",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int which) {
// code to execute after dialog
editor = wmbPreference1.edit();
editor.putBoolean("PHONENUMBERENTERED", true);
editor.commit();
String mobno=input.getText().toString();
//save phonenumber in shared preference
editor = wmbPreference1.edit();
editor.putString("PHONENUMBER", mobno);
editor.commit();
final String rnc=rc.nextId();
randomcode=rnc;
//code to set installsp with randomnumber code
editor= wmbPreference2.edit();
editor.putString("install_code", rnc);
editor.commit();
Log.d("rnc", rnc);
try
{
//code to send text message
SmsManager sm = SmsManager.getDefault();
sm.sendTextMessage(mobno, null,"xxxxx\nInstallation Password\n#####\n"+"6 digit Password: "+rnc+" " , null, null);
}
catch(Exception e)
{
// Toast.makeText(HomeActivity.this, "Please Enter Phone Number", Toast.LENGTH_LONG);
}
//code to create alert dialog
passwordDialog();
}
});
// Setting Negative "NO" Button
alertDialog.setNegativeButton("SKIP",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
passwordDialog();
}
});
alertDialog.show();
}
public String getIMEI()
{
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
String imei=telephonyManager.getDeviceId();
return imei;
}
public void checkPassword()
{
activation = input.getText().toString();
SharedPreferences installsp = getApplicationContext().getSharedPreferences("install_code_prefs", Activity.MODE_PRIVATE);
sent_code=installsp.getString("install_code", null);
phonenumber=wmbPreference1.getString("PHONENUMBER", "");
new WebServiceBackgroundTask().execute(phonenumber,sent_code,deviceimei);
}
public void saveIMEI()
{
editor = wmbPreference1.edit();
editor.putString("IMEI", deviceimei);
editor.commit();
}
public class WebServiceBackgroundTask extends AsyncTask<String, Integer, String> {
int i=0;
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDialog = new ProgressDialog(SplashActivity.this);
progressDialog.setTitle("YATRAMiTR");
progressDialog.setIcon(R.drawable.logo);
progressDialog.setMessage(Html.fromHtml("<b>Password</b><br/>Validating Password..."));
progressDialog.setIndeterminate(false);
progressDialog.setCancelable(false);
progressDialog.show();
}
#Override
protected String doInBackground(String... params) {
String resp="";
if(activation.compareTo(sent_code)==0)
{
// Toast.makeText(SplashActivity.this,"Password Matched", Toast.LENGTH_SHORT).show();
//code to set wmbPreference with ISACTIVATED flag
editor=wmbPreference1.edit();
editor.putString("PWD", sent_code);
editor.commit();
isactivated=true;
editor = wmbPreference1.edit();
editor.putBoolean("ISACTIVATED", true);
editor.commit();
resp="success";
}
else
isactivated=false;
return resp;
}
#Override
protected void onProgressUpdate(Integer... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
progressDialog.dismiss();
// Toast.makeText(SplashActivity.this,"Sent code:"+sent_code, Toast.LENGTH_SHORT).show();
// Toast.makeText(SplashActivity.this,"Entered code:"+activation, Toast.LENGTH_SHORT).show();
if(result!="")
Toast.makeText(SplashActivity.this, result, Toast.LENGTH_LONG).show();
if(isactivated)
{
//code to restart app
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(i);
}
else
{
Toast.makeText(SplashActivity.this,"Wrong Password!", Toast.LENGTH_SHORT).show();
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
finish();
startActivity(i);
}
}
}
}
Your MainActivity.java should be like this..
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
wmbPreference = getApplicationContext().getSharedPreferences("install_code_prefs", Activity.MODE_PRIVATE);
boolean freshrun=wmbPreference.getBoolean("FRESHRUN",true);
if(freshrun)
{
Intent intent=new Intent(HomeActivity.this,SplashActivity.class);
finish();
startActivity(intent);
editor = wmbPreference.edit();
editor.putBoolean("FRESHRUN", false);
editor.commit();
}
else
{
////your normal code here
}
The above code checks if the app is activated or not..if not, the itwill be redirected to the Splashscreen Activity.
Now the Randomcode class is as follows(RandomCodeGenerator.java)..
import java.math.BigInteger;
import java.security.SecureRandom;
public class RandomCodeGenerator {
private SecureRandom random = new SecureRandom();
public String nextId() {
return new BigInteger(30, random).toString(32);
}
}
ConnectionDetector.java
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context){
this._context = context;
}
/**
* Checking for all possible internet providers
* **/
public boolean isConnectingToInternet(){
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null)
{
NetworkInfo[] info = connectivity.getAllNetworkInfo();
if (info != null)
for (int i = 0; i < info.length; i++)
if (info[i].getState() == NetworkInfo.State.CONNECTED)
{
return true;
}
}
return false;
}
}
AletDialogManager.java
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
public class AlertDialogManager {
/**
* Function to display simple Alert Dialog
* #param context - application context
* #param title - alert dialog title
* #param message - alert message
* #param status - success/failure (used to set icon)
* - pass null if you don't want icon
* */
#SuppressWarnings("deprecation")
public void showAlertDialog(Context context, String title, String message,
Boolean status) {
AlertDialog alertDialog = new AlertDialog.Builder(context).create();
// Setting Dialog Title
alertDialog.setTitle(title);
// Setting Dialog Message
alertDialog.setMessage(message);
if(status != null)
// Setting alert dialog icon
// alertDialog.setIcon((status) ? R.drawable.success : R.drawable.fail);
alertDialog.setIcon(R.drawable.logo);
alertDialog.setCancelable(false);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
}
});
// Showing Alert Message
alertDialog.show();
}
}
Try this and check if this was the one that was needed for you..Please do tell me if there are any errors..

Android application retain the state after the app is restored from minimize

I have an app which starts from a splash screen and then navigates to other activities. If i press the home button in a particular activity ,the app gets minimized. Again if i click on the app icon, the app starts from the splash screen. I want to resume my app from the activity in which the home button was pressed. How to achieve this?
package com.xyz.user.login;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageButton;
public class ResetPasswordActivity extends Activity {
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// TODO Auto-generated method stub
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(R.layout.menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.logout:
// Single menu item is selected do something
// Ex: launching new activity/screen or show alert message
PopIt("Are you sure you want to exit?");
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void PopIt(String string) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(string)
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Intent intent = new Intent(
getApplicationContext(),
SignInActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("EXIT", true);
startActivity(intent);
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reset_password);
ImageButton imgRPass=(ImageButton)findViewById(R.id.imgChangePass);
imgRPass.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent=new Intent(ResetPasswordActivity.this,ResetPasswordMessageActivity.class);
startActivity(intent);
}
});
ImageButton imgBack=(ImageButton)findViewById(R.id.imgbtnBackFromResetPass);
imgBack.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
finish();
}
});
}
}
Maybe the code in your Activities has a call to finish() in onStop() or onPause(). That destroys the Activity when it's minimised and causes the app to start again. There are other steps to take to be sure of restoring the state, but that is a good place to start looking.
You could try putting this code in there to track what is going on.
private static final String TAG = "ResetPasswordActivity";
#Override public void onStart() {
Log.d(TAG, "onStart:");
super.onStart();
}
#Override public void onResume() {
Log.d(TAG, "onResume:");
super.onResume();
}
#Override public void onPause() {
Log.d(TAG, "onPause:");
super.onPause();
}
#Override public void onStop() {
Log.d(TAG, "onStop:");
super.onStop();
}
#Override public void onDestroy() {
Log.d(TAG, "onDestroy:");
super.onDestroy();
}
There are calls to finish and startActivity in there, although I cannot see why they should be executed. I'd put a Log statement by each. Then try it again and see what the Logcat output says when you minimise and relaunch the app.
You are talking about the default behavior of android. when you press home button app get minimized and when you click on app icon, by default app start from the same screen because its in pause mode and running in background. however you are getting splash screen on next launch that means your activity is getting killed by somehow either by android(due to memory constraint) or its getting a crash. see your logcat for details.
Write in AndroidManifest.xml to every activity option android:launchMode="singleTop".
Make sure you don't have android:noHistory="true" in your activity tag of manifest file. With it Android doesn't keep activity state when you minimizing your app

BACK Button is not working ,while progressDialog is running

I have a little problem; I hope you can help me.
While progressDialog is running, the user presses the BACK Button. The current Activity progressDialog goes to Background, but progressDialog is running.
My problem is that when the user clicks on the BACK button, progressDialog should be foreground Activity, stop current progress and ask "Do you want to continue or exit?"
If the user presses Continue, progressDialog should continue the remaining work.
Otherwise, close the current activity.
CODE HERE:
public class SampleExample extends Activity {
static final int PROGRESS_DIALOG = 0;
Button button;
TextView download;
ProgressThread progressThread;
ProgressDialog progressDialog;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
download = (TextView) findViewById(R.id.download);
button = (Button) findViewById(R.id.progressDialog);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog(PROGRESS_DIALOG);
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Ask the user if they want to quit
new AlertDialog.Builder(this).setIcon(
android.R.drawable.ic_dialog_alert).setTitle("Exit")
.setMessage("Are you sure you want to leave?")
.setNegativeButton(android.R.string.cancel, null)
.setPositiveButton(android.R.string.ok,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
// Exit the activity
SampleExample.this.finish();
}
}).show();
// Say that we've consumed the event
return true;
}
return super.onKeyDown(keyCode, event);
}
protected Dialog onCreateDialog(int id) {
switch (id) {
case PROGRESS_DIALOG:
progressDialog = new ProgressDialog(SampleExample.this);
progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
progressDialog.setMessage("Loading...");
download.setText("Now downloading.......");
progressThread = new ProgressThread(handler);
progressThread.start();
progressDialog.setCancelable(true);
return progressDialog;
default:
return null;
}
}
// Define the Handler that receives messages from the thread and update the
// progress
final Handler handler = new Handler() {
public void handleMessage(Message msg) {
int total = msg.getData().getInt("total");
progressDialog.setProgress(total);
if (total >= 100) {
download.setText(" download is completed.");
dismissDialog(PROGRESS_DIALOG);
progressThread.setState(ProgressThread.STATE_DONE);
}
}
};
/** Nested class that performs progress calculations (counting) */
private class ProgressThread extends Thread {
Handler mHandler;
final static int STATE_DONE = 0;
final static int STATE_RUNNING = 1;
int mState;
int total;
ProgressThread(Handler h) {
mHandler = h;
}
public void run() {
mState = STATE_RUNNING;
total = 0;
while (mState == STATE_RUNNING) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
Log.e("ERROR", "Thread Interrupted");
}
Message msg = mHandler.obtainMessage();
Bundle b = new Bundle();
b.putInt("total", total);
msg.setData(b);
mHandler.sendMessage(msg);
total++;
}
Log.d("SampleExample", "6666 run () 6666 End");
}
/*
* sets the current state for the thread, used to stop the thread
*/
public void setState(int state) {
mState = state;
}
}
}
You need to override back button event. You can do this as:
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && progressDialog.isShowing()) {
Log.d(this.getClass().getName(), "back button pressed");//write your own logic here, Whatever you want to do
}
return super.onKeyDown(keyCode, event);
}
Well, I had the same issue. The simplest method that worked for me is using progressDialog.setCancelable(true).. This declares whether the dialog is cancelable by hitting the back key.. Try it and let me know if it works for you or not. Good luck
Similar issue , When progressDialog.setCancelable(true) is set then hitting back button does not execute code written in back button code but just cancels the progress dialog..Hitting the key again works.
i want to cancel the progress dialog and execute some piece of code together which is not working.
Clicking back button twice does not make sense to me.
You can use progressDialog.setCancelable(true) and then use progressDialog.setOnCancelListener() to provide the OnCancelListener to execute your code to be executed onCancel().
See the Android documentation on Dialogs.

Categories

Resources