I need to develop an app that has the share function. I have to share on Facebook, twitter, email and maybe other services.
How can I do this? There a library on th
I think the following code will help....
public void btnShareClick(View v) {
// shareBtnFlag = 1;
Dialog d = new Dialog(DrawAppActivity.this);
d.requestWindowFeature(d.getWindow().FEATURE_NO_TITLE);
d.setCancelable(true);
d.setContentView(R.layout.sharing);
final Button btnFacebook = (Button) d.findViewById(R.id.btnFacebook);
final Button btnEmail = (Button) d.findViewById(R.id.btnEmail);
btnEmail.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (!btnEmail.isSelected()) {
btnEmail.setSelected(true);
} else {
btnEmail.setSelected(false);
}
saveBtnFlag = 1;
// Check if email id is available-------------
AccountManager manager = AccountManager
.get(DrawAppActivity.this);
Account[] accounts = manager.getAccountsByType("com.google");
Account account = CommonFunctions.getAccount(manager);
if (account.name != null) {
emailSendingTask eTask = new emailSendingTask();
eTask.execute();
if (CommonFunctions.createDirIfNotExists(getResources()
.getString(R.string.path)))
{
tempImageSaving(
getResources().getString(R.string.path),
getCurrentImage());
}
Intent sendIntent;
sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setType("application/octet-stream");
sendIntent.setType("image/jpeg");
sendIntent.putExtra(Intent.EXTRA_EMAIL,
new String[] { account.name });
sendIntent.putExtra(Intent.EXTRA_SUBJECT, "Drawing App");
sendIntent.putExtra(Intent.EXTRA_TEXT, "Check This Image");
sendIntent.putExtra(Intent.EXTRA_STREAM,
Uri.parse("file://" + tempPath.getPath()));
List<ResolveInfo> list = getPackageManager()
.queryIntentActivities(sendIntent,
PackageManager.MATCH_DEFAULT_ONLY);
if (list.size() != 0) {
startActivity(Intent.createChooser(sendIntent,
"Send Email Using:"));
}
else {
AlertDialog.Builder confirm = new AlertDialog.Builder(
DrawAppActivity.this);
confirm.setTitle(R.string.app_name);
confirm.setMessage("No Email Sending App Available");
confirm.setPositiveButton("Set Account",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
confirm.show();
}
} else {
AlertDialog.Builder confirm = new AlertDialog.Builder(
DrawAppActivity.this);
confirm.setTitle(R.string.app_name);
confirm.setMessage("No Email Account Available!");
confirm.setPositiveButton("Set Account",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
Intent i = new Intent(
Settings.ACTION_SYNC_SETTINGS);
startActivity(i);
dialog.dismiss();
}
});
confirm.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
confirm.show();
}
}
});
btnFacebook.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
if (!btnFacebook.isSelected()) {
btnFacebook.setSelected(true);
} else {
btnFacebook.setSelected(false);
}
saveBtnFlag = 1;
// if (connection.isInternetOn()) {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
getCurrentImage();
Intent i = new Intent(DrawAppActivity.this,
FaceBookAuthentication.class);
i.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(i);
}
else {
ShowAlertMessage.showDialog(DrawAppActivity.this,
R.string.app_name, R.string.Sd_card,
R.string.button_retry);
}
}
});
d.show();
}
public void tempImageSaving(String tmpPath, byte[] image) {
Random rand = new Random();
tempfile = new File(Environment.getExternalStorageDirectory(), tmpPath);
if (!tempfile.exists()) {
tempfile.mkdirs();
}
tempPath = new File(tempfile.getPath(), "DrawApp" + rand.nextInt()
+ ".jpg");
try {
FileOutputStream fos1 = new FileOutputStream(tempPath.getPath());
fos1.write(image);
fos1.flush();
fos1.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
sendBroadcast(new Intent(
Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
public byte[] getCurrentImage() {
Bitmap b = drawingSurface.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
b.compress(Bitmap.CompressFormat.PNG, 100, stream);
byteArray = stream.toByteArray();
return byteArray;
}
private class emailSendingTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(DrawAppActivity.this);
progressDialog.setTitle(R.string.app_name);
progressDialog.setMessage("Saving..Please Wait..");
// progressDialog.setIcon(R.drawable.icon);
progressDialog.show();
}
@Override
protected String doInBackground(String... urls) {
String response = "";
try {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
response = "Yes";
} else {
ShowAlertMessage.showDialog(DrawAppActivity.this,
R.string.app_name, R.string.Sd_card,
R.string.button_retry);
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
if (result.contains("Yes")) {
getCurrentImage();
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
progressDialog.cancel();
}
}
private class ImageSavingTask extends AsyncTask<String, Void, String> {
@Override
protected void onPreExecute() {
progressDialog = new ProgressDialog(DrawAppActivity.this);
progressDialog.setTitle(R.string.app_name);
progressDialog.setMessage("Saving..Please Wait..");
// progressDialog.setIcon(R.drawable.icon);
progressDialog.show();
}
@Override
protected String doInBackground(String... urls) {
String response = "";
try {
if (android.os.Environment.getExternalStorageState().equals(
android.os.Environment.MEDIA_MOUNTED)) {
response = "Yes";
} else {
ShowAlertMessage.showDialog(DrawAppActivity.this,
R.string.app_name, R.string.Sd_card,
R.string.button_retry);
}
} catch (Exception e) {
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
if (result.contains("Yes")) {
getCurrentImage();
if (CommonFunctions.createDirIfNotExists(getResources()
.getString(R.string.path)))
{
saveImageInSdCard(getResources().getString(R.string.path),
getCurrentImage());
}
}
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
Uri.parse("file://"
+ Environment.getExternalStorageDirectory())));
progressDialog.cancel();
}
}
For facebook application use facebook SDK
Share on Facebook
private ShareDialog shareDialog;
shareDialog = new ShareDialog((AppCompatActivity) context);
shareDialog.registerCallback(callbackManager, new FacebookCallback<Sharer.Result>() {
@Override
public void onSuccess(Sharer.Result result) {
Log.e("TAG","Facebook Share Success");
logoutFacebook();
}
@Override
public void onCancel() {
Log.e("TAG","Facebook Sharing Cancelled by User");
}
@Override
public void onError(FacebookException error) {
Log.e("TAG","Facebook Share Success: Error: " + error.getLocalizedMessage());
}
});
if (ShareDialog.canShow(ShareLinkContent.class)) {
ShareLinkContent linkContent = new ShareLinkContent.Builder()
.setQuote("Content goes here")
.setContentUrl(Uri.parse("URL goes here"))
.build();
shareDialog.show(linkContent);
}
AndroidManifest.xml
<!-- Facebook Share -->
<provider
android:name="com.facebook.FacebookContentProvider"
android:authorities="com.facebook.app.FacebookContentProvider{@string/facebook_app_id}"
android:exported="true" />
<!-- Facebook Share -->
dependencies {
implementation 'com.facebook.android:facebook-share:[5,6)' //Facebook Share
}
Share on Twitter
public void shareProductOnTwitter() {
TwitterConfig config = new TwitterConfig.Builder(this)
.logger(new DefaultLogger(Log.DEBUG))
.twitterAuthConfig(new TwitterAuthConfig(getResources().getString(R.string.twitter_api_key), getResources().getString(R.string.twitter_api_secret)))
.debug(true)
.build();
Twitter.initialize(config);
twitterAuthClient = new TwitterAuthClient();
TwitterSession twitterSession = TwitterCore.getInstance().getSessionManager().getActiveSession();
if (twitterSession == null) {
twitterAuthClient.authorize(this, new Callback<TwitterSession>() {
@Override
public void success(Result<TwitterSession> result) {
TwitterSession twitterSession = result.data;
shareOnTwitter();
}
@Override
public void failure(TwitterException e) {
Log.e("TAG","Twitter Error while authorize user " + e.getMessage());
}
});
} else {
shareOnTwitter();
}
}
private void shareOnTwitter() {
StatusesService statusesService = TwitterCore.getInstance().getApiClient().getStatusesService();
Call<Tweet> tweetCall = statusesService.update("Content goes here", null, false, null, null, null, false, false, null);
tweetCall.enqueue(new Callback<Tweet>() {
@Override
public void success(Result<Tweet> result) {
Log.e("TAG","Twitter Share Success");
logoutTwitter();
}
@Override
public void failure(TwitterException exception) {
Log.e("TAG","Twitter Share Failed with Error: " + exception.getLocalizedMessage());
}
});
}
yes you can ... you just need to know the exact package name of the application:
And you can create the intent like this
Intent intent = context.getPackageManager().getLaunchIntentForPackage(application);
if (intent != null) {
// The application exists
Intent shareIntent = new Intent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent.setPackage(application);
shareIntent.putExtra(android.content.Intent.EXTRA_TITLE, title);
shareIntent.putExtra(Intent.EXTRA_TEXT, description);
// Start the specific social application
context.startActivity(shareIntent);
} else {
// The application does not exist
// Open GooglePlay or use the default system picker
}
I think you want to give Share button, clicking on which the suitable media/website option should be there to share with it. In Android, you need to create createChooser
for the same.
Sharing Text:
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "This is the text that will be shared.");
startActivity(Intent.createChooser(sharingIntent,"Share using"));
Sharing binary objects (Images, videos etc.)
Intent sharingIntent = new Intent(Intent.ACTION_SEND);
Uri screenshotUri = Uri.parse(path);
sharingIntent.setType("image/png");
sharingIntent.putExtra(Intent.EXTRA_STREAM, screenshotUri);
startActivity(Intent.createChooser(sharingIntent, "Share image using"));
FYI, above code are referred from Sharing content in Android using ACTION_SEND Intent
The ACTION_SEND will work correctly for all and it takes the Body of the text to wall in twitter, G mail.. but it fails For Face Book page... Its as known bug in the Facebook android SDK .. but still they haven't fixed it
This will help
1- First Define This Constants
public static final String FACEBOOK_PACKAGE_NAME = "com.facebook.katana";
public static final String TWITTER_PACKAGE_NAME = "com.twitter.android";
public static final String INSTAGRAM_PACKAGE_NAME = "com.instagram.android";
public static final String PINTEREST_PACKAGE_NAME = "com.pinterest";
public static final String WHATS_PACKAGE_NAME = "com.whatsapp";
2- Second Use This method
public static void shareAppWithSocial(Context context, String application, String title,
String description) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_SEND);
intent.setPackage(application);
intent.putExtra(android.content.Intent.EXTRA_TITLE, title);
intent.putExtra(Intent.EXTRA_TEXT, description);
intent.setType("text/plain");
try {
// Start the specific social application
context.startActivity(intent);
} catch (android.content.ActivityNotFoundException ex) {
// The application does not exist
Toast.makeText(context, "app have not been installed.", Toast.LENGTH_SHORT).show();
}
}