从资源引用字符串到接口

时间:2016-05-19 13:22:23

标签: java android retrofit

我有一个应用程序需要将订阅密钥放在请求标头中。有没有办法可以将字符串资源中的密钥引用到接口。

鉴于此代码

public interface apiService { 
    @Headers({
            "Content-Type: application/octet-stream",
            "Ocp-Apim-Subscription-Key: 194bcbe84a424c8d9c7378cc9e5fa41d"//key
    })
    @POST("vision/v1.0/analyze")
    Call<visualFeatures_Description> uploadImage(@Body RequestBody imageFile);
}

我想将存储库上传到Github并将资源的xml文件添加到.gitignore中,这样我的密钥就不可见了。

我尝试使用

getString(R.strings.key) 

在界面内部,但它表示我无法从静态上下文中引用。

3 个答案:

答案 0 :(得分:0)

你应该使用Application类。

public class AppController extends Application {

private static Context mContext;

@Override
public void onCreate() {
    super.onCreate();
    mContext = this;
}

public static Context getContext(){
    return mContext;
}
}

现在您可以像这样访问resources ..

 AppController.getContext().getResources().getString(R.string.key);

不要忘记在Manifest.xml中添加此类

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:name=".AppController"  <!--Here you can see this -->
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

答案 1 :(得分:0)

试试这个:

{
   "_index": "incident_db",
   "_type": "incidents",
   "_source": {
      "incident": {
         "name": "something",
         "severity": 3
      }
   }
}

您可以在任何地方使用它。

答案 2 :(得分:0)

您可以改为使用BuildConfig字段:

buildConfigField "String", "API_KEY", '"key"'

然后您可以使用BuildConfig.API_KEY访问任何地方(如果此字段不可用,请尝试执行“清理并重建”)

defaultConfig {
        applicationId "your app"
        minSdkVersion 21
        targetSdkVersion 30
        versionCode buildVersionCode
        versionName buildVersionName
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

        buildConfigField "String", "API_KEY", '"my_key_here"'
    }