Reputation: 891
I want open chat page of an specific telegram contact for example @userTest by android intent.
this is snippet of open telegram by intent:
Intent myIntent = new Intent(Intent.ACTION_SEND);
myIntent.setType("text/plain");
myIntent.setPackage("org.telegram.messenger");
activity.startActivity(myIntent);
but now how open chat page of an specific user?
Upvotes: 6
Views: 5105
Reputation: 265
This is a simple solution, but it works flawlessly.
try {
Intent telegram = new Intent(Intent.ACTION_VIEW, Uri.parse("https://t.me/UsernameOrId"));
telegram.setPackage("org.telegram.messenger");
startActivity(telegram);
} catch (Exception e) {
Toast.makeText(this, "Telegram app is not installed", Toast.LENGTH_LONG).show();
}
Upvotes: 3
Reputation: 1413
This one worked for me:
try {
Intent telegram = new Intent(Intent.ACTION_VIEW, Uri.parse("https://t.me/USER_NAME"));
telegram.setPackage("org.telegram.messenger");
startActivity(telegram);
}catch (Exception e)
{
Toast.makeText(getContext(), "Telegram app is not installed", Toast.LENGTH_LONG).show();
}
Tip: You can get USER_NAME by click on you telegram profile option you will get option of username in Account session --> if username is none create unique username and put here its work for me
Upvotes: 0
Reputation: 17774
How it works:
It builds list of browsers to ignore them if telegram client is installed.
If there is one and only one client(goodresolvers == 1) then it's opened.
If there are no good clients (goodresolvers == 0) it fall backs to default intent handler.
You can improve this code further if you implement a dialog with custom chooser who only allows selecting "good" clients in case user have several Telegram clients installed.
public static void openTelegram(Activity activity, String userName) {
Intent general = new Intent(Intent.ACTION_VIEW, Uri.parse("https://t.com/" + userName));
HashSet<String> generalResolvers = new HashSet<>();
List<ResolveInfo> generalResolveInfo = activity.getPackageManager().queryIntentActivities(general, 0);
for (ResolveInfo info : generalResolveInfo) {
if (info.activityInfo.packageName != null) {
generalResolvers.add(info.activityInfo.packageName);
}
}
Intent telegram = new Intent(Intent.ACTION_VIEW, Uri.parse("https://t.me/" + userName));
int goodResolver = 0;
// gets the list of intents that can be loaded.
List<ResolveInfo> resInfo = activity.getPackageManager().queryIntentActivities(telegram, 0);
if (!resInfo.isEmpty()) {
for (ResolveInfo info : resInfo) {
if (info.activityInfo.packageName != null && !generalResolvers.contains(info.activityInfo.packageName)) {
goodResolver++;
telegram.setPackage(info.activityInfo.packageName);
}
}
}
//TODO: if there are several good resolvers create custom chooser
if (goodResolver != 1) {
telegram.setPackage(null);
}
if (telegram.resolveActivity(activity.getPackageManager()) != null) {
activity.startActivity(telegram);
}
}
usage: openTelegram(activity, "userTest");
Upvotes: 3