Integrating with Twitter on Android

Integrating with Twitter on Android

The first step:

To create a button in your .xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".TheDeveloperWorldIsYours" >

    <button
        android:id="@+id/twitterButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</RelativeLayout>

Now in your .class, you should your dialog, this form.

public class TheDeveloperWorldIsYours extends Activity {
	private Button mTwitterButton;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_the_developer_world_is_yours);

		mTwitterButton = (Button) findViewById(R.id.twitterButton);
		mTwitterButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				// TODO Auto-generated method stub

				Intent share = findTwitterClient();

				if (share != null) {

					share.setType("text/plain");

					share.putExtra(Intent.EXTRA_TEXT, "TEXT");

					startActivity(share);
				}

				else {

					AlertDialog.Builder builder = new AlertDialog.Builder(
							TheDeveloperWorldIsYours.this);

					builder.setMessage("Instal twitter")

					.setTitle("¡attention!")

					.setCancelable(false)

					.setNeutralButton("Accept",

					new DialogInterface.OnClickListener() {

						public void onClick(DialogInterface dialog, int id) {

							dialog.cancel();

						}

					});

					AlertDialog alert = builder.create();

					alert.show();

					System.out.println("TEXT");

				}

			}

		});
	}

	public Intent findTwitterClient() {
	    final String[] twitterApps = {
	            // package // name - nb installs (thousands)
	            "com.twitter.android", // official - 10 000
	            "com.twidroid", // twidroid - 5 000
	            "com.handmark.tweetcaster", // Tweecaster - 5 000
	            "com.thedeck.android" }; // TweetDeck - 5 000 };
	    Intent tweetIntent = new Intent();
	    tweetIntent.setType("text/plain");
	    final PackageManager packageManager = getPackageManager();
	    List list = packageManager.queryIntentActivities(
	            tweetIntent, PackageManager.MATCH_DEFAULT_ONLY);

	    for (int i = 0; i < twitterApps.length; i++) {
	        for (ResolveInfo resolveInfo : list) {
	            String p = resolveInfo.activityInfo.packageName;
	            if (p != null && p.startsWith(twitterApps[i])) {
	                tweetIntent.setPackage(p);
	                return tweetIntent;
	            }
	        }
	    }
	    return null;

	}

}