Determine if app was launched from home screen?

后端 未结 2 1491
礼貌的吻别
礼貌的吻别 2021-01-15 05:50

In my main activity, onCreate I set a textView to the current date. From that activity, I startActivityForResult activity2, where I can change the date. onActivityResult, I

相关标签:
2条回答
  • 2021-01-15 06:02

    Try to save the value of the date from activity2 into the android SharedPreferences.

    You can set the date to the preferences by using something like this:

    SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
    SharedPreferences.Editor prefsEditor = myPrefs.edit();
    prefsEditor.putString(MY_NAME, "Sai");
    prefsEditor.putString(MY_WALLPAPER, "f664.PNG");
    prefsEditor.commit();
    

    and you can read the preferences by using something like that:

    SharedPreferences myPrefs = this.getSharedPreferences("myPrefs", MODE_WORLD_READABLE);
    String prefName = myPrefs.getString(MY_NAME, "nothing");
    String wallPaper = myPrefs.getString(MY_WALLPAPER, null);
    

    Set a flag like "dateWasAlreadySet" to the SharedPreferences if the date was set from activty2, so you know that the date was already set.

    Pseudo Code:

    If(SharedPreferences.dateWasAlreadySet){
        activity1.textField.text = SharedPreferences.get("myDate");
    } else {
        activity1.textField.text = currentDate;
    }
    

    I hope you understand what I mean.

    0 讨论(0)
  • 2021-01-15 06:03

    How about something like this:

    First of all, create an onSaveInstanceState(Bundle) method and save the current contents of the date TextView to it. This is called before Android stops, hides, or destroys your activity.

    When you start activity2, your onStop() of activity1 will be called. In there, set a flag to indicate whether or not onStop() is called due to you starting a new activity (make the intent for activity2 a member, not local variable for this). Ensure you save this flag in onSaveInstanceState of activity1.

    Implement onRestoreInstanceState(Bundle) in activity1, and restore to local variables the date and flag values.

    Finally, in onResume of activity1, check the flag - it you are resuming because you are returning from activity2, do not change the TextView since that will be set in onActivityResult, otherwise, you can safely restore the saved date value.

    0 讨论(0)
提交回复
热议问题