实时提升接收方的共享偏好?

时间:2017-08-09 14:45:51

标签: java android sharedpreferences

这是我的第一个Android应用程序,我试图在接收方面实时更新共享偏好,代码是mainactivity.java

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        disp =(TextView) findViewById(R.id.textView2);
        sharedPreferences = getSharedPreferences(MyPREFERENCES,Context.MODE_PRIVATE);
        String host = sharedPreferences.getString(hostip,"");

        String clientId = MqttClient.generateClientId();
        client = new MqttAndroidClient(this.getApplicationContext(),"tcp://"+host,clientId);

        try {
            IMqttToken token = client.connect();
            token.setActionCallback(new IMqttActionListener() {
                @Override
                public void onSuccess(IMqttToken asyncActionToken) {
                    Toast.makeText(MainActivity.this,"Connected",Toast.LENGTH_LONG).show();
                }
                @Override
                public void onFailure(IMqttToken asyncActionToken, Throwable exception) {
                    Toast.makeText(MainActivity.this,"Connection failed",Toast.LENGTH_LONG).show();
                }
            });
        } catch (MqttException e) {
            e.printStackTrace();
        }
}

settings.java是发件人方

 SharedPreferences sharedpreferences;
    public static final String MyPREFERENCES = "MyPrefs" ;
    public static final String hostip = "hostipkey" ;
    public static final String topic = "topickey" ;


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

        editText1 = (EditText) findViewById(R.id.ipadd);
        editText2 = (EditText) findViewById(R.id.api);
        sharedpreferences = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);

        submit=(Button)findViewById(R.id.submit);



        submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String host  = editText1.getText().toString();
                String api  = editText2.getText().toString();
                SharedPreferences.Editor editor = sharedpreferences.edit();
                editor.putString(hostip, host);
                editor.putString(topic, api);
                editor.apply();
                Toast.makeText(settings.this,"Done",Toast.LENGTH_LONG).show();
            }
        });

     }

上面的代码运行良好,但我遇到的问题是我的共享首选项数据不会在接收方实时更新。为了获取数据,我必须重新启动应用程序,以便我的主要活动中的新值得到更新。任何有关这方面的帮助都非常感谢

此致 SAIF

2 个答案:

答案 0 :(得分:0)

尝试更新MainActivity中onResume中的值,它可以正常工作。

答案 1 :(得分:0)

Muthukishnan是对的,因为onResume()将在创建并重新启动后调用,onCreate()仅在创建活动时调用。

请参阅:Application Lifecircle