Search code examples
androidandroid-broadcastandroid-broadcastreceiver

Why I can't send broadcast to receiver successfull if Intent was set Type?


I create a receiver and dynamic register it in my app:

MyReceiver receiver = new MyReceiver();
IntentFilter intentFilter = new IntentFilter("com.test.receiver");
LocalBroadcastManager.getInstance(this).registerReceiver(receiver, intentFilter); 

I write some codes as below to sending broadcast, my receiver can recive the message successull, everything is ok.

Intent intent = new Intent();
intent.setAction("com.test.receiver");
LocalBroadcastManager.getInstance(MainActivity.this).sendBroadcast(intent);

But if I try to setType() for the Intent, my receiver will not work, nothing will be received.

Intent intent = new Intent();
intent.setAction("com.test.receiver");

intent.setType("test");

LocalBroadcastManager.getInstance(this).sendBroadcast(intent);

According to Android API document, Type doesn't have intent-filter function, do you know why?


Solution

  • From Android documentation, setType() method is used to set valid MIME type.

    setType(String type)

    Set an explicit MIME data type.

    Here is common MIME type that you can send.

    image/jpeg
    audio/mpeg4-generic
    text/html
    audio/mpeg
    audio/aac
    audio/wav
    audio/ogg
    audio/midi
    audio/x-ms-wma
    video/mp4
    video/x-msvideo
    video/x-ms-wmv
    image/png
    image/jpeg
    image/gif
    .xml ->text/xml
    .txt -> text/plain
    .cfg -> text/plain
    .csv -> text/plain
    .conf -> text/plain
    .rc -> text/plain
    .htm -> text/html
    .html -> text/html
    .pdf -> application/pdf
    .apk -> application/vnd.android.package-archive
    

    Whereas test is not a valid MIME type.