在服务和活动之间发送数据

时间:2018-08-01 17:21:35

标签: android

我想将数据(字符串)从服务发送到活动。 我怎样才能做到这一点? 这是我的服务,我想将令牌发送到RegisterActivity,但不起作用

public class FirebaseInstanceIDService extends FirebaseInstanceIdService {

    @Override
    public void onTokenRefresh() {

        String token = FirebaseInstanceId.getInstance().getToken();

        Log.d("My firebase id", "Refreshed token: " + token);

        Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
        intent.putExtra("TokenValue", token);
        FirebaseInstanceIDService.this.startActivity(intent );

    }

在RegisterActivity中

 Intent intent = getIntent();
            String tokenValue = intent.getStringExtra("TokenValue");
            Toast.makeText(RegisterActivity.this,tokenValue,Toast.LENGTH_SHORT).show();

3 个答案:

答案 0 :(得分:0)

在调用startActivity之前在意图中添加标记FLAG_ACTIVITY_NEW_TASK

Intent intent = new Intent(getApplicationContext(), RegisterActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("TokenValue", token);
startActivity(intent);

答案 1 :(得分:0)

使用界面可以轻松完成。首先创建一个界面,然后从要获取文本的活动或片段中订阅该界面,然后从服务中广播数据

答案 2 :(得分:0)

尝试一下:

这是我的服务类,例如:

public class TokenService extends FirebaseInstanceIdService {
private static final String TAG = "FirebaseIDService";
public static String DeviceToc = "";
@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.e(TAG, "Refreshed token: " + refreshedToken);

    DeviceToc = refreshedToken;
    Log.e("DeviceToc",""+refreshedToken);
    sendRegistrationToServer(refreshedToken);
}

private void sendRegistrationToServer(String token) {
  //        Utils.storeUserPreferences(this, DeviceToc,token);
    SharedPreferences pref = getApplicationContext().getSharedPreferences("MyPref", 0);

    SharedPreferences.Editor editor = pref.edit();
    editor.putString("deviceToc",token); // Storing string
    editor.apply();

    Log.i("token",""+token);
    // Add custom implementation, as needed.
}

这是我的登录活动,使用诸如此类的共享首选项获取令牌

      @Override
        protected Map<String, String> getParams()
        {
            Context c=LoginActivity.this;
            SharedPreferences pref = c.getApplicationContext().getSharedPreferences("MyPref", 0);
            String device_tok = pref.getString("deviceToc", null);
            //Pass the parameters to according to the API.
            Map<String, String> params = new HashMap<String, String>();
            params.put("user_name", emailedit.getText().toString().trim());
            params.put("userDeviceToken",device_tok);
            params.put("deviceType","android");
            params.put("user_login_password", passwordedit.getText().toString().trim());
            Log.d("params",""+params);

它可以帮助您。