Friday, April 26, 2013

[android help] Android - sharing


Maybe you wanted a more complete answer because the accepted one was rather short, I'm a year too late but hopefully it's still useful :)


So here's a possible solution in handling multiple intents...


1) You want to know the result (eg succes or fail) of the intent?


Just start the intent using following line:



startActivityForResult(intent, 1); //instead of startActivity(intent)


And retrieve the requestCode and resultCode by overriding onActivityResult:



@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 0) {
if(resultCode == Activity.RESULT_OK){
//intent 0 = succesful (Facebook)
} else{
//intent 0 = failed or canceled
}
} else if (requestCode == 1) {
if(resultCode == Activity.RESULT_OK){
//intent 1 = succesful (Twitter)
} else{
//intent 1 = failed or canceled
}
}
}


2) You want to know which app the intent opened?


Don' trust the built-in intent chooser, make your own dialog and give each intent another requestCode (a unique integer-value, to identify the intent)


An example:



new AlertDialog.Builder(this)
.setTitle("Share with friends!")
.setSingleChoiceItems(new ArrayAdapter(this, android.R.layout.select_dialog_singlechoice,
new String[]{"Facebook", "Twitter"}), -1, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
if (which == 0) {
StartFacebookShare();
} else if (which == 1) {
StartTwitterShare();
}
dialog.dismiss();
}
}).show();

private void StartFacebookShare() {
Intent intent = new Intent("android.intent.category.SEND");
intent.putExtra(Intent.EXTRA_SUBJECT, "URL");
intent.putExtra(Intent.EXTRA_TEXT, "http://www.stackoverflow.com");
intent.setClassName("com.facebook.katana", "com.facebook.katana.ShareLinkActivity");
startActivityForResult(intent, 0);
}
private void StartTwitterShare() {
String message = "www.stackoverflow.com"; //the string you want to tweet
try {
Intent intent = new Intent(Intent.ACTION_SEND);
intent.setClassName("com.twitter.android", "com.twitter.android.PostActivity");
intent.putExtra(Intent.EXTRA_TEXT, message);
startActivityForResult(intent, 1);
} catch (Exception e) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.setData(Uri.parse("https://twitter.com/intent/tweet?text=" + message));
startActivityForResult(intent, 1);
}
}


Some useful info can be found here and here, maybe search here or comment if you have suggestions for my code (I always like feedback ^^) or if you're stuck on something :)



.

stackoverflow.comm

No comments:

Post a Comment

Google Voice on T-Mobile? [General]

Google Voice on T-Mobile? So I recently switched from a GNex on Verizon to a Moto X DE on T-Mobile. I had always used Google Voice for my v...