我正在使用 Google Cloud Messaging 创建一个应用。打开应用程序后,我的主要 Activity (LoginActivity) 注册应用程序并接收“GCM 注册 token ”,我将以下行放入 RegistrationIntentService 中。
sharedPreferences.edit().putString("token", token).apply();
该 Activity 获取此 token 并显示带有该 token 的 toast。但是在我按下按钮(btn_login)后, token 被清空......
这是LoginActivity中的代码
private BroadcastReceiver mRegistrationBroadcastReceiver;
private static final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
private boolean isReceiverRegistered;
private Context context;
static String token;
Button btn_login;
EditText txt_GebruikersNaam, txt_Wachtwoord;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
context = getApplicationContext();
btn_login = (Button)findViewById(R.id.btn_login);
txt_GebruikersNaam= (EditText)findViewById(R.id.txt_GebruikersNaam);
txt_Wachtwoord= (EditText)findViewById(R.id.txt_Wachtwoord);
btn_login.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String gebruikersnaam = txt_GebruikersNaam.getText().toString();
String wachtwoord = txt_Wachtwoord.getText().toString();
if(!gebruikersnaam.equals("") || !wachtwoord.equals("")) {
// HERE THE TOKEN IS EMPTY
String json = createJsonPost(gebruikersnaam, wachtwoord, token);
}
}
});
token = getToken();
}
private String getToken(){
final String[] token = {""};
mRegistrationBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
boolean sentToken = sharedPreferences.getBoolean(QuickstartPreferences.SENT_TOKEN_TO_SERVER, false);
if (sentToken) {
CharSequence text = sharedPreferences.getString("token",null);
Toast.makeText(context, text.toString(), Toast.LENGTH_SHORT).show();
token[0] = text.toString();
} else {
Toast.makeText(context, "Geen verbinding", Toast.LENGTH_SHORT).show();
}
}
};
// Registering BroadcastReceiver
registerReceiver();
if (checkPlayServices()) {
// Start IntentService to register this application with GCM.
Intent intent = new Intent(this, RegistrationIntentService.class);
startService(intent);
}
return token[0];
}
private void registerReceiver(){
if(!isReceiverRegistered) {
LocalBroadcastManager.getInstance(this).registerReceiver(mRegistrationBroadcastReceiver,
new IntentFilter(QuickstartPreferences.REGISTRATION_COMPLETE));
isReceiverRegistered = true;
}
}
private String createJsonPost(String Naam, String Wachtwoord, String token){
JSONObject jsonObject = new JSONObject();
JSONObject jsonData = new JSONObject();
jsonData.put("user", Naam);
jsonData.put("pass", Wachtwoord);
jsonData.put("token", token);
jsonObject.put("authorization", jsonData);
}
最佳答案
这是因为您的 token = getToken();
在触发 onReceive(Context context, Intent Intent)
之前运行。您应该在 onReceive(Context context, Intentintent)
函数中设置您的token
。
关于java - 字符串填充后变空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37275776/