My app start with splash screen. Splash screen visible for 5 seconds then menu activity start. But when splash screen on display and I press back or home button app go in background but after few seconds its come on foreground automatically with menu activity. I want if user press home or back key app close permanently. Here is what I have tried so far.
Splash Screen Activity-
public class SplashScreen extends Activity
{
/** Called when the activity is first created. */
TimerTask task;
Intent objIntent, intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
UtilClass.playing = true;
objIntent = new Intent(SplashScreen.this, PlayAudio.class);
startService(objIntent);
new Handler().postDelayed(csRunnable2, 5000);
}
Runnable csRunnable2=new Runnable()
{
#Override
public void run()
{
intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
finish();
}
};
public void onBackPressed()
{
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
finish();
return;
}
#Override
protected void onPause() {
super.onPause();
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
finish();
}
}
You can see in onPause and onBackPressed I am closing app. But its start with menu activity after few seconds.
what suitianshi suggests is
public class SplashScreen extends Activity
{
/** Called when the activity is first created. */
TimerTask task;
Intent objIntent, intent;
Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
UtilClass.playing = true;
objIntent = new Intent(SplashScreen.this, PlayAudio.class);
startService(objIntent);
handler = new Handler();
handler.postDelayed(csRunnable2, 5000);
}
Runnable csRunnable2 = new Runnable()
{
#Override
public void run()
{
intent = new Intent(SplashScreen.this, MainActivity.class);
startActivity(intent);
finish();
}
};
public void onBackPressed()
{
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
finish();
return;
}
#Override
protected void onPause() {
super.onPause();
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
finish();
}
#Override
protected void onStop() {
super.onStop();
handler.removeCallbacks(csRunnable2);
}
}
As, Chris mentioned, Declare your HANDLER globally as,
Handler handler;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
UtilClass.playing = true;
objIntent = new Intent(SplashScreen.this, PlayAudio.class);
startService(objIntent);
handler = new Handler();
handler.postDelayed(csRunnable2, 5000);
}
Here in this Line,
handler.postDelayed(csRunnable2, 5000);
You are calling your "csRunnable2", after 5 seconds, So, it will come up after 5 seconds until unless,
=> You destroy your instance of handler class completely or ,
=> Make all the references Null.
So, When ever you are closing or pausing your activity(as in onBackPressed(), onPause(), onStop(), onDestroy() etc.,.) make sure to call :
handler.removeCallbacksAndMessages(null);
before you start next Activity.
This will makes null of all Handler instances.
For eg., in your code you can call,
public void onBackPressed()
{
handler.removeCallbacksAndMessages(null);
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
finish();
return;
}
#Override
protected void onPause() {
super.onPause();
handler.removeCallbacksAndMessages(null);
objIntent = new Intent(this, PlayAudio.class);
stopService(objIntent);
finish();
}
Related
I have an android activity, but when the phone goes to sleep(meaning I leave the phone there for a few seconds and then the screen goes black) and I turn it back on, the activity/app disappears(it's still active but i have to press the overview button to come back to the activity/app). How do I get it to come back automatically?
What I want to do is when the phone goes to sleep, when I turn it back on, the app/activity is there as it was when it went to sleep. I've checked up onResume, BroadcastReceivers, WakeLock, KeepScreenOn, Services, but I know I'm not doing it right.
OnResume doesn't work, WakeLock doesn't work, KeepScreenOn, just keeps the screen on and doesn't allow the phone to sleep, I haven't tried Services and BroadcastReceivers, but I thought I should ask here first.
Please help. Thanks.
I have MainActivity.java which opens initially and then starts AdminAddMerchantActivity.java. AdminAddMerchantActivity.java is a navigationView that starts 4 fragments including TimeFragment.java which has a tab layout, a view pager and a pager adapter. TimeFragment.java starts 5 fragments including PriceFragment.java.
Below is the activities lifecycle methods below.
MainActivity.java:
...
#Override
protected void onPause() {
super.onPause();
Log.d("state", "Pausing Main");
// Handle countdown stop here
}
#Override
protected void onResume() {
super.onResume();
Log.d("state", "Resuming Main");
currentActivity = sharedPreferences.getString(CURRENT_ACT, "main");
if(mAuth.getCurrentUser() != null)
{
if(currentActivity.equals("confirmFinalOrder"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, ConfirmFinalOrderActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("merchantDetails"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, MerchantDetailsActivity.class);
intent.putExtra("mid", sharedPreferences.getString("merchantid", ""));
startActivity(intent);
finish();
}
else if(currentActivity.equals("navigation")) {
isResumed++;
Intent intent = new Intent(MainActivity.this, NavigationActivity.class);
fragment = sharedPreferences.getString("fragment", "Find Food");
intent.putExtra("activity", fragment);
startActivity(intent);
finish();
}
else if(currentActivity.equals("adminaddnewmerchant"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, AdminAddNewMerchantActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("searchmerchants"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, SearchMerchantsActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("settingsuser"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, SettingsActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("settingsmerchant"))
{
isResumed++;
Intent intent = new Intent(this, SettingsMerchantActivity.class);
startActivity(intent);
finish();
}
else if(currentActivity.equals("sellerregistration"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, SellerRegistrationActivity.class);
startActivity(intent);
finish();
}
}
else{
if(currentActivity.equals("sellerregistration"))
{
isResumed++;
Intent intent = new Intent(MainActivity.this, SellerRegistrationActivity.class);
startActivity(intent);
finish();
}
else if(!sharedPreferences.getString("current activity", "main").equals("login user")
&& !sharedPreferences.getString("current activity", "main").equals("login merchant"))
{
currentActivity = "main";
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.clear();
editor.putString(CURRENT_ACT,currentActivity);
editor.commit();
Paper.book().write(Prevalent.RememberMeMerchant, "false");
Paper.book().write(Prevalent.emailKey, "UserEmail");
Paper.book().write(Prevalent.passwordKey, "UserPassword");
}
}
// Handle countdown start here
}
#Override
protected void onStop() {
super.onStop();
Log.d("state","Stopping Main");
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d("state", "Destroyed Main");
}
#Override
protected void onRestart() {
super.onRestart();
Log.d("state", "Restarted Main");
}
#Override
protected void onStart() {
super.onStart();
Log.d("state", "Started Main");
}
#Override
protected void onRestoreInstanceState(#NonNull Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
Log.d("state", "onRestoreInstanceState Main");
}
#Override
protected void onSaveInstanceState(#NonNull Bundle outState) {
super.onSaveInstanceState(outState);
Log.d("state", "onSaveInstanceState Main");
}
//if the user
#Override
public void onBackPressed() {
Log.d("state", "back login");
currentActivity = "main";
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString(CURRENT_ACT,currentActivity);
editor.commit();
}
...
AdminAddNewMerchantActivity.java:
...
#Override
public void onBackPressed()
{
if(drawer.isDrawerOpen(GravityCompat.START))
{
drawer.closeDrawer(GravityCompat.START);
}
else{
super.onBackPressed();
}
}
#Override
public void onResume() {
super.onResume(); // Always call the superclass method first
// Get the Camera instance as the activity achieves full user focus
//if (mCamera == null) {
//initializeCamera(); // Local method to handle camera init
//}
}
...
PriceFragment.java:
...
#Override
public void onDestroy() {
super.onDestroy();
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("scrollPrice", scrollView.getScrollY());
editor.commit();
}
#Override
public void onResume() {
Log.d("onResume", "Resumed");
super.onResume();
}
...
TimeFragment.java:
...
#Override
public void onResume() {
super.onResume();
}
...
The default Android behavior should do this automatically...
Are you doing something special on the onPause or onStop methods?
And if you're not, can you create a new project via Android Studio and test to see if this behavior persists on the new app?
Im working on offline login based application using SQLite. For the purpose of security i need to move to login activity if the app has minimized. i tried this code in onPause function
#Override
protected void onPause() {
Intent intent = new Intent(dashboard.this, login.class);
startActivity(intent);
finish();
super.onPause();
}
when i try to move from that activity to another also it moves to the login activity. i hope when im moving to another activity current activity is set to paused. that's why it moves to login activity.
you must set a Boolean to handle loginActivity ;
boolean mustGoToLoginActivity=true;
when you want to go to another Activity first set this boolean to false for example :
public void goToAnotherActivity(){
mustGoToLoginActivity=false;
//...
startActivity(anotherActivity);
}
and in onResume() methode set taht to true .
then in onPause() method :
#Override
protected void onPause() {
if(mustGoToLoginActivity){
Intent intent = new Intent(dashboard.this, login.class);
startActivity(intent);
finish();
}
super.onPause();
}
You are right, this scenario will not work. What you can do is use a static boolean to achieve the behavior like this.
public class MainActivity extends AppCompatActivity {
static Boolean navigateToLogin =false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (navigateToLogin) {
move();
navigateToLogin =false;
}
}
private void move() {
Intent intent = new Intent(this, newActivity.class);
startActivity(intent);
}
#Override
protected void onPause() {
super.onPause();
navigateToLogin = true;
}
}
I have an activity in android application and from that I am calling a method of an AsyncTask class which is calling a webservice. I want to reset/reload my activity on the basis of the result i get from that method. How can I reset my activity from that class?
You can try the following
Pass calling Activity context to your AsyncTask in constructor and save it in a variable Context context.
Then in your PostExecute method of AsyncTask, write following lines :
Intent targetIntent = new Intent(context, TargetActivity.class);
// Add your data to intent
targetIntent.putExtra("intent_extra_key", "intent_extra_value");
context.startActivity(targetIntent);
((Activity) context).finish();
Revert back for any issue.
Example:
Note: Remove the comment and delete or use comment for startActivity(i); in onPostExecute(Boolean aBoolean) if you want to test code example below without changing it.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
new LoadFromWebAsyncTask(this).execute();
}
private class LoadFromWebAsyncTask extends AsyncTask<Void, Void, Boolean> {
MainActivity activity;
LoadFromWebAsyncTask(MainActivity activity) {
this.activity = activity;
}
#Override
protected Boolean doInBackground(Void... params) {
return true;
}
#Override
protected void onPostExecute(Boolean aBoolean) {
super.onPostExecute(aBoolean);
activity.finish();
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
/* final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
activity.finish();
Intent i = new Intent(MainActivity.this, MainActivity.class);
startActivity(i);
}
}, 5*1000);*/
}
}
}
On button click I am opening activity(ActionListActivity) and sending intent to IntentService (later this service sends broadCast intent to ActionListActivity). But I am usually receiving only the first intent after launch. Is it real that intent is sent before the receiver is registred?
I want to get data providet by the intentService, and update my UI using it.
Scheme Activity->IntentService->BroadCastReceiver inside ActionListActivity
Activity:
private void selectDrawerItem(MenuItem menuItem)
{
switch (menuItem.getItemId()) {
case R.id.actions:{
Intent myIntent = new Intent(this, ActionListActivity.class);
this.startActivity(myIntent);
ProgressDialog progressDialog = new ProgressDialog(this);
progressDialog.show();
Intent dataIntent = new Intent(this, DatabaseWorkIntentService.class);
dataIntent.putExtra(Utils.INTENT_SERVICE_INVOKE, Utils.READ_ACTIONS_DATA);
startService(dataIntent);
progressDialog.dismiss();
}
}
}
IntentService:
private void readActionData(){
Log.e("read actions data","data");
List<Action> actionList;
actionList = Action.listAll(Action.class);
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(Utils.READ_ACTIONS_DATA);
broadcastIntent.putParcelableArrayListExtra(Utils.READ_ACTIONS_DATA, (ArrayList<? extends Parcelable>) actionList);
sendBroadcast(broadcastIntent);
}
ActionListActivity:
public class ActionListActivity extends BaseActivity {
boolean mIsReceiverRegistered = false;
DataBroadcastReceiver receiver;
TextView someTv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.action_list_activity);
this.initToolbarAndDrawerWithReadableName(getString(R.string.our_actions));
someTv = (TextView)findViewById(R.id.someTv);
}
public void someTvTest(Action action){
someTv.append(action.getName());
Log.e("data",action.getName());
}
#Override
protected void onPause() {
super.onPause();
if (mIsReceiverRegistered) {
unregisterReceiver(receiver);
receiver = null;
mIsReceiverRegistered = false;
}
}
#Override
protected void onResume() {
super.onResume();
if (!mIsReceiverRegistered) {
if (receiver == null)
receiver = new DataBroadcastReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(Utils.READ_ACTIONS_DATA);
receiver.setMainActivityHandler(this);
registerReceiver(receiver, filter);
mIsReceiverRegistered = true;
}
}
}
class DataBroadcastReceiver extends BroadcastReceiver{
ActionListActivity activity = null;
ArrayList<Action> list;
public void setMainActivityHandler(ActionListActivity main){
activity = main;
}
#Override
public void onReceive(Context context, Intent intent) {
Log.e("reciever","reciev");
list = intent.getParcelableArrayListExtra(Utils.READ_ACTIONS_DATA);
for (Action action:list){
if(activity!=null) {
activity.someTvTest(action);
}
}
}
}
You start activity and service async.
You need to start service inside ActionListActivity and wait for response.
The question is pretty self explanatory.
I'm doing a class that registers the activity of the user in order to avoid inactivity, after 2 minutes of no activity or everytime the user minimizes the app, the app should close. My code is the one listed below:
public class InActivityTimer extends Activity {
public static final long DISCONNECT_TIMEOUT = 2*60*1000; // 2 min = 2 * 60 * 1000 ms
public static int ESTADO_ACTIVIDAD=0; //Variable para saber si la actividad está al frente o no.
private static Handler disconnectHandler = new Handler(){
public void handleMessage(Message msg) {
}
};
private Runnable disconnectCallback = new Runnable() {
#Override
public void run() {
// Perform any required operation on disconnect
//finish();
finishAffinity();
Intent intent = new Intent(getApplicationContext(),VentanaInactividadCierreAplicacion.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
//intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intent);
}
};
public void resetDisconnectTimer(){
disconnectHandler.removeCallbacks(disconnectCallback);
disconnectHandler.postDelayed(disconnectCallback, DISCONNECT_TIMEOUT);
}
public void stopDisconnectTimer(){
disconnectHandler.removeCallbacks(disconnectCallback);
}
#Override
public void onUserInteraction(){
resetDisconnectTimer();
}
#Override
public void onResume() {
super.onResume();
ESTADO_ACTIVIDAD ++;
resetDisconnectTimer();
comprobarEstado();
}
private void comprobarEstado() {
if (ESTADO_ACTIVIDAD == 0){
// Intent startMain = new Intent(getApplicationContext(), SplashScreen.class);
// startMain.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
// startActivity(startMain);
// finish();
finishAffinity();
Toast.makeText(getApplicationContext(), "RandomPassGEN cerrado por seguridad", Toast.LENGTH_SHORT).show();}
}
#Override
public void onStop() {
super.onStop();
ESTADO_ACTIVIDAD--;
stopDisconnectTimer();
comprobarEstado();
}
/* #Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getBaseContext(),"La aplicación se reiniciará por seguridad", Toast.LENGTH_SHORT).show();
finishAffinity();
}*/
}
As you can see, I'm using finishaffinty twice. How could I do it withous using that command? I'd like to avoid it because using finishAffinity() needs android +4.1
Thank you so much for your help.
To close your application, do the following:
Intent intent = new Intent(this, MyRootActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("exit", true);
startActivity(intent);
MyRootActivity should be the root activity of your task (this is the one with ACTION=MAIN and CATEGORY=LAUNCHER in the manifest).
In MyRootActivity.onCreate() add the following after super.onCreate():
if (getIntent().hasExtra("exit")) {
// User wants to exit, so do that
finish();
return;
}
... here is the rest of your onCreate() code
This will only work if MyRootActivity doesn't call finish() when it starts the next Activity in your workflow. If MyRootActivity does call finish() when it starts the next Activity, you should change it so that it doesn't. In that case you will need to handle the case where the user BACKs into MyRootActivity as a special case.