哈玛林.当Android终止活动并且用户再次启动它时,有没有办法完全重新启动应用程序?



我的应用有多个活动,其中一些活动具有复杂的视图模型,并且它们之间存在高度依赖性。 当 Android 需要它时,它会终止进程,当用户再次导航到应用程序时,将调用最后一个使用的活动的 OnCreate。重建以前的状态很复杂,并且对于应用类型没有价值。当用户导航到已终止的活动时,只需系统从头开始重新启动应用程序,这将更加容易和强大。

有没有办法做到这一点?

你可以这样做

库斯顿我的应用程序.cs

[Application]
public class MyApplication : Application
{
    public static int APP_STATUS_KILLED = 0; // Represents that the application was started after it was killed
    public static int APP_STATUS_NORMAL = 1; // Represents the normal startup process at application time
    public static int APP_STATUS = APP_STATUS_KILLED; // Record the startup status of the App
    private static Context context;
    public override void OnCreate()
    {
        base.OnCreate();
        context = GetAppContext();
    }
    public static Context GetAppContext()
    {
        return context;
    }
    /**
     * Reinitialize the application interface, empty the current Activity stack, and launch the welcome page
     */
    public static void ReInitApp()
    {
        Intent intent = new Intent(GetAppContext(), typeof(SplashActivity));
        intent.SetFlags(ActivityFlags.ClearTask| ActivityFlags.NewTask);
        GetAppContext().StartActivity(intent);
    }
}

创建一个 SplashActivity.cs即 lanch 活动:

[Activity(Label = "SplashActivity")]
public class SplashActivity : Activity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        MyApplication.APP_STATUS = MyApplication.APP_STATUS_NORMAL; //App starts normally. Set the startup status of App to normal startup
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.activity_splash);
        GoMain();
    }
    private void GoMain()
    {
        Intent intent = new Intent(this, typeof(MainActivity));
        StartActivity(intent);
        Finish();
    }
}

然后创建 BaseActivity.cs ,所有活动都会将其扩展到 SplashActivity 旁边:

[Activity(Label = "BaseActivity")]
public abstract class BaseActivity : Activity
{
    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        if (MyApplication.APP_STATUS != MyApplication.APP_STATUS_NORMAL)
        { // Start the process abnormally and reinitialize the application interface directly
            MyApplication.ReInitApp();
            Finish();
            return;
        }
        else
        { // Normal startup process
            SetUpViewAndData(savedInstanceState); // child Activity initialization
        }
    }
    //Provide an interface to the subactivity setup interface. Do not initialize in onCreate
    protected abstract void SetUpViewAndData(Bundle savedInstanceState);
}

相关内容

最新更新