[英]Is there a way to restart completely the app when Android kills the activity and the user starts it again?
我的应用程序有多个活动,其中一些活动具有复杂的视图模型,并且它们之间的依赖性很高。 当Android需要它时,它会终止该过程,并且当用户再次导航到该应用程序时,将调用最后使用的活动的OnCreate。 重建以前的状态很复杂,并且对于应用程序的类型没有价值。 当用户导航到被终止的活动时,系统会从头开始重新启动应用程序,这将变得更加容易和强大。
有办法吗?
你可以这样
custon MyApplication.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 ,它是启动活动:
[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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.