在背景上松开MainActivity

时间:2016-11-22 18:33:49

标签: android activity-lifecycle application-lifecycle

每次应用程序进入后台,并且RAM开始填写,应用程序开始丢失变量(如果我没有错,这是Android的正常行为,它会丢失变量的实例)

当我从后台带回应用程序时,应用程序崩溃,因为我松开了MainActivity。

如果根本没有活动,有办法重新启动此活动吗? 这是一个含糊不清的问题,但我发现了这个问题,但我认为这不是最好的选择

ActivityManager mngr = (ActivityManager) getSystemService( ACTIVITY_SERVICE );

List<ActivityManager.RunningTaskInfo> taskList = mngr.getRunningTasks(10);

if(taskList.get(0).numActivities == 1 &&
   taskList.get(0).topActivity.getClassName().equals(this.getClass().getName())) {
    Log.i(TAG, "This is last activity in the stack");
}

我失去了完整的活动,我可以参加活动

@Override
public void onAttach(Activity activity) {
    LocalNotification.registerReceiver(reloadReceiver, LocalNotification.RELOAD_CARTMG);
    try {
        mListener = (OnFragmentInteractionListener) activity;
        MainActivity ma = (MainActivity)activity; //THIS IS LOOSE
        ma.openMyList = false;
        ma.openMyAddress = false;
        ma.hideSearchButton();
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement OnFragmentInteractionListener");
    }

    super.onAttach(activity);
}

这是应用内的日志

com.XXXX.mg E/Uncaught Exception detected in thread {}: Unable to start activity ComponentInfo{com.XXXX.mg/com.XXXX.view.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.XXXX.view.MainActivity.showShoppingCartIcon()' on a null object reference
                                                       java.lang.RuntimeException: Unable to start activity ComponentInfo{com.XXXX.mg/com.XXXX.view.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.XXXX.view.MainActivity.showShoppingCartIcon()' on a null object reference
                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2426)
                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490)
                                                           at android.app.ActivityThread.-wrap11(ActivityThread.java)
                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354)
                                                           at android.os.Handler.dispatchMessage(Handler.java:102)
                                                           at android.os.Looper.loop(Looper.java:148)
                                                           at android.app.ActivityThread.main(ActivityThread.java:5443)
                                                           at java.lang.reflect.Method.invoke(Native Method)
                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
                                                        Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.XXXX.view.MainActivity.showShoppingCartIcon()' on a null object reference
                                                           at com.XXXX.view.shoppingCart.ShoppingCartFragment.onDetach(ShoppingCartFragment.java:411)
                                                           at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1202)
                                                           at android.support.v4.app.FragmentManagerImpl.removeFragment(FragmentManager.java:1349)
                                                           at android.support.v4.app.BackStackRecord.popFromBackStack(BackStackRecord.java:915)
                                                           at android.support.v4.app.FragmentManagerImpl.popBackStackState(FragmentManager.java:1722)
                                                           at android.support.v4.app.FragmentManagerImpl$3.run(FragmentManager.java:593)
                                                           at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1617)
                                                           at android.support.v4.app.FragmentController.execPendingActions(FragmentController.java:339)
                                                           at android.support.v4.app.FragmentActivity.onStart(FragmentActivity.java:602)
                                                           at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1260)
                                                           at android.app.Activity.performStart(Activity.java:6261)
                                                           at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2389)
                                                           at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2490) 
                                                           at android.app.ActivityThread.-wrap11(ActivityThread.java) 
                                                           at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1354) 
                                                           at android.os.Handler.dispatchMessage(Handler.java:102) 
                                                           at android.os.Looper.loop(Looper.java:148) 
                                                           at android.app.ActivityThread.main(ActivityThread.java:5443) 
                                                           at java.lang.reflect.Method.invoke(Native Method) 
                                                           at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728) 
                                                           at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618) 

2 个答案:

答案 0 :(得分:2)

我不确定你的应用程序是否因为你的MainActivity松动而崩溃,你应该编码期待这种行为,使用像@pablobu建议的onSaveInstanceState是正确的方法。

我们能看到日志吗?如果您失去了实例的状态,那么您应该保存这些状态并将其恢复Recreating an Activity是因为碎片?你也可以保存这些,Handling Fragments Tutorial这是一个很好的阅读。

请你能给我们你的logcat输出,这对我们看到真正有用的东西可能有很大帮助。

修改

使用Logcat编辑,尝试查看片段生命周期,onAttach首先执行而不是onActivityCreated(),所以如果你的Activity已被销毁,你的onAttach方法将不会有你的活动,你应该等到你的Activity是重新创建

此外,你有

super.onAttach(activity);

在代码块的末尾,将它放在代码块之前。

/**
This method was deprecated in API level 23.
Use onAttach(Context) instead.
*/
@Override
public void onAttach(Context context) { 
super.onAttach(context);
MainActivity mainActivity;
if (context instanceof Activity) {
    mainActivity = (MainActivity) context;
    try {
        mListener = (OnFragmentInteractionListener) mainActivity;
        /**
        Since you are getting a reference and accesing attributes you should be careful
        with NullPointerException, check if not null first.
        Or better yet refactor a little your code using an interface to handle this behaviour or use
        the one you already created and just tell the activity what to do.

        */
        /*if(mainActivity != null) {
            ma.openMyList = false;
            ma.openMyAddress = false;
            ma.hideSearchButton();
        }*/

    } catch (ClassCastException e) {
        throw new      ClassCastException(mainActivity.getClass().getSimpleName() + " must implement OnFragmentInteractionListener");
    }
}
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
//since your Listener is global use mListener behaviour that I suggested here.
if (mListener != null){
        mListener.openListOfSomething(false);
        mListener.hideSearch();
    }
}

答案 1 :(得分:0)

您可以使用Bundle savedInstatceState,它在OnCreate和类似的方法中给出:

private String aVariable;

@Override
public void onCreate (Bundle savedInstantceState) {
   super.onCreate(savedInstanceState);
   // Get the variable from savedInstanceState, if it isn't empty.
   // If it is empty, it could be the first Activity run.
   try { 
      aVariable = savedInstanceState.get("Key");
   } catch (NullPointerException e) {
      aVariable = "Baum";
   }
}

@Override
public void onSaveInstanceState(Bundle outState){
    super.onSaveInstanceState(outState);
    outState.putString(aVariable, "Key");
}

这些方法在第一次运行时将变量“aVariable”设置为“Baum” (NullPointerException,因为没有String到“Key”)。 稍后,当Activity将被销毁时,将调用onSaveInstanceState。在那里你保存变量(aVariable)在一个键(“键”)下。