Load app/activity when phone wakes up from sleep - android

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?

Related

How can i avoid app forcefully closing error

App is designed in the way that it will check for Firebase ID on launching. If not,he will be taken to a Registration Activity. If already registered, he will be taken to home activity instead.
Along with this I have configured for click_action of push notification in launcher activity.
On the first opening, user can complete registration completes and open homeactivity as well. But when App is once closed and opened, App crash with message "forcefully closed".
When i checked in the Logcat, error showing is "null object at string line switch (clickaction){ .
please advise how can i rectify this.
public class MainActivity extends AppCompatActivity {
private static int SPLASH_TIME_OUT = 2000;
String clickaction;
FirebaseAuth firebaseAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
firebaseAuth=FirebaseAuth.getInstance();
FirebaseUser currentuser1 =firebaseAuth.getCurrentUser();
if (getIntent().getExtras() == null){
if (currentuser1!= null) {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent homeIntent = new Intent(MainActivity.this, HomeActivity.class);
startActivity(homeIntent);
finish();
}
}, SPLASH_TIME_OUT);
}
else {
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
Intent regintent = new Intent(MainActivity.this, Registration_Activity.class);
startActivity(regintent);
finish();
}
},SPLASH_TIME_OUT);
}
}
else
{
clickaction = (String) getIntent().getExtras().get("openactivity");
Intent intent=new Intent();
switch (clickaction){
case "Act1":
intent=new Intent(this, Activity1.class);
break;
case "Act2":
intent=new Intent(this, Activity2.class);
break;
case "Act3":
intent=new Intent(this, Activity3.class);
break;
default:
intent = new Intent(this, HomeActivity.class);
break;
}
startActivity(intent);
}
}
}

Activity minimize in android

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;
}
}

How to stop an intent activity from a service

I have started an Intent activity from a service. Now, how I can stop that intent activity from service itself?
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void startService (View view) {
Intent intent = new Intent(this,MainService.class);
startService(intent);
}
public void stopService (View view) {
Intent intent = new Intent(this,MainService.class);
stopService(intent);
}
}
startService, stopService have buttons associated.
public class MainService extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Service started",Toast.LENGTH_LONG).show();
Intent dialogIntent = new Intent(this, calledActivity.class);
dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(dialogIntent);
return START_STICKY;
//return super.onStartCommand(intent,flags,startId);
}
#Override
public void onDestroy() {
//super.onDestroy();
Toast.makeText(this, "Service stopped",Toast.LENGTH_LONG).show();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
//Intent dialogIntent = new Intent(this, MainActivity.class);
//dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//startActivity(dialogIntent);
return null;
}
}
public class calledActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toast.makeText(this, "I am here", Toast.LENGTH_LONG).show();
displayNumber();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "I am stopping", Toast.LENGTH_LONG).show();
finish();
}
#Override
protected void onDestroy () {
super.onDestroy();
Toast.makeText(this, "I am being destroyed", Toast.LENGTH_LONG).show();
finish();
}
public void displayNumber () {
TextView tv = (TextView)findViewById(R.id.textView);
Integer counter = 10;
while (counter > 0) {
//tv.setText("Here you go" + String.valueOf(counter));
tv.setText("Here you go" + counter);
counter = counter - 1 ;
Toast.makeText(this, "I am there "+counter, Toast.LENGTH_LONG).show();
}
}
}
When service invokes the intent activity, I think intent activity is on the foreground. Now, whenever I press stop service button, application crashes. I believe as stopService is associated with the service class but not in the intent activity. Is there any way to stop the intent activity from the service?
Service works on UI thread. Try using IntentService. It runs on background thread.

How to close app in activity

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();
}

Why doesn't stop an android activity after calling finish()?

I have an Activity called MyProgressDialog which contains a ProgressDialog. This ScreenProgressDialog activity is called in the Main activity by intents:
if(msg.what == SET_PROGRESS){
intent.putExtra("action", "set");
...
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else if(msg.what == SHOW_PROGRESS){
intent.putExtra("action", "show");
...
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
else if(msg.what == HIDE_PROGRESS){
intent.putExtra("action", "hide");
intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
startActivity(intent);
}
Here is the MyProgressDialog activity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.e("screenPD", "spd created");
extras = getIntent().getExtras();
pd = new ProgressDialog(this);
...setting the pd...
pd.show();
Log.e("screenPD", "spd shown");
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
int newTitle = intent.getExtras().getInt("title");
if (intent.getExtras().getString("action").equals("set")){
pd.set methods...
pd.show();
Log.e("DialogSET", "DialogSET "+intent.getExtras().getInt("progress"));
}
else if (intent.getExtras().getString("action").equals("show")){
pd.set methods...
pd.show();
Log.e("DialogSHOW", "DialogSHOW "+progress);
}
else if (intent.getExtras().getString("action").equals("hide")){
pd.dismiss();
this.finish();
Log.e("DialogHIDE", "DialogHIDE");
return;
}
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("screenPD", "destroyed");
}
And here is the LogCat:
DialogHIDE(2615): DialogHIDE
screenPD(2615): spd created
screenPD(2615): spd shown
screenPD(2615): destroyed
So the 3rd intent starts, calls the finish(); return; and the Onreate method is started which displays a new ProgressDialog. The onDestroy is called, but the ProgressDialog doesn't hide from the screen. After the finish() method the activity shold be closed. Where is the problem? Thank you!
There is no error. the method invoking finish() will run out to completion and after its completion the controll returns to Android
After startactivity method you call finish() to finish current activity. After start that new activity that finish the previous activity.

Categories

Resources