需求:App内调起社交平台的“官方账号页面”,如果用户安装有对应社交App,直接调起;否则则通过浏览器方式打开网页。
Facebook,Twitter,Youtube,Instagram
/**
* 跳转 Facebook
* @param context 上下文
* @return 跳转 intent
*/
public static Intent newFacebookProfileIntent(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
if (versionCode >= 3002850) { // newer versions of fb app
intent.setData(Uri.parse("fb://facewebmodal/f?href=https://www.facebook.com/用户名"));
} else { // older versions of fb app
intent.setData(Uri.parse("fb://page/用户名"));
}
// 部分机型无法调起,facebook,再次判断,失败则浏览器方式显示
if (intent.resolveActivity(context.getPackageManager()) != null) {
return intent;
} else {
intent.setData(Uri.parse("https://www.facebook.com/用户名"));
return intent; // normal web url
}
} catch (PackageManager.NameNotFoundException e) {
intent.setData(Uri.parse("https://www.facebook.com/用户名"));
return intent; // normal web url
}
}
/**
* 跳转 Twitter
* @param context 上下文
* @return 跳转 intent
*/
public static Intent newTwitterProfileIntent(Context context) {
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
if (context.getPackageManager().getPackageInfo("com.twitter.android", 0) != null) {
// 推特用户id(纯数字),id获取方法:(http://gettwitterid.com/)
intent.setData(Uri.parse("twitter://user?user_id=推特用户id"));
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
return intent;
}
} catch (PackageManager.NameNotFoundException ignored) {
}
intent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.twitter.com/用户名"));
return intent;
}
/**
* 跳转 Youtube
* @param context 上下文
* @return 跳转 intent
*/
public static Intent newYoutubeProfileIntent(Context context) {
Intent intent = new Intent(Intent.ACTION_VIEW);
// 浏览器地址
String URL_YOUTUBE = "https://www.youtube.com/channel/用户channel ID";
// app 内Action
String URL_YOUTUBE_INAPP = "vnd.youtube.com/channel/用户channel ID";
intent.setData(Uri.parse(URL_YOUTUBE_INAPP));
if (intent.resolveActivity(context.getPackageManager()) != null) {
return intent;
} else {
intent.setData(Uri.parse(URL_YOUTUBE));
return intent;
}
}
/**
* Instagram
* @param context 上下文
* @return intent
*/
public static Intent newInstagramProfileIntent(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent intent = new Intent(Intent.ACTION_VIEW);
try {
if (packageManager.getPackageInfo("com.instagram.android", 0) != null) {
intent.setData(Uri.parse("http://instagram.com/_u/用户名"));
intent.setPackage("com.instagram.android");
return intent;
}
} catch (Exception ignored) {
}
intent.setData(Uri.parse("http://www.instagram.com/用户名"));
return intent;
}
使用
Intent intent = newFacebookProfileIntent(mContext);
// 判断是否可用,防止连浏览器都没有的用户触发崩溃
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
网友评论