【发布时间】:2013-05-29 15:18:27
【问题描述】:
目前我正在开发一个从服务器检索 json 的应用程序。我正在多台设备上测试该应用程序,但我只有一张 SIM 卡。因此,为了在设备上进行测试,我需要将 SIM 卡移动到该设备。如果应用无法通过 APN 联系到服务器,则不会有结果。
我所做的是将所述 json 的实例保存在资源中,并在调试模式下使用它作为结果。这样我就可以测试所有内容(除了连接/请求),而不必每次都切换 SIM 卡。
private class RequestTask extends AsyncTask< String, String, String > {
...
@Override
protected void onPostExecute( String pResult ) {
...
if ( retrieveFromRawResource( pResult ) ) {
pResult = CustomUtils.parseRawResource( getActivity().getResources(), R.raw.debugjson );
}
...
}
private boolean retrieveFromRawResource( String pResult ) {
return !isValidResult( pResult ) && CustomUtils.isDebugMode( getActivity() );
}
private boolean isValidResult( String pResult ) {
return ( pResult != null && !pResult.isEmpty() );
}
...
}
public class CustomUtils {
...
public static String parseRawResource( Resources pResources, int pResourceId ) {
StringBuilder builder = new StringBuilder();
String line;
try {
InputStream is = pResources.openRawResource( pResourceId );
BufferedReader reader = new BufferedReader( new InputStreamReader( is ) );
while ( ( line = reader.readLine() ) != null )
{
builder.append( line );
builder.append( "\n" );
}
return builder.toString();
} catch ( Exception e ) {
return null;
}
}
...
public static boolean isDebugMode( Context pContext ) {
return ( ( pContext.getApplicationInfo().flags &= ApplicationInfo.FLAG_DEBUGGABLE ) != 0 );
}
...
}
这很好用,但它的缺点是发布 APK 中存在“未使用”资源。该文件非常大,因此最好从所有版本中删除它。
不必每次都手动删除/添加这样的事情是否可行?也许使用 ant 和 Proguard 的组合?我可以在编译之前暂时删除原始 json 文件并在之后替换它,但是对该资源的引用仍然在代码中,即使它没有被调用。
【问题讨论】:
-
我有一个非常相似的情况,我想要一些预装的 JSON 用于我的 UI 的 Robotium 测试,但我不想将测试 JSON 留在发布版本中。对于仅测试代码,您可以将其包装在 if (BuildConfig.DEBUG) {} 我希望您可以为资源做类似的事情。
标签: android ant proguard android-resources