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

Android 在非活动类之间传递字符串,android,sharedpreferences,Android,Sharedpreferences,我有两个非活动类,我需要将一个字符串从一个类发送到另一个类,我的方法是使用共享首选项,但我无法在第二个类中获取共享字符串。第一类将在每次打开应用程序时运行,并生成令牌 头等舱: public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService { private static final String TAG = "MyFirebaseIDService"; /** * Called if Instance

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

头等舱:

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);
}
}
公共类截击{
私有静态最终字符串标记=“截击”;
私有静态截击实例=null;
公共静态最终字符串键\u TOKEN=“TOKEN”;
//截击API
公共请求队列请求队列;
SharedReferences sp2=GetSharedReferences(“PUSHToken”,Context.MODE\u PRIVATE);
String-token=sp2.getString(“PUSHToken”,“PUSHToken”);
专用截击(上下文)
{
this.token=token;
requestQueue=Volley.newRequestQueue(context.getApplicationContext());
返回;
}
公共静态同步截击输出getInstance(上下文)
{
if(null==实例)
实例=新截击(上下文);
返回实例;
}
公共静态同步截击输出getInstance()
{
if(null==实例)
{
抛出新的非法状态异常(VolleyPut.class.getSimpleName()+
未初始化,请先调用getInstance(…);
}
返回实例;
}
公共void截击(字符串域、字符串api、最终字符串finalToken、最终CustomListener侦听器){
JSONArray JSONArray=新的JSONArray();
JSONObject JSONObject=新的JSONObject();
试一试{
jsonObject.put(“令牌”,令牌);
jsonArray.put(jsonObject);
Log.i(“JsonString:,jsonObject.toString());
}捕获(例外e){
System.out.println(“错误:+e”);
}
StringRequest sr=新的StringRequest(Request.Method.PUT,域+api,
新的Response.Listener(){
@凌驾
公共void onResponse(字符串响应){
Log.e(“HttpClient”,“success!response:”+response);
if(null!=响应)
getResult(response);
返回;
}
},
新的Response.ErrorListener(){
@凌驾
公共无效onErrorResponse(截击错误){
if(null!=错误。networkResponse)
{
Log.d(标记+“:”,“错误响应代码:”+Error.networkResponse.statusCode);
//getResult(false);
}
}
})
{
@凌驾
公共映射getHeaders()引发AuthFailureError{
HashMap headers=新的HashMap();
标题。放置(“授权”,finalToken);
headers.put(“内容类型”、“应用程序/json”);
headers.put(KEY_TOKEN,TOKEN);
返回标题;
}
};
requestQueue.add(sr);
}
}

但是,我在第二个类中无法解析方法GetSharedReference时出错。解决这个问题的方法是什么?是否在非活动类之间传递字符串?

问题是FirebaseInstancedService位于类android.content.Context的内部,因此,在MyFirebaseInstancedService中,您有一个上下文,可以使用GetSharedReferences

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

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

以下是如何实施它:

请记住,如果使用此方法,必须将其放入清单中:

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

您可以创建一个全局变量,如下所示:-

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);
这将解决无法解析方法GetSharedReference的错误