I try the following code to send messages to line app. It works; however, before I send message,it will move to the line friends page and I have to choose friends whom I want to send the messages to. How could I modify the code that I could choose friends at code instead of choosing friends manually.
public class MainActivity extends AppCompatActivity {
static final int REQUEST_ACTION_PICK = 1;
public static final String PACKAGE_NAME = "jp.naver.line.android";
public static final String CLASS_NAME = "jp.naver.line.android.activity.selectchat.SelectChatActivity";
private List<ApplicationInfo> m_appList;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendTextHandler(this);
}
public void sendTextHandler(MainActivity view) {
String sendText = ((TextView)findViewById(R.id.send_text)).getText().toString();
if(checkLineInstalled()){
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setClassName(PACKAGE_NAME, CLASS_NAME);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, sendText);
startActivity(intent);
}else{
Toast toast = Toast.makeText(this, "LINEがインストールされていません", Toast.LENGTH_SHORT);
toast.show();
}
}
private boolean checkLineInstalled(){
PackageManager pm = getPackageManager();
m_appList = pm.getInstalledApplications(0);
boolean lineInstallFlag = false;
for (ApplicationInfo ai : m_appList) {
if(ai.packageName.equals(PACKAGE_NAME)){
lineInstallFlag = true;
break;
}
}
return lineInstallFlag;
}
}
The code is from https://gist.github.com/ekos/3993270.
If you want to be able to open a specific user based on the ID you can do the following:
String userId = findUserId();
String sendText = "line://ti/p/~" + userId;
Intent intent = null;
try {
intent = Intent.parseUri(sendText, Intent.URI_INTENT_SCHEME);
} catch (URISyntaxException e) {
e.printStackTrace();
}
startActivity(intent);
If you want to make a message and then be able to choose who to send it to you can use the following:
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("line://msg/text/" + getMessage()));
startActivity(intent);
I start an application with this code:
Intent hasApp = getPackageManager().getLaunchIntentForPackage("appName.app");
Intent intent = new Intent(Intent.ACTION_VIEW);
dataId = response.getdataId();
intent.setData(Uri.parse("appName:?pid=" + dataId + "&action=returntoapp"));
startActivityForResult(intent, Globals.DATA_REQUEST_CODE);
And i close the opened application with this code:
setResult(Activity.RESULT_OK);
finish();
But when the first app called the onActivityResult() method I got the same requestCode, but the intent is null, and the resultCode is ACTIVITY_CANCELED.
I don't understand why.
Try this
String packageName = "com.example.app"
public static boolean openApp(Context context, String packageName) {
PackageManager manager = context.getPackageManager();
try {
Intent i = manager.getLaunchIntentForPackage(packageName);
if (i == null) {
return false;
}
i.addCategory(Intent.CATEGORY_LAUNCHER);
context.startActivity(i);
return true;
} catch (Exception e) {
return false;
}
}
I am Unable to implement mailto link functionality in the custom webview given below. Pls Help me mix these two codes I Am relatively new to android. I don't know how to implement the mailto Code.
Solution on stackoverflow:
Mailto Code
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.startsWith("mailto:")){
MailTo mt = MailTo.parse(url);
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL, new String[]{mt.getTo()});
i.putExtra(Intent.EXTRA_SUBJECT, mt.getSubject());
i.putExtra(Intent.EXTRA_CC, mt.getCc());
i.putExtra(Intent.EXTRA_TEXT, mt.getBody());
mContext.startActivity(i);
view.reload();
return true;
}
view.loadUrl(url);
return true;
}
My code
public class MainActivity extends Activity implements OnClickListener {
final Context context = this;
private WebView webView;
private ImageButton btnrefresh;
private TextView txtrefresh;
private Menu optionsMenu;
#SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//define button
btnrefresh = (ImageButton) findViewById(R.id.imageButton1);
btnrefresh.setOnClickListener(this);
btnrefresh.setVisibility(View.GONE);
//define textView
txtrefresh = (TextView)findViewById((R.id.textView1));
txtrefresh.setVisibility(View.GONE);
if(isConnected())
{
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
// webView.getSettings().setPluginState(PluginState.ON);
webView.setWebViewClient(new WebViewClient());
initWebView(webView);
webView.loadUrl("xxxxx");
}
else
{
RelativeLayout rel = (RelativeLayout)findViewById(R.id.relativelayout1);
rel.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
refresh();
}
});
btnrefresh.setVisibility(View.VISIBLE);
txtrefresh.setVisibility(View.VISIBLE);
Toast.makeText(getBaseContext(), "No Internet Connection !!", Toast.LENGTH_SHORT).show();
}
}
public boolean onCreateOptionsMenu(Menu menu) {
this.optionsMenu = menu;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.airport_menuRefresh:
webView.reload();
Toast.makeText(getBaseContext(), "Refeshing...", Toast.LENGTH_SHORT).show();
// Complete with your code
return true;
case R.id.goBack:
if(webView.canGoBack()) {
webView.goBack();
}
return true;
case R.id.goForward:
if(webView.canGoForward()) {
webView.goForward();
}
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void refresh()
{
if (isConnected()) {
btnrefresh.setVisibility(View.GONE);
txtrefresh.setVisibility(View.GONE);
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new WebViewClient());
initWebView(webView);
webView.loadUrl("xxxxxx");
Toast.makeText(getBaseContext(), "Connected !!", Toast.LENGTH_LONG).show();
Toast.makeText(getBaseContext(), "Loading....", Toast.LENGTH_SHORT).show();
Toast.makeText(getBaseContext(), "Please wait....", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getBaseContext(), "No Internet Connection !!", Toast.LENGTH_SHORT).show();
}
}
public boolean isConnected(){
ConnectivityManager connMgr = (ConnectivityManager) getSystemService(Activity.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.isConnected())
{
return true;
}
else
return false;
}
public void wifi()
{
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifi.setWifiEnabled(true);
}
public void alertwifi()
{
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
// set title
alertDialogBuilder.setTitle("NO Internet Connection!!");
// set dialog message
alertDialogBuilder
.setMessage("Click below to turn on Wifi or Enable Data pack")
.setCancelable(false)
.setPositiveButton("Wifi",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
wifi();
}
})
.setNeutralButton("GPRS",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
datapack();
}
})
.setNegativeButton("Back",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
public void datapack()
{
try
{
ConnectivityManager dataManager;
dataManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
Method dataMtd = ConnectivityManager.class.getDeclaredMethod("setMobileDataEnabled", boolean.class);
dataMtd.setAccessible(true);
dataMtd.invoke(dataManager, true);
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_BACK)) {
AlertDialog.Builder alertbox = new AlertDialog.Builder(MainActivity.this);
alertbox.setTitle("Do You Want To Exit ?");
alertbox.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// finish used for destroyed activity
exit();
}
});
alertbox.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface arg0, int arg1) {
// Nothing will be happened when clicked on no button
// of Dialog
}
});
alertbox.show();
}
return super.onKeyDown(keyCode, event);
}
public void exit()
{
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
public void onClick(View v)
{
//refresh ImageButton function
if (v == btnrefresh)
{
refresh();
}
}
private final static Object methodInvoke(Object obj, String method, Class<?>[] parameterTypes, Object[] args) {
try {
Method m = obj.getClass().getMethod(method, new Class[] { boolean.class });
m.invoke(obj, args);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
private void initWebView(WebView webView) {
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccess(true);
settings.setDomStorageEnabled(true);
settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
settings.setLoadWithOverviewMode(true);
settings.setUseWideViewPort(true);
settings.setSupportZoom(true);
// settings.setPluginsEnabled(true);
methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
// settings.setPluginState(PluginState.ON);
methodInvoke(settings, "setPluginState", new Class[] { PluginState.class }, new Object[] { PluginState.ON });
// settings.setPluginsEnabled(true);
methodInvoke(settings, "setPluginsEnabled", new Class[] { boolean.class }, new Object[] { true });
// settings.setAllowUniversalAccessFromFileURLs(true);
methodInvoke(settings, "setAllowUniversalAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true });
// settings.setAllowFileAccessFromFileURLs(true);
methodInvoke(settings, "setAllowFileAccessFromFileURLs", new Class[] { boolean.class }, new Object[] { true });
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.clearHistory();
webView.clearFormData();
webView.clearCache(true);
webView.setWebChromeClient(new MyWebChromeClient());
// webView.setDownloadListener(downloadListener);
}
UploadHandler mUploadHandler;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == Controller.FILE_SELECTED) {
// Chose a file from the file picker.
if (mUploadHandler != null) {
mUploadHandler.onResult(resultCode, intent);
}
}
super.onActivityResult(requestCode, resultCode, intent);
}
#SuppressLint("NewApi")
class MyWebChromeClient extends WebChromeClient {
public MyWebChromeClient() {
}
#SuppressLint("NewApi")
private String getTitleFromUrl(String url) {
String title = url;
try {
URL urlObj = new URL(url);
String host = urlObj.getHost();
if (host != null && !host.isEmpty()) {
return urlObj.getProtocol() + "://" + host;
}
if (url.startsWith("file:")) {
String fileName = urlObj.getFile();
if (fileName != null && !fileName.isEmpty()) {
return fileName;
}
}
} catch (Exception e) {
// ignore
}
return title;
}
#Override
public boolean onJsAlert(WebView view, String url, String message, final JsResult result) {
String newTitle = getTitleFromUrl(url);
new AlertDialog.Builder(MainActivity.this).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
}).setCancelable(false).create().show();
return true;
// return super.onJsAlert(view, url, message, result);
}
#Override
public boolean onJsConfirm(WebView view, String url, String message, final JsResult result) {
String newTitle = getTitleFromUrl(url);
new AlertDialog.Builder(MainActivity.this).setTitle(newTitle).setMessage(message).setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
result.confirm();
}
}).setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
result.cancel();
}
}).setCancelable(false).create().show();
return true;
// return super.onJsConfirm(view, url, message, result);
}
// Android 2.x
public void openFileChooser(ValueCallback<Uri> uploadMsg) {
openFileChooser(uploadMsg, "");
}
// Android 3.0
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
openFileChooser(uploadMsg, "", "filesystem");
}
// Android 4.1
public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
mUploadHandler = new UploadHandler(new Controller());
mUploadHandler.openFileChooser(uploadMsg, acceptType, capture);
}
};
class Controller {
final static int FILE_SELECTED = 4;
Activity getActivity() {
return MainActivity.this;
}
}
class UploadHandler {
/*
* The Object used to inform the WebView of the file to upload.
*/
private ValueCallback<Uri> mUploadMessage;
private String mCameraFilePath;
private boolean mHandled;
private boolean mCaughtActivityNotFoundException;
private Controller mController;
public UploadHandler(Controller controller) {
mController = controller;
}
String getFilePath() {
return mCameraFilePath;
}
boolean handled() {
return mHandled;
}
void onResult(int resultCode, Intent intent) {
if (resultCode == Activity.RESULT_CANCELED && mCaughtActivityNotFoundException) {
// Couldn't resolve an activity, we are going to try again so skip
// this result.
mCaughtActivityNotFoundException = false;
return;
}
Uri result = intent == null || resultCode != Activity.RESULT_OK ? null
: intent.getData();
// As we ask the camera to save the result of the user taking
// a picture, the camera application does not return anything other
// than RESULT_OK. So we need to check whether the file we expected
// was written to disk in the in the case that we
// did not get an intent returned but did get a RESULT_OK. If it was,
// we assume that this result has came back from the camera.
if (result == null && intent == null && resultCode == Activity.RESULT_OK) {
File cameraFile = new File(mCameraFilePath);
if (cameraFile.exists()) {
result = Uri.fromFile(cameraFile);
// Broadcast to the media scanner that we have a new photo
// so it will be added into the gallery for the user.
mController.getActivity().sendBroadcast(
new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, result));
}
}
mUploadMessage.onReceiveValue(result);
mHandled = true;
mCaughtActivityNotFoundException = false;
}
void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
final String imageMimeType = "image/*";
final String videoMimeType = "video/*";
final String audioMimeType = "audio/*";
final String mediaSourceKey = "capture";
final String mediaSourceValueCamera = "camera";
final String mediaSourceValueFileSystem = "filesystem";
final String mediaSourceValueCamcorder = "camcorder";
final String mediaSourceValueMicrophone = "microphone";
// According to the spec, media source can be 'filesystem' or 'camera' or 'camcorder'
// or 'microphone' and the default value should be 'filesystem'.
String mediaSource = mediaSourceValueFileSystem;
if (mUploadMessage != null) {
// Already a file picker operation in progress.
return;
}
mUploadMessage = uploadMsg;
// Parse the accept type.
String params[] = acceptType.split(";");
String mimeType = params[0];
if (capture.length() > 0) {
mediaSource = capture;
}
if (capture.equals(mediaSourceValueFileSystem)) {
// To maintain backwards compatibility with the previous implementation
// of the media capture API, if the value of the 'capture' attribute is
// "filesystem", we should examine the accept-type for a MIME type that
// may specify a different capture value.
for (String p : params) {
String[] keyValue = p.split("=");
if (keyValue.length == 2) {
// Process key=value parameters.
if (mediaSourceKey.equals(keyValue[0])) {
mediaSource = keyValue[1];
}
}
}
}
//Ensure it is not still set from a previous upload.
mCameraFilePath = null;
if (mimeType.equals(imageMimeType)) {
if (mediaSource.equals(mediaSourceValueCamera)) {
// Specified 'image/*' and requested the camera, so go ahead and launch the
// camera directly.
startActivity(createCameraIntent());
return;
} else {
// Specified just 'image/*', capture=filesystem, or an invalid capture parameter.
// In all these cases we show a traditional picker filetered on accept type
// so launch an intent for both the Camera and image/* OPENABLE.
Intent chooser = createChooserIntent(createCameraIntent());
chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(imageMimeType));
startActivity(chooser);
return;
}
} else if (mimeType.equals(videoMimeType)) {
if (mediaSource.equals(mediaSourceValueCamcorder)) {
// Specified 'video/*' and requested the camcorder, so go ahead and launch the
// camcorder directly.
startActivity(createCamcorderIntent());
return;
} else {
// Specified just 'video/*', capture=filesystem or an invalid capture parameter.
// In all these cases we show an intent for the traditional file picker, filtered
// on accept type so launch an intent for both camcorder and video/* OPENABLE.
Intent chooser = createChooserIntent(createCamcorderIntent());
chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(videoMimeType));
startActivity(chooser);
return;
}
} else if (mimeType.equals(audioMimeType)) {
if (mediaSource.equals(mediaSourceValueMicrophone)) {
// Specified 'audio/*' and requested microphone, so go ahead and launch the sound
// recorder.
startActivity(createSoundRecorderIntent());
return;
} else {
// Specified just 'audio/*', capture=filesystem of an invalid capture parameter.
// In all these cases so go ahead and launch an intent for both the sound
// recorder and audio/* OPENABLE.
Intent chooser = createChooserIntent(createSoundRecorderIntent());
chooser.putExtra(Intent.EXTRA_INTENT, createOpenableIntent(audioMimeType));
startActivity(chooser);
return;
}
}
// No special handling based on the accept type was necessary, so trigger the default
// file upload chooser.
startActivity(createDefaultOpenableIntent());
}
private void startActivity(Intent intent) {
try {
mController.getActivity().startActivityForResult(intent, Controller.FILE_SELECTED);
} catch (ActivityNotFoundException e) {
// No installed app was able to handle the intent that
// we sent, so fallback to the default file upload control.
try {
mCaughtActivityNotFoundException = true;
mController.getActivity().startActivityForResult(createDefaultOpenableIntent(),
Controller.FILE_SELECTED);
} catch (ActivityNotFoundException e2) {
// Nothing can return us a file, so file upload is effectively disabled.
Toast.makeText(mController.getActivity(), R.string.uploads_disabled,
Toast.LENGTH_LONG).show();
}
}
}
private Intent createDefaultOpenableIntent() {
// Create and return a chooser with the default OPENABLE
// actions including the camera, camcorder and sound
// recorder where available.
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType("*/*");
Intent chooser = createChooserIntent(createCameraIntent(), createCamcorderIntent(),
createSoundRecorderIntent());
chooser.putExtra(Intent.EXTRA_INTENT, i);
return chooser;
}
private Intent createChooserIntent(Intent... intents) {
Intent chooser = new Intent(Intent.ACTION_CHOOSER);
chooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, intents);
chooser.putExtra(Intent.EXTRA_TITLE,
mController.getActivity().getResources()
.getString(R.string.choose_upload));
return chooser;
}
private Intent createOpenableIntent(String type) {
Intent i = new Intent(Intent.ACTION_GET_CONTENT);
i.addCategory(Intent.CATEGORY_OPENABLE);
i.setType(type);
return i;
}
private Intent createCameraIntent() {
Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File externalDataDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DCIM);
File cameraDataDir = new File(externalDataDir.getAbsolutePath() +
File.separator + "browser-photos");
cameraDataDir.mkdirs();
mCameraFilePath = cameraDataDir.getAbsolutePath() + File.separator +
System.currentTimeMillis() + ".jpg";
cameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(new File(mCameraFilePath)));
return cameraIntent;
}
private Intent createCamcorderIntent() {
return new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
}
private Intent createSoundRecorderIntent() {
return new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
}
}
}
enter code here
I think webView.setWebViewClient(new WebViewClient()); this should be something like this :
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
initiateCall(url);
return true;
}
if (url.startsWith("mailto:")) {
sendEmail(url.substring(7));
return true;
}
return false;
}
sendMail will be :
private void sendEmail(String add) {
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL, new String[] { add });
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(WebViewActivity.this,
"There are no email clients installed.", Toast.LENGTH_SHORT)
.show();
}
}
I don't know about your case, but this is working for me.
private class MyWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Uri uri;
try {
uri = Uri.parse(url);
} catch (NullPointerException e) {
// let Android deal with this
return true;
}
String host = uri.getHost(); // Host is null when user clicked on email, phone number, ...
if (host != null && host.equals("stackoverflow.com")) {
// This is my web site, so do not override; let my WebView load the page
return false;
}
else {
// Otherwise, the link is not for a page on my site, so launch another Activity that handles URLs or anything else (email, phone number, ...)
// Always do this, because WebView is poor in security terms
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(intent);
return true;
}
}
And assign it
webView.setWebChromeClient(new MyWebChromeClient());
I have a button that shares the link to my app;
but this button shows skype, gmail, whatsapp...
how can I only show whatsapp for example? what can I do?
Plus when sending a mail I need to choose only gmail and hotmail for example how to do that?
I mean I know how to choose an app such as whatsapp:
Sending message through WhatsApp
but how can I choose several apps..
thanks.
Edit
Does someone have a tutorial on how to create your own share chooser? thanks.
Create your own chooser and use the following codes:
public void share_on_gmail()
{
Intent sharingIntent = is_intent_available("com.google.android.gm",
"com.google.android.gm.ComposeActivityGmail", "Gmail");
send_mail(sharingIntent);
}
public void share_on_yahoo()
{
Intent sharingIntent = is_intent_available("com.android.email",
"com.android.email.activity.MessageCompose", "Email");
send_mail(sharingIntent);
}
public void share_on_facebook()
{
Intent sharingIntent = is_intent_available("com.facebook.katana",
"com.facebook.katana.ShareLinkActivity", "Facebook");
}
public void share_on_twitter()
{
Intent sharingIntent = is_intent_available("com.twitter.android",
"com.twitter.android.PostActivity", "Twitter");
if (sharingIntent != null)
{
String subject = ((XmlNewsDetailsParser)xmlParser).subject;
String body = ((XmlNewsDetailsParser)xmlParser).body;
File mFile = savebitmap(((Picture)itemsAdapter.getItem(0)).image.bitmap);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mFile));
sharingIntent.putExtra(Intent.EXTRA_TEXT, "القارئ العربي" + "\n\n" + subject + "\n\n" + Html.fromHtml(body));
startActivity(sharingIntent);
}
}
public Intent is_intent_available(final String className, String activityName, String appName)
{
Intent I = new Intent(android.content.Intent.ACTION_SEND);
if (!activityName.equals(""))
{
I.setClassName(className, activityName);
}
else
{
I.setPackage(className);
}
PackageManager packageManager = getPackageManager();
List list = packageManager.queryIntentActivities(I, PackageManager.MATCH_DEFAULT_ONLY);
if (list==null || list.size() == 0)
{
AlertDialog ad = new AlertDialog.Builder(this).create();
ad.setMessage("Please install the " + appName + " app to share news with your friends.");
ad.setButton2("Later", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
ad.setButton("Install Now", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent marketIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("market://search?q=" + className));
startActivity(marketIntent);
}
});
ad.show();
return null;
}
return I;
}
public void send_mail(Intent sharingIntent)
{
if (sharingIntent == null) return;
String subject = ((XmlNewsDetailsParser)xmlParser).subject;
String body = ((XmlNewsDetailsParser)xmlParser).body;
File mFile = savebitmap(((Picture)itemsAdapter.getItem(0)).image.bitmap);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_SUBJECT, subject + "القارئ العربي - ");
sharingIntent.putExtra(Intent.EXTRA_TEXT, Html.fromHtml(body));
sharingIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(mFile));
startActivity(sharingIntent);
}
I have the class name and the activity name for a couple of more applications. I can provide it. Try those and I will modify the answer.
I have been struggling to send text from my app to Twitter.
The code below works to bring up a list of apps such as Bluetooth, Gmail, Facebook and Twitter, but when I select Twitter it doesn't prefill the text as I would have expected.
I know that there are issues around doing this with Facebook, but I must be doing something wrong for it to not be working with Twitter.
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Example Text");
startActivity(Intent.createChooser(intent, "Share Text"));
I'm using this snippet on my code:
private void shareTwitter(String message) {
Intent tweetIntent = new Intent(Intent.ACTION_SEND);
tweetIntent.putExtra(Intent.EXTRA_TEXT, "This is a Test.");
tweetIntent.setType("text/plain");
PackageManager packManager = getPackageManager();
List<ResolveInfo> resolvedInfoList = packManager.queryIntentActivities(tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);
boolean resolved = false;
for (ResolveInfo resolveInfo : resolvedInfoList) {
if (resolveInfo.activityInfo.packageName.startsWith("com.twitter.android")) {
tweetIntent.setClassName(
resolveInfo.activityInfo.packageName,
resolveInfo.activityInfo.name);
resolved = true;
break;
}
}
if (resolved) {
startActivity(tweetIntent);
} else {
Intent i = new Intent();
i.putExtra(Intent.EXTRA_TEXT, message);
i.setAction(Intent.ACTION_VIEW);
i.setData(Uri.parse("https://twitter.com/intent/tweet?text=" + urlEncode(message)));
startActivity(i);
Toast.makeText(this, "Twitter app isn't found", Toast.LENGTH_LONG).show();
}
}
private String urlEncode(String s) {
try {
return URLEncoder.encode(s, "UTF-8");
} catch (UnsupportedEncodingException e) {
Log.wtf(TAG, "UTF-8 should always be supported", e);
return "";
}
}
Hope it helps.
you can simply open the URL with the text and Twitter App will do it. ;)
String url = "http://www.twitter.com/intent/tweet?url=YOURURL&text=YOURTEXT";
Intent i = new Intent(Intent.ACTION_VIEW);
i.setData(Uri.parse(url));
startActivity(i);
and it will also open the browser to login at the tweet if twitter app is not found.
Try this, I used it and worked great
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("https://twitter.com/intent/tweet?text=...."));
startActivity(browserIntent);
First you have to check if the twitter app installed on the device or not then share the text on twitter:
try
{
// Check if the Twitter app is installed on the phone.
getActivity().getPackageManager().getPackageInfo("com.twitter.android", 0);
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setClassName("com.twitter.android", "com.twitter.android.composer.ComposerActivity");
intent.setType("text/plain");
intent.putExtra(Intent.EXTRA_TEXT, "Your text");
startActivity(intent);
}
catch (Exception e)
{
Toast.makeText(getActivity(),"Twitter is not installed on this device",Toast.LENGTH_LONG).show();
}
For sharing text and image on Twitter, more controlled version of code is below, you can add more methods for sharing with WhatsApp, Facebook ... This is for official App and does not open browser if app not exists.
public class IntentShareHelper {
public static void shareOnTwitter(AppCompatActivity appCompatActivity, String textBody, Uri fileUri) {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setType("text/plain");
intent.setPackage("com.twitter.android");
intent.putExtra(Intent.EXTRA_TEXT,!TextUtils.isEmpty(textBody) ? textBody : "");
if (fileUri != null) {
intent.putExtra(Intent.EXTRA_STREAM, fileUri);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.setType("image/*");
}
try {
appCompatActivity.startActivity(intent);
} catch (android.content.ActivityNotFoundException ex) {
ex.printStackTrace();
showWarningDialog(appCompatActivity, appCompatActivity.getString(R.string.error_activity_not_found));
}
}
public static void shareOnWhatsapp(AppCompatActivity appCompatActivity, String textBody, Uri fileUri){...}
private static void showWarningDialog(Context context, String message) {
new AlertDialog.Builder(context)
.setMessage(message)
.setNegativeButton(context.getString(R.string.close), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
})
.setCancelable(true)
.create().show();
}
}
For getting Uri from File, use below class:
public class UtilityFile {
public static #Nullable Uri getUriFromFile(Context context, #Nullable File file) {
if (file == null)
return null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
try {
return FileProvider.getUriForFile(context, "com.my.package.fileprovider", file);
} catch (Exception e) {
e.printStackTrace();
return null;
}
} else {
return Uri.fromFile(file);
}
}
// Returns the URI path to the Bitmap displayed in specified ImageView
public static Uri getLocalBitmapUri(Context context, ImageView imageView) {
Drawable drawable = imageView.getDrawable();
Bitmap bmp = null;
if (drawable instanceof BitmapDrawable) {
bmp = ((BitmapDrawable) imageView.getDrawable()).getBitmap();
} else {
return null;
}
// Store image to default external storage directory
Uri bmpUri = null;
try {
// Use methods on Context to access package-specific directories on external storage.
// This way, you don't need to request external read/write permission.
File file = new File(context.getExternalFilesDir(Environment.DIRECTORY_PICTURES), "share_image_" + System.currentTimeMillis() + ".png");
FileOutputStream out = new FileOutputStream(file);
bmp.compress(Bitmap.CompressFormat.PNG, 90, out);
out.close();
bmpUri = getUriFromFile(context, file);
} catch (IOException e) {
e.printStackTrace();
}
return bmpUri;
}
}
For writing FileProvider, use this link: https://github.com/codepath/android_guides/wiki/Sharing-Content-with-Intents