1. 程式人生 > >Android 開啟外部應用(微博/微信/QQ等)

Android 開啟外部應用(微博/微信/QQ等)

跳轉微信首頁

Intent intent = new Intent();
ComponentName cmp = new ComponentName("com.tencent.mm","com.tencent.mm.ui.LauncherUI");
intent.setAction(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setComponent(cmp);
startActivityForResult(intent, 0
);

通過以上程式碼就可跳轉到微信首頁。

錯誤處理

在跳轉微信的時候,我們還必須要考慮一個問題,那就是:

使用者可能在手機中沒有安裝微信

此時,當我們執行以上的程式碼,應用就會報class not found的錯誤。

解決方法:

在跳轉模組外加一個 try…catch 模組,捕獲異常,在catch模組中進行錯誤處理。

try {
        Intent intent = new Intent();
        ComponentName cmp = new ComponentName("com.tencent.mm","com.tencent.mm.ui.LauncherUI"
); intent.setAction(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_LAUNCHER); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setComponent(cmp); startActivityForResult(intent, 0); } catch (Exception e) { //若無法正常跳轉,在此進行錯誤處理 Toast.makeText
(MainActivity.this, "無法跳轉到微信,請檢查您是否安裝了微信!", Toast.LENGTH_SHORT).show(); }

其他外部應用

跳轉其他應用頁面,和跳轉微信首頁類似。只需將 ComponentName 中的 Package Name(包名) 和 Class Name(類名)相應的替換掉就可以了。

ComponentName("Package Name","Class Name");

常用的Package命令:

Application Package Name Class Name
新浪微博(編輯介面) com.sina.weibo com.sina.weibo.EditActivity
騰訊微博(編輯介面) com.tencent.WBlog com.tencent.WBlog.activity.MicroblogInput
微信 com.tencent.mm com.tencent.mm.ui.LauncherUI
QQ com.tencent.mobileqq com.tencent.mobileqq.activity.HomeActivity

參考文章: