简体   繁体   English

重新启动应用程序时,SharedPreferences不起作用

[英]SharedPreferences not working when relaunch app

I have 4 activities: MainActivity, p1, p2, p3. 我有4个活动:MainActivity,p1,p2,p3。

My app works fine but problem here is that when app force stop or flick up app in home button to close, and when the app is opened again, seems shared performance is cleared. 我的应用程序运行正常,但是这里的问题是,当应用程序强制停止或按主页按钮中的应用程序以关闭它,并且再次打开该应用程序时,共享性能似乎已清除。

I use editor.apply() , but still not working. 我使用editor.apply() ,但仍然无法正常工作。

MainActivity: 主要活动:

public class MainActivity extends Activity {


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_page);



        final Button resume = (Button) findViewById(R.id.resume);
        Button next = (Button) findViewById(R.id.next);
        Button exit = (Button) findViewById(R.id.exit);


        resume.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                final String PREFS_NAME = "MyPrefsFile";

                SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);

                if (settings.getBoolean("my_first_time", true)) {

                    resume.setEnabled(false);

                    Log.d("Comments", "First time");


                    settings.edit().putBoolean("my_first_time", false).commit();
                }else
                {

                    MainActivity.this.finish();

                }
            }
        });

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, p1.class);
                startActivity(intent);
            }
        });

        exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(Intent.ACTION_MAIN);
                intent.addCategory(Intent.CATEGORY_HOME);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(intent);
            }
        });
    }
    }

Xml : Xml:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:text="resume"
        android:layout_width="wrap_content"
        android:id="@+id/resume"
        android:layout_height="wrap_content" />

    <Button
        android:text="next"
        android:id="@+id/next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/exit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="exit"/>
</LinearLayout>

P1: P1:

public class p1 extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.p1);

        Button next = (Button) findViewById(R.id.next);
        Button home=(Button)findViewById(R.id.home);

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent intent = new Intent(p1.this, p2.class);
                startActivity(intent);

            }
        });

        home.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {


                Intent intent = new Intent(p1.this, MainActivity.class);
                startActivity(intent);

            }
        });

}
    private void storeCurrentActivity(){
        SharedPreferences myPref =getSharedPreferences("APP_SHARED_PREF", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor=myPref.edit();
        editor.putString("lastactivity", p1.this.getClass().getSimpleName());
        editor.commit();

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

}

XML: XML:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:text="next"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/next"/>
<TextView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="page 1"/>
    <Button
        android:text="go in main"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/home"/>

</LinearLayout>

and p2, p3 like p1. 和p2,p3像p1。

You just save these values to Sharedpreference in onPause() method :) 您只需将这些值保存到onPause()方法中的Sharedpreference即可:)

Android Shared preferences example Android共享首选项示例

Update: 更新:

I usually create Preferences class (Singleton pattern) which exposes getters and setters to quickly read and save values to SharedPreferences. 我通常创建Preferences类(Singleton模式),该类公开getter和setter以快速读取值并将其保存到SharedPreferences。 I inject the same instance of Preferences anywhere in the code using Dagger as Dependency Injector. 我使用Dagger作为依赖项注入器在代码的任何位置注入了Preferences的相同实例。

Why do we should use singleton pattern: Why use a singleton instead of static methods? 为什么我们应该使用单例模式: 为什么使用单例而不是静态方法?

I will give you an example of Preferences class: 我将给您一个Preferences类的示例:

public class Preferences {

    private SharedPreferences sharedPreferences;
    private final String NOTIFICATIONS_ENABLED = "NOTIFICATIONS_ENABLED";

    @Inject
    public Preferences(Context context) {
        sharedPreferences = context.getSharedPreferences("Preferences", 0);
    }

    public void setNotificationsEnabled(boolean enabled){
        SharedPreferences.Editor edit = sharedPreferences.edit();
        edit.putBoolean(NOTIFICATIONS_ENABLED, enabled);
        edit.commit();           
    }

    public boolean isNotificationsEnabled(){
        return sharedPreferences.getBoolean(NOTIFICATIONS_ENABLED, true);
    }
}

And use it anywhere you want: 并在您想要的任何地方使用它:

public class MainActivity extends Activity {

    @Inject
    NavigationController navigationController;

    @Inject
    Preferences preferences;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        SharedObjectGraph.getObjectGraph().inject(this);

        if(preferences.isNotificationsEnabled()){
            // do something
        }
    }

you are putting 0 as default value in setting sharedPreference and in if condition checking is it false... 您将0作为默认值设置为sharedPreference,如果条件检查为false ...

PREFS_NAME = "MyPrefsFile"; PREFS_NAME =“ MyPrefsFile”; and

if (settings.getBoolean("my_first_time", true)) 如果(settings.getBoolean(“ my_first_time”,true))

are matching different conditions. 匹配不同的条件。 changed sharedpreference name 更改的共享首选项名称

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM