在非活动类之间传递字符串

时间:2016-12-08 08:30:02

标签: android sharedpreferences

我有两个非活动类,我需要从一个类发送一个字符串到另一个类,我的方法是使用共享首选项但我不能在第二个类中获取共享字符串。每次打开应用程序时都会运行第一个类,并生成一个令牌

头等舱:

public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {

private static final String TAG = "MyFirebaseIDService";

/**
 * Called if InstanceID token is updated. This may occur if the security of
 * the previous token had been compromised. Note that this is called when the InstanceID token
 * is initially generated so this is where you would retrieve the token.
 */
// [START refresh_token]
@Override
public void onTokenRefresh() {
    // Get updated InstanceID token.
    String refreshedToken = FirebaseInstanceId.getInstance().getToken();
    Log.d(TAG, "Refreshed token: " + refreshedToken);


    sendRegistrationToServer(refreshedToken);
}
// [END refresh_token]

/**
 * Persist token to third-party servers.
 *
 * Modify this method to associate the user's FCM InstanceID token with any server-side account
 * maintained by your application.
 *
 * @param token The new token.
 */
public void sendRegistrationToServer(String token) {
    // TODO: Implement this method to send token to your app server.
    SharedPreferences sp = getSharedPreferences("PUSHToken", Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sp.edit();
    editor.putString("PUSHToken", token);
    editor.commit();

}
}

我正在尝试传递字符串令牌并存储在我的第二个非活动类中以获取我的排球请求:

public class VolleyPut {

private static final String TAG = "VolleyPut";
private static VolleyPut instance = null;
public static final String KEY_TOKEN = "token";
//for Volley API
public RequestQueue requestQueue;

SharedPreferences sp2=getSharedPreferences("PUSHToken", Context.MODE_PRIVATE);
String token = sp2.getString("PUSHToken", "");

private VolleyPut(Context context)
{

    this.token = token;
    requestQueue = Volley.newRequestQueue(context.getApplicationContext());

    return;

}

public static synchronized VolleyPut getInstance(Context context)
{
    if (null == instance)
        instance = new VolleyPut(context);

    return instance;
}

public static synchronized VolleyPut getInstance()
{
    if (null == instance)
    {
        throw new IllegalStateException(VolleyPut.class.getSimpleName() +
                " is not initialized, call getInstance(...) first");
    }
    return instance;

}

public void VolleyPUT(String domain, String api, final String finalToken, final CustomListener<String> listener){

    JSONArray jsonArray = new JSONArray();
    JSONObject jsonObject = new JSONObject();
    try{

        jsonObject.put("token", token);
        jsonArray.put(jsonObject);
        Log.i("JsonString :", jsonObject.toString());

    }catch (Exception e){
        System.out.println("Error:" + e);
    }

    StringRequest sr = new StringRequest(Request.Method.PUT, domain + api,
            new Response.Listener<String>() {
                @Override
                public void onResponse(String response) {
                    Log.e("HttpClient", "success! response: " + response);
                    if(null != response)
                        listener.getResult(response);
                    return;
                }
            },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    if (null != error.networkResponse)
                    {
                        Log.d(TAG + ": ", "Error Response code: " + error.networkResponse.statusCode);
                        //listener.getResult(false);
                    }
                }
            })
    {

        @Override
        public Map<String,String> getHeaders() throws AuthFailureError {
            HashMap<String, String> headers= new HashMap<>();
            headers.put("Authorization",finalToken);
            headers.put("Content-Type","application/json");
            headers.put(KEY_TOKEN,token);
            return headers;
        }
    };
    requestQueue.add(sr);
}
}

但是我收到错误无法在我的第二课中解决方法getsharedpreference。如何解决这个问题,无论如何都要在非活动类之间传递字符串?

2 个答案:

答案 0 :(得分:1)

问题是FirebaseInstanceIdService来自android.content.Context类,因此,在MyFirebaseInstanceIDService中你有一个Context并且可以使用getSharedPreferences。

解决方案是(修改最小代码)将上下文传递给第二个类,并使用它来获取共享首选项。

更好的解决方案(我自己的想法)是创建一个自定义应用程序,并始终将其用作所有应用程序的通用上下文。降低参数和较低的依赖性,因为您始终拥有“CustomApplication”并可以使用它。

这里有如何实现它:

https://stackoverflow.com/a/27416998/585540

请记住,如果您使用此方法,则必须将其放在Manifest中:

<application ....
        android:name="com.you.yourapp.CustomApplication"
        ......>

答案 1 :(得分:0)

您可以创建一个全局变量: -

public Context context;


public VolleyPut(Context context)
{

this.token = token;
this.context=context
requestQueue = Volley.newRequestQueue(context.getApplicationContext());

return;

}

SharedPreferences sp2=**context**.getSharedPreferences("PUSHToken", Context.MODE_PRIVATE);

这将解决无法解析方法getsharedpreference的错误