Created
September 17, 2014 09:52
-
-
Save fedefernandez/93c786aa3dc2f307fb9c to your computer and use it in GitHub Desktop.
Intent launcher for common data
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import android.app.Activity; | |
import android.content.Intent; | |
import android.net.Uri; | |
import android.text.TextUtils; | |
public class IntentLauncher { | |
public static class IntentLauncherException extends Exception { | |
public IntentLauncherException(String detailMessage) { | |
super(detailMessage); | |
} | |
public IntentLauncherException(Throwable throwable) { | |
super(throwable); | |
} | |
} | |
public static enum Type { | |
TEXT, | |
URL, | |
EMAIL, | |
PHONE | |
} | |
private Activity activity; | |
private Type type; | |
private String text; | |
public IntentLauncher(Activity activity, Type type, String text) { | |
this.activity = activity; | |
this.type = type; | |
this.text = text; | |
} | |
public void launchIntent() throws IntentLauncherException { | |
if (TextUtils.isEmpty(text)) { | |
throw new IntentLauncherException("Link can't be empty or null"); | |
} | |
Intent intent = null; | |
if (type == Type.URL) { | |
intent = new Intent(Intent.ACTION_VIEW); | |
intent.setData(Uri.parse(text)); | |
} else if (type == Type.EMAIL) { | |
intent = new Intent(Intent.ACTION_SEND); | |
intent.putExtra(Intent.EXTRA_EMAIL, text); | |
intent.setType("message/rfc822"); | |
} else if (type == Type.PHONE) { | |
intent = new Intent(Intent.ACTION_DIAL); | |
intent.setData(Uri.parse(text)); | |
} else if (type == Type.TEXT) { | |
intent = new Intent(Intent.ACTION_SEND); | |
intent.putExtra(Intent.EXTRA_TEXT, text); | |
intent.setType("text/plain"); | |
} | |
if (intent == null) { | |
throw new IntentLauncherException("Can't launch type: " + type.name()); | |
} else { | |
try { | |
activity.startActivity(intent); | |
} catch (Exception e) { | |
throw new IntentLauncherException(e); | |
} | |
} | |
} | |
public static class Builder { | |
private final Activity activity; | |
private Type type; | |
private String text; | |
public Builder(Activity activity) { | |
this.activity = activity; | |
} | |
public Builder type(Type Type) { | |
this.type = Type; | |
return this; | |
} | |
public Builder text(String text) { | |
this.text = text; | |
return this; | |
} | |
public IntentLauncher build() { | |
return new IntentLauncher(activity, type, text); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment