ANDROID onBackPressed doesnt work for the activity - java

I implemented the onBackPressed for my activity where it will check the internet connection but when i click the back button in my tablet, it does nothing. I dont understand what is the cause of it. Can help?
Below is my code
if (!cd.isConnectingToInternet()) {
AlertDialog.Builder splash = new AlertDialog.Builder(this);
splash.setIcon(R.drawable.ic_fail)
.setTitle("No Internet Connection")
.setMessage(
"Please check your internet connection and try again.")
.setCancelable(false)
.setPositiveButton("Try again",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
Intent splash = new Intent(
getApplicationContext(),
SplashActivity.class);
startActivity(splash);
finish();
}
})
.setNegativeButton("Wifi Setting",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
startActivity(new Intent(
android.provider.Settings.ACTION_WIFI_SETTINGS));
dialog.cancel();
}
});
AlertDialog alert = splash.create();
alert.show();
} else {
Thread timer = new Thread() {
public void run() {
try {
sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
Intent login = new Intent(getApplicationContext(),
LoginActivity.class);
startActivity(login);
finish();
}
}
};
timer.start();
}
}
public void onRestart() {
super.onRestart();
Intent splash = new Intent(getApplicationContext(),
SplashActivity.class);
startActivity(splash);
}
#Override
public void onBackPressed() {
super.onBackPressed();
finish();
}

just try this code...
#Override
public void onBackPressed()
{
moveTaskToBack(true);
}

comment, and check
//super.onBackPressed();

- finish() is the proper way to close the Activity.
- But still if its doesn't, due to some reason use System.exit(0) after finish().. this will surely work.... I know its crude...but works...
///////////////////////////// Edited Part///////////////////////////////////////
- override the method onKeyDown() of Activity.
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
this.finish();
}
return true;
}

try this instead. I think it will Work for you.
#Override
public void onBackPressed() {
//super.onBackPressed();
// finish your Activity
ActivityName.this.finish();
return;
}

Try This:
#Override
public void onBackPressed() {
yourclassname.this.finish();
android.os.Process.killProcess(android.os.Process.myPid());
System.exit(0);
getParent().finish();
}

Related

How to use EventBus in two Activity on Android

In my application i want use EventBus for manage events.
In my app i open activity B on the Activity A ! and i want when activity B finished, call one event in Activity A.
I write below codes
Activity B :
private void finishWithAnimate() {
EventBus.getDefault().post(new EventShowDialog(ExtraConstants.NOTE_DIALOG.name()));
if (pageType.equals(Extras.DETAIL)) {
Intent intent = new Intent();
setResult(4757, intent);
finish();
} else {
finish();
RegisterInAuctionActivity.this.overridePendingTransition(0, android.R.anim.fade_out);
}
}
Activity A :
#Subscribe(threadMode = ThreadMode.MAIN)
public void getEventShowDialog(EventShowDialog eventShowDialog) {
Log.e("showDialogEvent", "Root");
if (eventShowDialog.getDialogName().equals(ExtraConstants.NOTE_DIALOG.name())) {
Log.e("showDialogEvent", "Call");
if (!prefsUtils.getFromSharedBool(PrefsKeys.NEW_NOTE_DIALOG.name())) {
closeDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
noteDialog.dismiss();
prefsUtils.setToSharedBool(PrefsKeys.NEW_NOTE_DIALOG.name(), true);
}
});
noteDialog.show();
}
}
}
#Override
public void onStart() {
super.onStart();
EventBus.getDefault().register(this);
}
#Override
public void onStop() {
EventBus.getDefault().unregister(this);
super.onStop();
}
Update codes:
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 4757) {
//Note dialog
noteDialog = new Dialog(this);
noteDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
noteDialog.setContentView(R.layout.important_note);
noteDialog.setCancelable(false);
closeDialog = noteDialog.findViewById(R.id.okPayFrag_submitOK);
closeDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
noteDialog.dismiss();
prefsUtils.setToSharedBool(PrefsKeys.NEW_NOTE_DIALOG.name(), true);
}
});
if (!prefsUtils.getFromSharedBool(PrefsKeys.NEW_NOTE_DIALOG.name())) {
Toast.makeText(context, "Show", Toast.LENGTH_SHORT).show();
noteDialog.show();
closeDialog.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
noteDialog.dismiss();
prefsUtils.setToSharedBool(PrefsKeys.NEW_NOTE_DIALOG.name(), true);
}
});
}
finish();
overridePendingTransition(android.R.anim.fade_in, 0);
startActivity(getIntent());
overridePendingTransition(android.R.anim.fade_in, 0);
}
}
But not call any log in getEventShowDialog . Not show me any log in this method!
how can i fix it?
You are trying to perform some actions on getting a result from an activity.
So when your activity B finishes, do a setResult and catch the same on Activity A onActivityResult and perform your action(call the function you want).
You need to do a startActivityForResult while opening B from A though.

