[英]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.