一般假设
所以我发现了很多关于使用 proguard 从代码中剥离日志语句的信息。基本上所有人都说 -assumenosideeffects 与使用 ${sdk.dir}/tools/proguard/proguard-android-optimize.txt 配置一起可以解决问题。我的理解是得到等于做一些的字节码
if(Consts.DEBUG) Log.d("","");
又名我假设从我的 apk 中消除了对 doSomeExpensiveStuff() 的调用:
android.util.Log.d("Hello","World"+(new Foo().doSomeExpensiveStuff()));
我的代码
public class MainActivity extends Activity {
private class Slooow {
@Override
public String toString() {
// being slow
try {
Thread.sleep(5000);
} catch(InterruptedException e) {
}
return "bla";
}
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("tag", "onCreate: " + (new Slooow().toString()));
}
}
proguard-project.txt:
-repackageclasses ''
-optimizationpasses 5
-dontobfuscate
-assumenosideeffects class android.util.Log { public * ; }
反编译的dex文件
.method public onCreate(Landroid/os/Bundle;)V
.limit registers 5
; this: v3 (Lcom/example/test/MainActivity;)
; parameter[0] : v4 (Landroid/os/Bundle;)
.line 18
invoke-super {v3,v4},android/app/Activity/onCreate ; onCreate(Landroid/os/Bundle;)V
.line 19
const/high16 v0,32515
invoke-virtual {v3,v0},com/example/test/MainActivity/setContentView ; setContentView(I)V
.line 20
new-instance v0,java/lang/StringBuilder
const-string v1,"onCreate: "
invoke-direct {v0,v1},java/lang/StringBuilder/<init> ; <init>(Ljava/lang/String;)V
new-instance v1,com/example/test/MainActivity$Slooow
const/4 v2,0
invoke-direct {v1,v2},com/example/test/MainActivity$Slooow/<init> ; <init>(B)V
invoke-virtual {v1},com/example/test/MainActivity$Slooow/toString ; toString()Ljava/lang/String;
move-result-object v1
invoke-virtual {v0,v1},java/lang/StringBuilder/append ; append(Ljava/lang/String;)Ljava/lang/StringBuilder;
.line 21
return-void
.end method
问题
现在,如果我将它部署到我的设备上,我不会得到任何日志输出,但仍然是 5s 睡眠(或任何其他不应该打扰我的用户的代码延迟或崩溃)。我究竟做错了什么?
进一步调查
Log.d("t", "h" + "w"); // would get stripped just fine.
if(DEBUG)
Log.d("t", "h: " + (new Slooow().toString())); // would get optimized away, too.
Log.d("t", "h" + bundle.toString()); // has just the same problem as described above.