Keep user logged in but exit android app on double pressing back

I am using Firebase to sign in the user and have implemented the code to exit the app on double click. But the problem is the same screen is popping up again.
I tried a workaround setting a SharedPreference and then checking that in mAuthListner. But it did not work.
Here are the relevant sections of the code:
mAuthListener = new FirebaseAuth.AuthStateListener(){
#Override
public void onAuthStateChanged(#NonNull FirebaseAuth firebaseAuth) {
SharedPreferences d= getSharedPreferences("backPressed", Context.MODE_PRIVATE);
Boolean t = d.getBoolean("back",false);
if (firebaseAuth.getCurrentUser() != null && !t) {
startActivity(new Intent(MainActivity.this, Second.class));
}
if (t) {
d.edit().putBoolean("back",false);
}
}
};
Code for back button pressed:
boolean doubleBackToExitPressedOnce = false;
private Handler mHandler = new Handler();
private final Runnable mRunnable = new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce = false;
}
};
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
SharedPreferences d= getSharedPreferences("backPressed",Context.MODE_PRIVATE);
d.edit().putBoolean("back",true);
finish();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
mHandler.postDelayed(mRunnable, 2000);
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mHandler != null) { mHandler.removeCallbacks(mRunnable); }
}
How can I exit the app on back pressed twice while keeping the user logged in?
This is not a Firebase issue as Firebase will not log out until you specifically call the "Log Out" method.
You do not need SharedPreferences. Just set an Activity level variable BackOnce to False then set it in the OnBackPressed as necessary.
boolean BackOnce = false;
#Override
public void onBackPressed() {
if (BackOnce) {
finish();
} else {
BackOnce = true;
Snackbar sb = Snackbar.make(myView, "Press back again to close app", Snackbar.LENGTH_SHORT);
sb.addCallback(new Snackbar.Callback() {
#Override
public void onDismissed(Snackbar snackbar, int event) {
super.onDismissed(snackbar, event);
BackOnce = false;
}
});
sb.show();
}
}

How to use AsyncTask method outside

I am checking server available or not with AsyncTask class and its working fine with below code
class AsyncServerOnlineCheck extends AsyncTask {
boolean isReachable;
#Override
protected Object doInBackground(Object[] objects) {
isReachable = NetworkCheck.isReachable(SplashsActivity.this);
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
if (isReachable) {
new DownloadLatestData().execute();
Toast.makeText(SplashsActivity.this, "Server is online", Toast.LENGTH_SHORT).show();
} else {
if (database.isDataBaseCreated()) {
Toast.makeText(SplashsActivity.this, "Server is offline", Toast.LENGTH_SHORT).show();
Intent i = new Intent(SplashsActivity.this, MainActivity.class);
startActivity(i);
overridePendingTransition(R.anim.fade_in, R.anim.fade_out);
finish();
} else {
connectionerror();
}
}
}
}
Now I want use isReachable condition in other method called connectionerror. Both is in same activity. connectionerror is like below
public void connectionerror() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(SplashsActivity.this);
alertDialog.setTitle("Error!");
alertDialog.setMessage("Connection Lost ! Try Again");
alertDialog.setPositiveButton("Retry",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
if (downloadLatestDataStatus != null) {
downloadLatestDataStatus.clear();
}
if (NetworkCheck.isInternetAvailable(SplashsActivity.this)) {
new DownloadLatestData().execute();
} else {
connectionerror();
}
}
});
alertDialog.show();
}
You can see one condition in connectionerror method like below
if (NetworkCheck.isInternetAvailable(SplashsActivity.this)) {
new DownloadLatestData().execute();
}
instead this condition for network check, I want use isReachable from AsyncTask....How can I do it ?
I have got solved via hire freelancer for fix it. He have done like below in alert dialogue
new AsyncServerOnlineCheck().execute();
Thanks all friends !!

back button alert box(Android Studio)

