上面说的反编译要各种解包,打包,签名,相对也比较繁琐,然后我们可以发现,apk其实都是一个压缩包,我们直接在这个压缩包里添加对应的文件作为渠道号标记是不是又能省去上面繁琐的步奏呢?!打开一个APK文件之后你会看到META-INF这个文件夹!
public
static
void
addUmengChannel
(
String
filepath
,
String
channel
)
{
String
channel_title
=
"umengchannel_"
;
if
(
filepath
.
substring
(
filepath
.
lastIndexOf
(
"."
)
+
1
).
toLowerCase
().
equals
(
"apk"
))
{
String
path2
=
""
;
if
(
filepath
.
lastIndexOf
(
File
.
separator
)
>=
0
)
{
path2
=
filepath
.
substring
(
0
,
filepath
.
lastIndexOf
(
File
.
separator
)
+
1
);
//得到父路径
}
if
(
path2
.
length
()
!=
0
)
{
File
s
=
new
File
(
filepath
);
//原始的apk
File
t
=
new
File
(
filepath
.
substring
(
0
,
filepath
.
lastIndexOf
(
"."
))
+
"_"
+
channel
+
".apk"
);
//目标apk
if
(
!
t
.
exists
())
{
//不存在就创建
try
{
t
.
createNewFile
();
}
catch
(
IOException
var12
)
{
var12
.
printStackTrace
();
}
}
Utils
.
fileChannelCopy
(
s
,
t
);
//拷贝原始apk到目标apk
File
addFile
=
new
File
(
path2
+
channel_title
+
channel
);
//需要添加的渠道文件
if
(
!
addFile
.
exists
())
{
try
{
addFile
.
createNewFile
();
}
catch
(
IOException
var11
)
{
var11
.
printStackTrace
();
}
}
try
{
Utils
.
addFileToExistingZip
(
t
,
addFile
);
//将新加的渠道文件添加到目标apk文件中
addFile
.
delete
();
}
catch
(
IOException
var10
)
{
var10
.
printStackTrace
();
}
}
}
}
public
static
void
addFileToExistingZip
(
File
zipFile
,
File
file
)
throws
IOException
{
File
tempFile
=
File
.
createTempFile
(
zipFile
.
getName
(),
(
String
)
null
);
tempFile
.
delete
();
boolean
renameOk
=
zipFile
.
renameTo
(
tempFile
);
//拷贝
if
(
!
renameOk
)
{
throw
new
RuntimeException
(
"could not rename the file "
+
zipFile
.
getAbsolutePath
()
+
" to "
+
tempFile
.
getAbsolutePath
());
}
else
{
byte
[]
buf
=
new
byte
[
1024
];
ZipInputStream
zin
=
new
ZipInputStream
(
new
FileInputStream
(
tempFile
));
ZipOutputStream
out
=
new
ZipOutputStream
(
new
FileOutputStream
(
zipFile
));
for
(
ZipEntry
entry
=
zin
.
getNextEntry
();
entry
!=
null
;
entry
=
zin
.
getNextEntry
())
{
String
in
=
entry
.
getName
();
if
(
in
.
contains
(
"umengchannel"
))
{
//如果有重复的就不复制回去了!
continue
;
}
out
.
putNextEntry
(
new
ZipEntry
(
in
));
int
len1
;
while
((
len1
=
zin
.
read
(
buf
))
>
0
)
{
out
.
write
(
buf
,
0
,
len1
);
}
}
zin
.
close
();
FileInputStream
in1
=
new
FileInputStream
(
file
);
out
.
putNextEntry
(
new
ZipEntry
(
"META-INF/"
+
file
.
getName
()));
//创建对应的渠道文件
int
len2
;
while
((
len2
=
in1
.
read
(
buf
))
>
0
)
{
out
.
write
(
buf
,
0
,
len2
);
}
out
.
closeEntry
();
in1
.
close
();
out
.
close
();
tempFile
.
delete
();
}
}