如何检查 APK 是否已签名或“调试版本"? [英] How to check if APK is signed or "debug build"?

查看:37
本文介绍了如何检查 APK 是否已签名或“调试版本"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

据我所知,在 android 中,发布版本"是签名的 APK.如何从代码检查它或者Eclipse是否有某种秘密定义?

As far as I know, in android "release build" is signed APK. How to check it from code or does Eclipse has some kinda of secret defines?

我需要它来调试从 Web 服务数据填充的 ListView 项目(不,logcat 不是一个选项).

I need this to debug populating ListView items from web service data (no, logcat not an option).

我的想法:

  • 应用程序的android:debuggable,但由于某种原因,它看起来不可靠.
  • 硬编码设备 ID 不是个好主意,因为我使用相同的设备来测试签名的 APK.
  • 在代码中的某处使用手动标志?有道理,但肯定会在某个时候忘记更改,而且所有程序员都很懒惰.
  • Application's android:debuggable, but for some reason that doesn't look reliable.
  • Hard-coding device ID isn't good idea, because I am using same device for testing signed APKs.
  • Using manual flag somewhere in code? Plausible, but gonna definitely forget to change at some time, plus all programmers are lazy.

推荐答案

有多种方法可以检查应用程序是使用调试证书还是发布证书构建的,但以下方法对我来说似乎最好.

There are different way to check if the application is build using debug or release certificate, but the following way seems best to me.

根据 Android 文档中的信息 签署您的应用程序,调试键包含以下主题专有名称:CN=Android Debug,O=Android,C=US".我们可以使用此信息来测试包是否使用调试密钥签名,而无需将调试密钥签名硬编码到我们的代码中.

According to the info in Android documentation Signing Your Application, debug key contain following subject distinguished name: "CN=Android Debug,O=Android,C=US". We can use this information to test if package is signed with debug key without hardcoding debug key signature into our code.

给定:

import android.content.pm.Signature;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

您可以通过以下方式实现 isDebuggable 方法:

You can implement an isDebuggable method this way:

private static final X500Principal DEBUG_DN = new X500Principal("CN=Android Debug,O=Android,C=US");
private boolean isDebuggable(Context ctx)
{
    boolean debuggable = false;

    try
    {
        PackageInfo pinfo = ctx.getPackageManager().getPackageInfo(ctx.getPackageName(),PackageManager.GET_SIGNATURES);
        Signature signatures[] = pinfo.signatures;

        CertificateFactory cf = CertificateFactory.getInstance("X.509");

        for ( int i = 0; i < signatures.length;i++)
        {   
            ByteArrayInputStream stream = new ByteArrayInputStream(signatures[i].toByteArray());
            X509Certificate cert = (X509Certificate) cf.generateCertificate(stream);       
            debuggable = cert.getSubjectX500Principal().equals(DEBUG_DN);
            if (debuggable)
                break;
        }
    }
    catch (NameNotFoundException e)
    {
        //debuggable variable will remain false
    }
    catch (CertificateException e)
    {
        //debuggable variable will remain false
    }
    return debuggable;
}

这篇关于如何检查 APK 是否已签名或“调试版本"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