做launcher時,使用者點選apk的圖示就對應着需要打開這個apk,有兩種方式可以啟動這個apk
第一種:知道apk的包名和它的主activity
[java] view
plaincopyprint?
// 幫助
private componentname help_set;
private final static string help_set_pack = "cn.abc.help";
private final static string help_set_name = "cn.abc.help.mainactivity";
/**
* 啟動一個app
* com -- componentname 對象,包含apk的包名和主activity名
* param -- 需要傳給apk的參數
*/
private void startapp(componentname com, string param) {
if (com != null) {
packageinfo packageinfo;
try {
packageinfo = getpackagemanager().getpackageinfo(com.getpackagename(), 0);
} catch (namenotfoundexception e) {
packageinfo = null;
toast.maketext(this, "沒有安裝", toast.length_short).show();
e.printstacktrace();
}
intent intent = new intent();
intent.setflags(intent.flag_activity_new_task);
intent.setcomponent(com);
if (param != null) {
bundle bundle = new bundle(); // 建立bundle對象
bundle.putstring("flag", param); // 裝入資料
intent.putextras(bundle); // 把bundle塞入intent裡面
}
startactivity(intent);
} catch (exception e) {
toast.maketext(this, "啟動異常", toast.length_short).show();
}
}
第二種:隻知道apk的包名,這種方法最常用了,畢竟要啟動的apk不一定是我們自己寫的。
/*
public void startapp(string apppackagename){
try{
intent intent = this.getpackagemanager().getlaunchintentforpackage(apppackagename);
startactivity(intent);
}catch(exception e){
toast.maketext(this, "沒有安裝", toast.length_long).show();
綜合起來比較第二種方法的代碼要簡潔得多,比較實用!