簡體   English   中英

如何退出並停止從應用程序運行的后台但不關閉服務

[英]How to exit with stopping the background running from application but, not close services

我一直在尋找關於如何關閉Android應用程序的解決方案。

收集所有涉及該主題的帖子,我最終建立了一個健康有效的解決方案,我想在這篇文章中分享

如果我在某處失敗了,請糾正我。

public static void closeApp(Activity activity) {
    //Go to home to change main android view and focus
    //You can remove this part
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_HOME);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        activity.startActivity(intent);

    //finish in background many activities as possible
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        activity.finishAndRemoveTask();
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        activity.finishAffinity();
    } else {
        activity.finish();
    }

    //Kill all existing app process
    activity.moveTaskToBack(true);
    android.os.Process.killProcess(android.os.Process.myPid());

    //close the app
    System.exit(0);
}

用例子

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            closeApp(MainActivity.this);
        }
    });
}

在發布資源和完全關閉應用程序時,您使用的方法看起來非常全面。 雖然我覺得它有點過分,但如果這是你的用例所要求的,那么沒有問題。 您可以查看此SO以獲取更多見解。

我對以下行發表評論

停止從應用程序運行的后台,但不關閉服務

android.os.Process.killProcess(android.os.Process.myPid()); 此方法將使用給定的PID終止進程。 如果您的服務正在運行此PID,那么它們也將被殺死。

從Android O開始,對后台執行施加了一些限制,因此您無法在后台運行服務。 當您的應用程序退出時,操作系統將終止服務,就像您調用了stopSelf() 因此,您將無法使您的服務保持活力。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM