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

时间:2016-08-04 09:55:55

标签: android sharedpreferences android-switch android-togglebutton

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

当应用程序在后台运行时,交换机的状态仍然存在,但当应用程序从后台清除时,它会返回默认(关闭)状态。

我尝试从here复制程序。但我仍然无法维持开关按钮的状态。

@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 {
            }
        }
    });

你能告诉我哪里出错了吗?

3 个答案:

答案 0 :(得分:1)

也许尝试使用editor.commit()而不是editor.apply()。请参阅此post了解它们之间的区别。

答案 1 :(得分:0)

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

我添加了一张支票,看看我是否在Downloads文件夹中下载了PDF。 如果是,那么我只需将开关转到ON,如果没有,则关闭。

 @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) {

        }
    });


}

答案 2 :(得分:0)

我更喜欢将状态开关另存为共享首选项的布尔值。 然后在onCreate()和onResume()之后加载共享的首选项 做到这一点。

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

快乐的编码,