In my first class, I have this piece of code:
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(R.drawable.ic_launcher)
.setTitle(R.string.ALERTA1)
.setMessage(R.string.ALERTA2)
.setPositiveButton(R.string.ALERTA3, new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton(R.string.ALERTA4, null)
.show();
}
This will make an alert box when the back button is pressed, but this works in every class, I only want it to work in this one.
UPDATE:
public void onBackPressed() {
finish();
}
In every class.
Put this in your other classes:
public void onBackPressed() {
super.onBackPressed();
return;
}
That might work.

Adding a Cancel Button to a CustomAlertDialog

I am just a themer, not a programmer, any help/guidance is appreciated.
I am trying to add a Cancel button to this code:
public class gobuuf extends Activity {
/** Called when the activity is first created. */
class CustomAlertDialog extends AlertDialog {
public CustomAlertDialog(Context context) {
super(context);
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean ret = super.onKeyDown(keyCode, event);
finish();
return ret;
}
public void setCancel(int buttonNegative, String string, Object object) {
// TODO Auto-generated method stub
}
}
private CustomAlertDialog mDialog;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
if (isExistSkin("com.gau.go.launcherex")) {
startGOLauncher("com.gau.go.launcherex");
finish();
return;
}
mDialog = new CustomAlertDialog(this);
mDialog.setTitle(R.string.dialogtitle);
mDialog.setMessage(getResources().getString(R.string.dialogcontent));
mDialog.setCancel(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.dialognothanks), null);
mDialog.setButton(DialogInterface.BUTTON_POSITIVE, getResources().getString(R.string.dialogok),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String marketuriString = "market://search?q=pname:com.gau.go.launcherex";
Intent EMarketintent = new Intent(Intent.ACTION_VIEW, Uri.parse(marketuriString));
EMarketintent.setPackage("com.android.vending");
EMarketintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
// Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(marketuriString));
try {
startActivity(EMarketintent);
} catch (ActivityNotFoundException e) {
String link = "http://61.145.124.93/soft/3GHeart/com.gau.go.launcherex.apk";
Uri browserUri = Uri.parse(link);
Intent browserIntent = new Intent(Intent.ACTION_VIEW, browserUri);
browserIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
startActivity(browserIntent);
} catch (ActivityNotFoundException e2) {
// TODO: handle exception
e2.printStackTrace();
}
} catch (Exception e3) {
// TODO: handle exception
e3.printStackTrace();
}
finish();
}
});
mDialog.show();
}
#Override
protected void onDestroy() {
super.onDestroy();
android.os.Process.killProcess(android.os.Process.myPid());
}
private boolean isExistSkin(String packageName) {
try {
createPackageContext(packageName,
Context.CONTEXT_IGNORE_SECURITY);
} catch (NameNotFoundException e) {
return false;
}
return true;
}
private void startGOLauncher(String packageName){
PackageManager packageMgr = this.getPackageManager();
Intent launchIntent = packageMgr.getLaunchIntentForPackage(packageName);
if (null != launchIntent){
try
{
this.startActivity(launchIntent);
}
catch(ActivityNotFoundException e)
{
}
}
}
}
I have added the corresponding string, but don't know what else to do: add an onclicklistener, I know I need some kind of action coded somewhere finish(); or .cancel something. Thanks for any help, again.
I should say, I've been playing around with this bit you see:
mDialog.setCancel(DialogInterface.BUTTON_NEGATIVE,getResources().getString(R.string.dialognothanks), null);
I am not sure if this is exactly what you are looking for, but you can do something like this... this one just closes the dialog.
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
For a very good tutorial on creating dialogs, I would recommend using : http://developer.android.com/guide/topics/ui/dialogs.html. This should be very helpful.
It's now working and performing how I wanted it to by doing this:
1) I removed:
public void setCancel(int buttonNegative, String string, Object object) {
// TODO Auto-generated method stub
}
and
mDialog.setCancel(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.dialognothanks), null);
2) and added:
mDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.dialognothanks),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
mDialog.cancel();
finish();
}
});
just before the
mDialog.show();
Trial and Error FTW. Maybe I should learn Java and Android from the ground up to save me the time later.
Now I have to learn how to make the Cancel button not only finish(); but also start another activity.
I figured out how to start an activity by following the answer on this page:
Android: How to start an Activity from an alert dialog
So my code now looks like:
mDialog.setButton(DialogInterface.BUTTON_NEGATIVE, getResources().getString(R.string.dialognothanks),
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent i = new Intent(getBaseContext(), AboutActivityOverview.class);
startActivity(i);
}
});

Categories

Resources