从Android服务中的get SharedPreferences获取数据

时间:2019-04-11 22:44:09

标签: android service sharedpreferences

启动Service类后如何从SharedPreferences中获取数据? 在这段代码中,我有很多令人困惑的问题。有时,如果在onCreate()中运行,则首先在MyService.class中运行有时不这样做。在我的代码中,有时displayName()返回null有时返回a但我无法在MyService.class中执行saveName(“ b”)。我该怎么做呢?我需要从最初在MainActivity类中创建的SharedPreferences中读取数据。

MyService.class是:

public class MyService extends Service {
    private   String SHARED_PREF_NAME = "username";
    private   String KEY_NAME = "key_username";
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(this, " onBind ...   " , Toast.LENGTH_SHORT ).show();
        return null;
    }

    @Override
    public void onCreate() {

        if( displayName() == "a" )
        {
            Toast.makeText(this, " ٬٬٬٬٬٬٬٬٬"  +  displayName()   , Toast.LENGTH_SHORT ).show();
            saveName("b");

        }else if ( displayName() == "b" )
        {
            Toast.makeText(this, " ٬٬٬٬٬٬٬٬٬ "  +  displayName()  , Toast.LENGTH_SHORT ).show();
        }else
        {
            Toast.makeText(this, " ٬٬٬٬٬٬٬٬٬ nothing :"  +   displayName()    , Toast.LENGTH_SHORT ).show();
        }


        // super.onCreate();
    }


    @Override
    public int  onStartCommand(Intent intent , int flags , int startId) {
       // Toast.makeText(this, " onStartCommand ...   "  , Toast.LENGTH_SHORT ).show();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        Toast.makeText(this, " onDestroy ...   "  , Toast.LENGTH_SHORT ).show();
        super.onDestroy();
    }//onDestroy

    public String displayName() {
        //myapp.bmodel.getApplicationContext().
        SharedPreferences sp = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE);
        String name = sp.getString(KEY_NAME, null);
        return name;
    }//displayName

    public void saveName(String name) {
        SharedPreferences sp = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(KEY_NAME, name);
        editor.apply();
    }//saveName

}

和MainActivity.class是:

public class MainActivity extends AppCompatActivity {

    Button button;
    TextView textView;
    EditText editText;

    private   String SHARED_PREF_NAME = "username";
    private   String KEY_NAME = "key_username";


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.textView);
        editText = (EditText) findViewById(R.id.editText);
        button = (Button) findViewById(R.id.button);

        displayName();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                saveName();
            }
        });



    }

    public void startService(View view){
        Intent intent= new  Intent(this, MyService.class);
        startService(intent);
    }

    public void stopService(View view){
        Intent intent= new  Intent(this, MyService.class);
        stopService(intent);
    }




    private void displayName() {
        SharedPreferences sp = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE);
        String name = sp.getString(KEY_NAME, null);

        if (name != null) {
            textView.setText("Welcome " + name);
        }

    }


    private void saveName() {
        String name = editText.getText().toString();
        if (name.isEmpty()) {
            editText.setError("Oops! No Name");
            editText.requestFocus();
            return;
        }
        SharedPreferences sp = getSharedPreferences(SHARED_PREF_NAME, MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString(KEY_NAME, name);
        editor.apply();
        // Optional, to display the name after shared prefs saved.
        displayName();
    }
}//class

1 个答案:

答案 0 :(得分:0)

将此代码用于Myservice类:

NULL
  

displayName()==“ a” ---> displayName()。equals(“ a”)

  

editor.apply()---> editor.commit()

commit():同步写入数据(阻止从其调用的线程)。然后它会通知您该操作成功。

apply():计划将数据异步写入。它不会通知您有关操作成功的信息。