废话不说,上代码:
public static boolean signApk(String sourcePath, String targetPath, String key,
String passwd, String alias) {
if (sourcePath == null || targetPath == null || passwd == null|| key == null)
return false;
File file = new File(sourcePath);
if (!file.exists())
return false;
file=new File(key);
if(!file.exists())
return false;
String cmd = "jarsigner -verbose -keystore " + key + " -signedjar " + targetPath + " " + sourcePath + " " + alias;
Process process=null;
try {
process = Runtime.getRuntime().exec(cmd);
OutputStream outputStream = process.getOutputStream();
outputStream.write(passwd.getBytes());
outputStream.close();
InputStream inputStream = process.getInputStream();
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
if(line.contains("incorrect"))
return false;
}
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
return false;
}
return true;
}
sourcePath是要签名的apk路径,targetPath是签名后生成的文件路径,key为使用的keystore路径,passwd为keystore对应的密码,alias是keystore的别名。
如果不知道怎么获取alias,可以使用下面的代码,alias可以在工程根目录下的alias.txt中查看:
public static void getAlias(String key, String passwd){
String cmd = "cmd.exe /c keytool -list -v -keystore "+key+" -storepass "+passwd+" > ./alias.txt";
try {
Process process=null;
process= Runtime.getRuntime().exec(cmd);
if (process != null) {
InputStream inputStream = process.getErrorStream();
InputStreamReader reader = new InputStreamReader(inputStream);
BufferedReader bufferedReader = new BufferedReader(reader);
String line = null;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
bufferedReader.close();
reader.close();
inputStream.close();
process.destroy();
}
} catch (IOException e) {
e.printStackTrace();
}
}
其中keytool同样是JDK下的工具,这里直接使用了,所以也需要实现配置好JAVA_HOME。