How to add custom mime type in Android?

2019-07-28 00:11发布

问题:

I have a special service to upload files. When upload is finished, I send a broadcast from my service - which contains a special serialized object. This object may be an instance of many classes. To recognize this object class, I use a custom intent type.

How it looks:

// Sending broadcast
Intent intent = new Intent(UploaderService.ACTION_UPLOAD_SUCCESSFULLY);
intent.setType(UploaderService.TYPE_DOC);
intent.putExtra(UploaderService.FIELD_RESULT, object);
context.sendBroadcast(intent);

// Registering receiver
IntentFilter filter = new IntentFilter(UploaderService.ACTION_UPLOAD_SUCCESSFULLY);
filter.addDataType(UploaderService.TYPE_DOC);
registerReceiver(receiver, filter);

During the registering receiver I catch IntentFilter.MalformedMimeTypeException. TYPE_DOC constant looks like "vnd.com.my.package.doc".

So, I suppose, my mime type must be registered in system. How I can do it within code?

回答1:

So, I suppose, my mime type must be registered in system.

No, you need to use a valid MIME type construction. vnd.com.my.package.doc is a malformed MIME type. Use application/vnd.com.my.package.doc for a vendor-prefixed MIME type.

Note that using MIME types on broadcasts is rather unusual behavior.