2016-12-08 114 views
0

我有兩個非活動類,我需要從一個類發送一個字符串到另一個類,我的方法是使用共享首選項,但無法在第二個類中獲取共享字符串。第一類將運行的每個應用程序打開時,將生成令牌在非活動類之間傳遞字符串

第一類:

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在我的第二課堂。如何解決這個問題,並且無論如何都要在非活動類之間傳遞字符串?

回答

1

問題是,來自類android.content.Context的FirebaseInstanceIdService innherits如此,在MyFirebaseInstanceIDService中你有一個Context並且可以使用getSharedPreferences。

解決方法是(修改最小代碼)將上下文傳遞給第二個類,並使用它獲取共享首選項。

更好的解決方案(我自己的想法)是創建一個自定義的應用程序,並將其始終用作所有應用程序的常見上下文。較低的參數和較低的依賴性,因爲您始終擁有「CustomApplication」並可以使用它。

這裏如何實現它:

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

記住,如果你使用這種方法,必須把它放在清單:

<application .... 
     android:name="com.you.yourapp.CustomApplication" 
     ......> 
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