关闭应用程序时通过共享首选项保存开关按钮状态

Save Switch Button State via Shared Preferences When App is Closed

在我的 Activity 中,我有一个切换按钮。我想在应用程序从后台关闭时保持开关按钮的状态。

当应用程序在后台时,开关状态保持不变,但当应用程序从后台清除时,它会返回默认 (OFF) 状态。

我尝试从 复制程序。但是我还是无法保持开关按钮的状态。

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings);
    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    switch1 = (Switch) findViewById(R.id.switch1);

    SharedPreferences sharedPrefs = getSharedPreferences("com.example.xyz", MODE_PRIVATE);
    switch1.setChecked(sharedPrefs.getBoolean("NameOfThingToSave", true));


    switch1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (switch1.isChecked()) {

                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                editor.putBoolean("NameOfThingToSave", true);
                editor.apply();
                switch1.setChecked(true);

                AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
                // Setting Dialog Title
                alertDialog.setTitle("Download all the Product's PDF.");
                // Setting Icon to Dialog
                alertDialog.setIcon(R.drawable.pdf_alert_dialog);

                // Setting Positive "Yes" Button
                alertDialog.setPositiveButton("CANCEL",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                switch1.setChecked(false);
                                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                                editor.putBoolean("NameOfThingToSave", false);
                                editor.apply();

                                dialog.dismiss();
                            }
                        });
                // Setting Negative "NO" Button
                alertDialog.setNegativeButton("DOWNLOAD ALL ",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {

                                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                                editor.putBoolean("NameOfThingToSave", true);
                                editor.apply();

                                
                                AlertDialog.Builder alertDialog1 = new AlertDialog.Builder(context);
                                // Setting Dialog Title
                                alertDialog1.setTitle("Free storage Available:" + megAvailable1 + " MB");
                                alertDialog1.setMessage("File size to Download: POJO MB");
                                // Setting Icon to Dialog
                                alertDialog1.setIcon(R.drawable.pdf_alert_dialog);

                                alertDialog1.setPositiveButton("CANCEL",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog1, int which) {
                                                switch1.setChecked(false);
                                                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                                                editor.putBoolean("NameOfThingToSave", false);
                                                editor.apply();

                                                dialog1.dismiss();
                                            }
                                        });
                                // Setting Negative "NO" Button
                                alertDialog1.setNegativeButton("DOWNLOAD  ",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(DialogInterface dialog1, int which) {

                                                getFeedDownload();

                                                SharedPreferences.Editor editor = getSharedPreferences("com.example.xyz", MODE_PRIVATE).edit();
                                                editor.putBoolean("NameOfThingToSave", true);
                                                editor.apply();

                                            }

                                        });
                                alertDialog1.show();
                            }
                        });

                // Showing Alert Message
                alertDialog.show();
            } else {
            }
        }
    });

我哪里错了?

也许尝试 editor.commit() 而不是 editor.apply()。它们的区别可以参考这个post

我犯的错误是在我的 onResume 中我关闭了开关。 因此,每次我重新启动应用程序时,无论共享偏好如何,开关都会关闭。

我添加了一个检查以查看我是否在“下载”文件夹中下载了 PDF。 如果是,那么我只是将开关打开,如果不是,则关闭。

 @Override
public void onResume() {
    super.onResume();

    Call<List<Products>> listCall = mManager.getProductsService().getAllProducts();
    //execte for the call back (asynchronous).

    // Now we start to execute the call
    listCall.enqueue(new Callback<List<Products>>() {
        @Override
        public void onResponse(Response<List<Products>> response, Retrofit retrofit) {
            if (response.isSuccess()) {
                List<Products> productsList = response.body();

                for (int i = 0; i < productsList.size(); i++) {
                    Products products = productsList.get(i);
                    String links = (products.getFilePath());
                    String name = products.getFileID();
                    String link = links.replaceAll("\\", "");
                    Log.i("linkkkkkSettings", link);


                    File applictionFile = new File(Environment.getExternalStoragePublicDirectory(
                            Environment.DIRECTORY_DOWNLOADS) + "/" + name + ".pdf");
                    if (applictionFile != null && applictionFile.exists()) {

                        switch1.setChecked(bundle.getBoolean("ToggleButtonState", true));
                    } else {

                        switch1.setChecked(bundle.getBoolean("ToggleButtonState", false));
                    }


                }
            }
        }

        @Override
        public void onFailure(Throwable t) {

        }
    });


}

我更喜欢将状态开关保存为共享首选项的布尔值。
然后在 onCreate()onResume() 后加载共享首选项 这样做:

daynight = findViewById(R.id.switchDnevni);
daynight.setChecked(switchChecked);