If I click on the HYPERLINK, I get a dialog with the message that no app was found to handle this link, but I know that my android device has some applications to handle this file, becuase I open this file already by click the file itself. Here the code snippet:
case DragEvent.ACTION_DROP:
final String DATA = event.getClipData().getItemAt(0).getText().toString();
final String RECORDS_DIR = ((ScribeApplication ) getApplication()).RECORDS_DIRECTORY_ABSOLUTE_PATH;
final Spanned HYPERLINK = Html.fromHtml("" + RECORDS_DIR + DATA + "");
editor.setMovementMethod(LinkMovementMethod.getInstance());
if (editor.length() > 0)
{
editor.append("\n");
editor.append(HYPERLINK);
}
else
editor.append(HYPERLINK);
return true;
DATA is the file name e.g. record1.3pg
RECORDS_DIR is the absolute path to the directory with the recording files.
HYPERLINK is the absolute path of a record file.
editor is an instance of Eidttext
As mentioned above, if I navigate to the records directory and click the record file itself I get an app chooser and can select an app to handle this record file. So what I did wrong that I dont get an app chooser by clicking the hyperlink within the edittext but rather an dialog with the failure that no app was found?
Many thanks in advance!
Here is my solution for the issue described by CommonsWare:
public class ClickableIntentURLSpan extends URLSpan
{
private Context context;
private Intent intent;
public ClickableIntentURLSpan(final Context CONTEXT, final String URL, final Intent INTENT)
{
super(URL);
final boolean INPUT_OK = (CONTEXT != null) && (INTENT != null);
if (INPUT_OK)
{
context = CONTEXT;
intent = INTENT;
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
}
else
throw new IllegalArgumentException("Illegal refer to null.");
}
#Override
public void onClick(final View VIEW)
{
context.startActivity(intent);
}
}
case DragEvent.ACTION_DROP:
final String DATA = event.getClipData().getItemAt(0).getText().toString();
final String RECORDS_DIR = ((ScribeApplication ) getApplication()).RECORDS_DIRECTORY_ABSOLUTE_PATH;
final String ABSOLUTE_URL = "file://" + RECORDS_DIR + '/' + DATA;
final Intent PLAY_RECORD_INTENT = new Intent(Intent.ACTION_VIEW);
final File RECORD_FILE = new File(RECORDS_DIR, DATA);
PLAY_RECORD_INTENT.setDataAndType(Uri.fromFile(RECORD_FILE), "audio/*");
final ClickableIntentURLSpan INTENT_URL = new ClickableIntentURLSpan(getApplicationContext(), ABSOLUTE_URL, PLAY_RECORD_INTENT);
final SpannableString HYPERLINK = new SpannableString(DATA);
HYPERLINK.setSpan(INTENT_URL, 0, DATA.length(), 0);
editor.setMovementMethod(LinkMovementMethod.getInstance());
if (editor.length() > 0)
{
editor.append("\n");
editor.append(HYPERLINK);
}
else
editor.append(HYPERLINK);
return true;
I am working on a multimedia application. I am capturing one image through the camera and want to send that image with a text to some other number. But I am not getting how to send the image via the MMS.
MMS is just a htttp-post request. You should perform the request using extra network feature :
final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final int result = connMgr.startUsingNetworkFeature( ConnectivityManager.TYPE_MOBILE, Phone.FEATURE_ENABLE_MMS);
If you get result with Phone.APN_REQUEST_STARTED value, you have to wait for proper state. Register BroadCastReciver and wait until Phone.APN_ALREADY_ACTIVE appears:
final IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(reciver, filter);
If connection background is ready, build content and perform request. If you want to do that using android's internal code, please use this:
final SendReq sendRequest = new SendReq();
final EncodedStringValue[] sub = EncodedStringValue.extract(subject);
if (sub != null && sub.length > 0) {
sendRequest.setSubject(sub[0]);
}
final EncodedStringValue[] phoneNumbers = EncodedStringValue
.extract(recipient);
if (phoneNumbers != null && phoneNumbers.length > 0) {
sendRequest.addTo(phoneNumbers[0]);
}
final PduBody pduBody = new PduBody();
if (parts != null) {
for (MMSPart part : parts) {
final PduPart partPdu = new PduPart();
partPdu.setName(part.Name.getBytes());
partPdu.setContentType(part.MimeType.getBytes());
partPdu.setData(part.Data);
pduBody.addPart(partPdu);
}
}
sendRequest.setBody(pduBody);
final PduComposer composer = new PduComposer(this.context, sendRequest);
final byte[] bytesToSend = composer.make();
HttpUtils.httpConnection(context, 4444L, MMSCenterUrl,
bytesToSendFromPDU, HttpUtils.HTTP_POST_METHOD, !TextUtils
.isEmpty(MMSProxy), MMSProxy, port);
MMSCenterUrl: url from MMS-APNs, MMSProxy: proxy from MMS-APNs, port: port from MMS-APNs
Note that some classes are from internal packages. Download from android git is required.
The request should be done with url from user's apn-space...code..:
public class APNHelper {
public class APN {
public String MMSCenterUrl = "";
public String MMSPort = "";
public String MMSProxy = "";
}
public APNHelper(final Context context) {
this.context = context;
}
public List<APN> getMMSApns() {
final Cursor apnCursor = this.context.getContentResolver().query(Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current"), null, null, null, null);
if ( apnCursor == null ) {
return Collections.EMPTY_LIST;
} else {
final List<APN> results = new ArrayList<APN>();
if ( apnCursor.moveToFirst() ) {
do {
final String type = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.TYPE));
if ( !TextUtils.isEmpty(type) && ( type.equalsIgnoreCase(Phone.APN_TYPE_ALL) || type.equalsIgnoreCase(Phone.APN_TYPE_MMS) ) ) {
final String mmsc = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSC));
final String mmsProxy = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSPROXY));
final String port = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSPORT));
final APN apn = new APN();
apn.MMSCenterUrl = mmsc;
apn.MMSProxy = mmsProxy;
apn.MMSPort = port;
results.add(apn);
}
} while ( apnCursor.moveToNext() );
}
apnCursor.close();
return results;
}
}
private Context context;
}
This seems to be answered in the post: Sending MMS with Android
Key lines of code being:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("sms_body", "some text");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
sendIntent.setType("image/png");
If you have to send MMS with any Image using Intent then use this code.
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
sendIntent.putExtra("sms_body", "some text");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/image_4.png"));
sendIntent.setType("image/png");
startActivity(sendIntent);;
OR
If you have to send MMS with Audio or Video file using Intent then use this.
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
sendIntent.putExtra("address", "1213123123");
sendIntent.putExtra("sms_body", "if you are sending text");
final File file1 = new File(mFileName);
if(file1.exists()){
System.out.println("file is exist");
}
Uri uri = Uri.fromFile(file1);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("video/*");
startActivity(sendIntent);
let me know if this help you.
The answer with the APN helper will not work after android 4.0. To get mms apn settings on Android 4.0 and above view this answer: View mms apn
Suppose I have a full path of file like:(/sdcard/tlogo.png). I want to know its mime type.
I created a function for it
public static String getMimeType(File file, Context context)
{
Uri uri = Uri.fromFile(file);
ContentResolver cR = context.getContentResolver();
MimeTypeMap mime = MimeTypeMap.getSingleton();
String type = mime.getExtensionFromMimeType(cR.getType(uri));
return type;
}
but when i call it, it returns null.
File file = new File(filePath);
String fileType=CommonFunctions.getMimeType(file, context);
First and foremost, you should consider calling MimeTypeMap#getMimeTypeFromExtension(), like this:
// url = file path or whatever suitable URL you want.
public static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
Detect mime type of any file
public String getMimeType(Uri uri) {
String mimeType = null;
if (ContentResolver.SCHEME_CONTENT.equals(uri.getScheme())) {
ContentResolver cr = getAppContext().getContentResolver();
mimeType = cr.getType(uri);
} else {
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(uri
.toString());
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
fileExtension.toLowerCase());
}
return mimeType;
}
The MimeTypeMap solution above returned null in my usage. This works, and is easier:
Uri uri = Uri.fromFile(file);
ContentResolver cR = context.getContentResolver();
String mime = cR.getType(uri);
Optimized version of Jens' answere with null-safety and fallback-type.
#NonNull
static String getMimeType(#NonNull File file) {
String type = null;
final String url = file.toString();
final String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase());
}
if (type == null) {
type = "image/*"; // fallback type. You might set it to */*
}
return type;
}
Important: getFileExtensionFromUrl() only works with lowercase!
Update (19.03.2018)
Bonus: Above methods as a less verbose Kotlin extension function:
fun File.getMimeType(fallback: String = "image/*"): String {
return MimeTypeMap.getFileExtensionFromUrl(toString())
?.run { MimeTypeMap.getSingleton().getMimeTypeFromExtension(toLowerCase()) }
?: fallback // You might set it to */*
}
File file = new File(path, name);
MimeTypeMap mime = MimeTypeMap.getSingleton();
int index = file.getName().lastIndexOf('.')+1;
String ext = file.getName().substring(index).toLowerCase();
String type = mime.getMimeTypeFromExtension(ext);
intent.setDataAndType(Uri.fromFile(file), type);
try
{
context.startActivity(intent);
}
catch(ActivityNotFoundException ex)
{
ex.printStackTrace();
}
Pay super close attention to umerk44's solution above. getMimeTypeFromExtension invokes guessMimeTypeTypeFromExtension and is CASE SENSITIVE. I spent an afternoon on this then took a closer look - getMimeTypeFromExtension will return NULL if you pass it "JPG" whereas it will return "image/jpeg" if you pass it "jpg".
Here is the solution which I used in my Android app:
public static String getMimeType(String url)
{
String extension = url.substring(url.lastIndexOf("."));
String mimeTypeMap = MimeTypeMap.getFileExtensionFromUrl(extension);
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(mimeTypeMap);
return mimeType;
}
EDIT
I created a small library for this.
But the underlying code is nearly the same.
It's available on GitHub
MimeMagic-Android
Solution September 2020
Using Kotlin
fun File.getMimeType(context: Context): String? {
if (this.isDirectory) {
return null
}
fun fallbackMimeType(uri: Uri): String? {
return if (uri.scheme == ContentResolver.SCHEME_CONTENT) {
context.contentResolver.getType(uri)
} else {
val extension = MimeTypeMap.getFileExtensionFromUrl(uri.toString())
MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase(Locale.getDefault()))
}
}
fun catchUrlMimeType(): String? {
val uri = Uri.fromFile(this)
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val path = Paths.get(uri.toString())
try {
Files.probeContentType(path) ?: fallbackMimeType(uri)
} catch (ignored: IOException) {
fallbackMimeType(uri)
}
} else {
fallbackMimeType(uri)
}
}
val stream = this.inputStream()
return try {
URLConnection.guessContentTypeFromStream(stream) ?: catchUrlMimeType()
} catch (ignored: IOException) {
catchUrlMimeType()
} finally {
stream.close()
}
}
That seems like the best option as it combines the previous answers.
First it tries to get the type using URLConnection.guessContentTypeFromStream but if this fails or returns null it tries to get the mimetype on Android O and above using
java.nio.file.Files
java.nio.file.Paths
Otherwise if the Android Version is below O or the method fails it returns the type using ContentResolver and MimeTypeMap
Sometimes Jeb's and Jens's answers don't work and return null. In this case I use follow solution. Head of file usually contains type signature. I read it and compare with known in list of signatures.
/**
*
* #param is InputStream on start of file. Otherwise signature can not be defined.
* #return int id of signature or -1, if unknown signature was found. See SIGNATURE_ID_(type) constants to
* identify signature by its id.
* #throws IOException in cases of read errors.
*/
public static int getSignatureIdFromHeader(InputStream is) throws IOException {
// read signature from head of source and compare with known signatures
int signatureId = -1;
int sigCount = SIGNATURES.length;
int[] byteArray = new int[MAX_SIGNATURE_LENGTH];
StringBuilder builder = new StringBuilder();
for (int i = 0; i < MAX_SIGNATURE_LENGTH; i++) {
byteArray[i] = is.read();
builder.append(Integer.toHexString(byteArray[i]));
}
if (DEBUG) {
Log.d(TAG, "head bytes=" + builder.toString());
}
for (int i = 0; i < MAX_SIGNATURE_LENGTH; i++) {
// check each bytes with known signatures
int bytes = byteArray[i];
int lastSigId = -1;
int coincidences = 0;
for (int j = 0; j < sigCount; j++) {
int[] sig = SIGNATURES[j];
if (DEBUG) {
Log.d(TAG, "compare" + i + ": " + Integer.toHexString(bytes) + " with " + sig[i]);
}
if (bytes == sig[i]) {
lastSigId = j;
coincidences++;
}
}
// signature is unknown
if (coincidences == 0) {
break;
}
// if first bytes of signature is known we check signature for full coincidence
if (coincidences == 1) {
int[] sig = SIGNATURES[lastSigId];
int sigLength = sig.length;
boolean isSigKnown = true;
for (; i < MAX_SIGNATURE_LENGTH && i < sigLength; i++) {
bytes = byteArray[i];
if (bytes != sig[i]) {
isSigKnown = false;
break;
}
}
if (isSigKnown) {
signatureId = lastSigId;
}
break;
}
}
return signatureId;
}
signatureId is an index of signature in array of signatures. For example,
private static final int[] SIGNATURE_PNG = hexStringToIntArray("89504E470D0A1A0A");
private static final int[] SIGNATURE_JPEG = hexStringToIntArray("FFD8FF");
private static final int[] SIGNATURE_GIF = hexStringToIntArray("474946");
public static final int SIGNATURE_ID_JPEG = 0;
public static final int SIGNATURE_ID_PNG = 1;
public static final int SIGNATURE_ID_GIF = 2;
private static final int[][] SIGNATURES = new int[3][];
static {
SIGNATURES[SIGNATURE_ID_JPEG] = SIGNATURE_JPEG;
SIGNATURES[SIGNATURE_ID_PNG] = SIGNATURE_PNG;
SIGNATURES[SIGNATURE_ID_GIF] = SIGNATURE_GIF;
}
Now I have file type even if URI of file haven't. Next I get mime type by file type. If you don't know which mime type to get, you can find proper in this table.
It works for a lot of file types. But for video it doesn't work, because you need to known video codec to get a mime type. To get video's mime type I use MediaMetadataRetriever.
I tried to use standard methods to determine the mime type, but I cannot retain the file extension using MimeTypeMap.getFileExtensionFromUrl(uri.getPath()). This method returned me an empty string. So I made a non-trivial solution to retain the file extension.
Here is the method returning the file extension:
private String getExtension(String fileName){
char[] arrayOfFilename = fileName.toCharArray();
for(int i = arrayOfFilename.length-1; i > 0; i--){
if(arrayOfFilename[i] == '.'){
return fileName.substring(i+1, fileName.length());
}
}
return "";
}
And having retained the file extension, it is possible to get mime type like below:
public String getMimeType(File file) {
String mimeType = "";
String extension = getExtension(file.getName());
if (MimeTypeMap.getSingleton().hasExtension(extension)) {
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return mimeType;
}
its works for me and flexible both for content and file
public static String getMimeType(Context context, Uri uri) {
String extension;
//Check uri format to avoid null
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
//If scheme is a content
final MimeTypeMap mime = MimeTypeMap.getSingleton();
extension = mime.getExtensionFromMimeType(context.getContentResolver().getType(uri));
} else {
//If scheme is a File
//This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
extension = MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(new File(uri.getPath())).toString());
}
return extension;
}
In kotlin it's way simpler.
Solution 1:
fun getMimeType(file: File): String? =
MimeTypeMap.getSingleton().getMimeTypeFromExtension(file.extension)
Solution 2: (File extension fuction)
fun File.mimeType(): String? =
MimeTypeMap.getSingleton().getMimeTypeFromExtension(this.extension)
MimeTypeMap may not recognize some file extensions like flv,mpeg,3gpp,cpp. So you need to think how to expand the MimeTypeMap for maintaining your code. Here is such an example.
http://grepcode.com/file/repo1.maven.org/maven2/com.google.okhttp/okhttp/20120626/libcore/net/MimeUtils.java#MimeUtils
Plus, here is a complete list of mime types
http: //www.sitepoint.com/web-foundations/mime-types-complete-list/
For Xamarin Android (From #HoaLe's answer above)
public String getMimeType(Uri uri) {
String mimeType = null;
if (uri.Scheme.Equals(ContentResolver.SchemeContent))
{
ContentResolver cr = Application.Context.ContentResolver;
mimeType = cr.GetType(uri);
}
else
{
String fileExtension = MimeTypeMap.GetFileExtensionFromUrl(uri.ToString());
mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(
fileExtension.ToLower());
}
return mimeType;
}
get file object....
File file = new File(filePath);
then....pass as a parameter to...
getMimeType(file);
...here is
public String getMimeType(File file) {
String mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(Uri.fromFile(file).toString()).toLowerCase());
if (mimetype == null) {
return "*/*";
}
return mimetype;///return the mimeType
}
While from asset/file(Note that few cases missing from the MimeTypeMap).
private String getMimeType(String path) {
if (null == path) return "*/*";
String extension = path;
int lastDot = extension.lastIndexOf('.');
if (lastDot != -1) {
extension = extension.substring(lastDot + 1);
}
// Convert the URI string to lower case to ensure compatibility with MimeTypeMap (see CB-2185).
extension = extension.toLowerCase(Locale.getDefault());
if (extension.equals("3ga")) {
return "audio/3gpp";
} else if (extension.equals("js")) {
return "text/javascript";
} else if (extension.equals("woff")) {
return "application/x-font-woff";
} else {
// TODO
// anyting missing from the map (http://www.sitepoint.com/web-foundations/mime-types-complete-list/)
// reference: http://grepcode.com/file/repo1.maven.org/maven2/com.google.okhttp/okhttp/20120626/libcore/net/MimeUtils.java#MimeUtils
}
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
While use ContentResolver
contentResolver.getType(uri)
While http/https request
try {
HttpURLConnection conn = httpClient.open(new URL(uri.toString()));
conn.setDoInput(false);
conn.setRequestMethod("HEAD");
return conn.getHeaderField("Content-Type");
} catch (IOException e) {
}
// This will return the mimeType.
// for eg. xyz.png it will return image/png.
// here uri is the file that we were picked using intent from ext/internal storage.
private String getMimeType(Uri uri) {
// This class provides applications access to the content model.
ContentResolver contentResolver = getContentResolver();
// getType(Uri url)-Return the MIME type of the given content URL.
return contentResolver.getType(uri);
}
I faced similar problem. So far I know result may different for different names, so finally came to this solution.
public String getMimeType(String filePath) {
String type = null;
String extension = null;
int i = filePath.lastIndexOf('.');
if (i > 0)
extension = filePath.substring(i+1);
if (extension != null)
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
return type;
}
I don't realize why MimeTypeMap.getFileExtensionFromUrl() has problems with spaces and some other characters, that returns "", but I just wrote this method to change the file name to an admit-able one. It's just playing with Strings. However, It kind of works. Through the method, the spaces existing in the file name is turned into a desirable character (which, here, is "x") via replaceAll(" ", "x") and other unsuitable characters are turned into a suitable one via URLEncoder. so the usage (according to the codes presented in the question and the selected answer) should be something like getMimeType(reviseUrl(url)).
private String reviseUrl(String url) {
String revisedUrl = "";
int fileNameBeginning = url.lastIndexOf("/");
int fileNameEnding = url.lastIndexOf(".");
String cutFileNameFromUrl = url.substring(fileNameBeginning + 1, fileNameEnding).replaceAll(" ", "x");
revisedUrl = url.
substring(0, fileNameBeginning + 1) +
java.net.URLEncoder.encode(cutFileNameFromUrl) +
url.substring(fileNameEnding, url.length());
return revisedUrl;
}
The above solution returned null in case of .rar file, using URLConnection.guessContentTypeFromName(url) worked in this case.
mime from local file:
String url = file.getAbsolutePath();
FileNameMap fileNameMap = URLConnection.getFileNameMap();
String mime = fileNameMap.getContentTypeFor("file://"+url);
you have multiple choice to get extension of file:like:
1-String filename = uri.getLastPathSegment(); see this link
2-you can use this code also
filePath .substring(filePath.lastIndexOf(".")+1);
but this not good aproch.
3-if you have URI of file then use this Code
String[] projection = { MediaStore.MediaColumns.DATA,
MediaStore.MediaColumns.MIME_TYPE };
4-if you have URL then use this code:
public static String getMimeType(String url) {
String type = null;
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
}
return type;
}
enjoy your code:)
// new processing the mime type out of Uri which may return null in some cases
String mimeType = getContentResolver().getType(uri);
// old processing the mime type out of path using the extension part if new way returned null
if (mimeType == null){mimeType URLConnection.guessContentTypeFromName(path);}
public static String getFileType(Uri file)
{
try
{
if (file.getScheme().equals(ContentResolver.SCHEME_CONTENT))
return subStringFromLastMark(SystemMaster.getContentResolver().getType(file), "/");
else
return MimeTypeMap.getFileExtensionFromUrl(file.toString()).toLowerCase();
}
catch(Exception e)
{
return null;
}
}
public static String getMimeType(Uri file)
{
try
{
return MimeTypeMap.getSingleton().getMimeTypeFromExtension(getFileType(file));
}
catch(Exception e)
{
return null;
}
}
public static String subStringFromLastMark(String str,String mark)
{
int l = str.lastIndexOf(mark);
int end = str.length();
if(l == -1)
return str;
return str.substring(l + 1, end);
}
Has also return null value
in my case path was
/storage/emulated/0/Music/01 - Ghost on the Dance Floor.mp3
as work around use
val url = inUrl.replace(" ","")
so method looks like
#JvmStatic
fun getMimeType(inUrl: String?): String {
if (inUrl == null) return ""
val url = inUrl.replace(" ","")
var type: String? = null
val extension = MimeTypeMap.getFileExtensionFromUrl(url)
if (extension != null) {
type = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension.toLowerCase())
}
if(type ==null){
val cR = WifiTalkie.getApplicationContext().contentResolver
type = cR.getType(Uri.parse(url))
}
if (type == null) {
type = "*/*" // fallback method_type. You might set it to */*
}
return type
}
as result it return success result:
audio/mpeg
Hope it helps anybody
None of the answers here are perfect. Here is an answer combining the best elements of all the top answers:
public final class FileUtil {
// By default, Android doesn't provide support for JSON
public static final String MIME_TYPE_JSON = "application/json";
#Nullable
public static String getMimeType(#NonNull Context context, #NonNull Uri uri) {
String mimeType = null;
if (uri.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
ContentResolver cr = context.getContentResolver();
mimeType = cr.getType(uri);
} else {
String fileExtension = getExtension(uri.toString());
if(fileExtension == null){
return null;
}
mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(
fileExtension.toLowerCase());
if(mimeType == null){
// Handle the misc file extensions
return handleMiscFileExtensions(fileExtension);
}
}
return mimeType;
}
#Nullable
private static String getExtension(#Nullable String fileName){
if(fileName == null || TextUtils.isEmpty(fileName)){
return null;
}
char[] arrayOfFilename = fileName.toCharArray();
for(int i = arrayOfFilename.length-1; i > 0; i--){
if(arrayOfFilename[i] == '.'){
return fileName.substring(i+1, fileName.length());
}
}
return null;
}
#Nullable
private static String handleMiscFileExtensions(#NonNull String extension){
if(extension.equals("json")){
return MIME_TYPE_JSON;
}
else{
return null;
}
}
}
Intent myIntent = new Intent(android.content.Intent.ACTION_VIEW);
File file = new File(filePatch);
Uri uris = Uri.fromFile(file);
String mimetype = null;
if
(uris.getScheme().equals(ContentResolver.SCHEME_CONTENT)) {
ContentResolver cr =
getApplicationContext().getContentResolver();
mimetype = cr.getType(uris);
} else {
String fileExtension =
MimeTypeMap.getFileExtensionFromUrl(uris.toString());
mimetype = MimeTypeMap.getSingleton().getMimeTypeFromExtension(fileExtension.toLowerCase());
}
I consider the easiest way is to refer to this Resource file:
https://android.googlesource.com/platform/libcore/+/master/luni/src/main/java/libcore/net/android.mime.types
I am working on a multimedia application. I am capturing one image through the camera and want to send that image with a text to some other number. But I am not getting how to send the image via the MMS.
MMS is just a htttp-post request. You should perform the request using extra network feature :
final ConnectivityManager connMgr = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
final int result = connMgr.startUsingNetworkFeature( ConnectivityManager.TYPE_MOBILE, Phone.FEATURE_ENABLE_MMS);
If you get result with Phone.APN_REQUEST_STARTED value, you have to wait for proper state. Register BroadCastReciver and wait until Phone.APN_ALREADY_ACTIVE appears:
final IntentFilter filter = new IntentFilter();
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
context.registerReceiver(reciver, filter);
If connection background is ready, build content and perform request. If you want to do that using android's internal code, please use this:
final SendReq sendRequest = new SendReq();
final EncodedStringValue[] sub = EncodedStringValue.extract(subject);
if (sub != null && sub.length > 0) {
sendRequest.setSubject(sub[0]);
}
final EncodedStringValue[] phoneNumbers = EncodedStringValue
.extract(recipient);
if (phoneNumbers != null && phoneNumbers.length > 0) {
sendRequest.addTo(phoneNumbers[0]);
}
final PduBody pduBody = new PduBody();
if (parts != null) {
for (MMSPart part : parts) {
final PduPart partPdu = new PduPart();
partPdu.setName(part.Name.getBytes());
partPdu.setContentType(part.MimeType.getBytes());
partPdu.setData(part.Data);
pduBody.addPart(partPdu);
}
}
sendRequest.setBody(pduBody);
final PduComposer composer = new PduComposer(this.context, sendRequest);
final byte[] bytesToSend = composer.make();
HttpUtils.httpConnection(context, 4444L, MMSCenterUrl,
bytesToSendFromPDU, HttpUtils.HTTP_POST_METHOD, !TextUtils
.isEmpty(MMSProxy), MMSProxy, port);
MMSCenterUrl: url from MMS-APNs, MMSProxy: proxy from MMS-APNs, port: port from MMS-APNs
Note that some classes are from internal packages. Download from android git is required.
The request should be done with url from user's apn-space...code..:
public class APNHelper {
public class APN {
public String MMSCenterUrl = "";
public String MMSPort = "";
public String MMSProxy = "";
}
public APNHelper(final Context context) {
this.context = context;
}
public List<APN> getMMSApns() {
final Cursor apnCursor = this.context.getContentResolver().query(Uri.withAppendedPath(Telephony.Carriers.CONTENT_URI, "current"), null, null, null, null);
if ( apnCursor == null ) {
return Collections.EMPTY_LIST;
} else {
final List<APN> results = new ArrayList<APN>();
if ( apnCursor.moveToFirst() ) {
do {
final String type = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.TYPE));
if ( !TextUtils.isEmpty(type) && ( type.equalsIgnoreCase(Phone.APN_TYPE_ALL) || type.equalsIgnoreCase(Phone.APN_TYPE_MMS) ) ) {
final String mmsc = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSC));
final String mmsProxy = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSPROXY));
final String port = apnCursor.getString(apnCursor.getColumnIndex(Telephony.Carriers.MMSPORT));
final APN apn = new APN();
apn.MMSCenterUrl = mmsc;
apn.MMSProxy = mmsProxy;
apn.MMSPort = port;
results.add(apn);
}
} while ( apnCursor.moveToNext() );
}
apnCursor.close();
return results;
}
}
private Context context;
}
This seems to be answered in the post: Sending MMS with Android
Key lines of code being:
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.putExtra("sms_body", "some text");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse(url));
sendIntent.setType("image/png");
If you have to send MMS with any Image using Intent then use this code.
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
sendIntent.putExtra("sms_body", "some text");
sendIntent.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///sdcard/image_4.png"));
sendIntent.setType("image/png");
startActivity(sendIntent);;
OR
If you have to send MMS with Audio or Video file using Intent then use this.
Intent sendIntent = new Intent(Intent.ACTION_SEND);
sendIntent.setClassName("com.android.mms", "com.android.mms.ui.ComposeMessageActivity");
sendIntent.putExtra("address", "1213123123");
sendIntent.putExtra("sms_body", "if you are sending text");
final File file1 = new File(mFileName);
if(file1.exists()){
System.out.println("file is exist");
}
Uri uri = Uri.fromFile(file1);
sendIntent.putExtra(Intent.EXTRA_STREAM, uri);
sendIntent.setType("video/*");
startActivity(sendIntent);
let me know if this help you.
The answer with the APN helper will not work after android 4.0. To get mms apn settings on Android 4.0 and above view this answer: View mms apn
Basically, I want to get a list of all installed apps and pick one to run from an activity.
I've tried ACTION_PICK with Intents but that seems to leave out apps that were downloaded and it has a bunch of junk in it.
Thanks
// to get the list of apps you can launch
Intent intent = new Intent(ACTION_MAIN);
intent.addCategory(CATEGORY_LAUNCHER);
List<ResolveInfo> infos = getPackageManager().queryIntentActivities(intent, 0);
// resolveInfo.activityInfo.packageName = packageName
// resolveInfo.activityInfo.name = className
// reusing that intent
intent.setClassName(packageName, className);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
startActivity(intent)
Hope that's enough to help you figure out.
final File favFile = new File(Environment.getRootDirectory(), DEFAULT_FAVORITES_PATH);
try {
favReader = new FileReader(favFile);
} catch (FileNotFoundException e) {
Log.e(LOG_TAG, "Couldn't find or open favorites file " + favFile);
return;
}//gives the path for downloaded apps in directory
private void loadApplications(boolean isLaunching) {
if (isLaunching && mApplications != null) {
return;
}
PackageManager manager = getPackageManager();
Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List<ResolveInfo> apps = manager.queryIntentActivities(mainIntent, 0);
Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));
if (apps != null) {
final int count = apps.size();
if (mApplications == null) {
mApplications = new ArrayList<ApplicationInfo>(count);
}
mApplications.clear();
for (int i = 0; i < count; i++) {
ApplicationInfo application = new ApplicationInfo();
ResolveInfo info = apps.get(DEFAULT_KEYS_SEARCH_LOCAL);
application.title = info.loadLabel(manager);
application.setActivity(new ComponentName(
info.activityInfo.applicationInfo.packageName,
info.activityInfo.name),
Intent.FLAG_ACTIVITY_NEW_TASK
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
application.icon = info.activityInfo.loadIcon(manager);
mApplications.add(application);
}
}
This will help u to load all the apps downloaded.