The following code was working on API 23, but it is not working on API 27. I read that there are some restrictions in Android API 26 and above for receiving Broadcast Intents but those are only for the ones specified in Manifest file :
public class USBTest extends Service
{
private USBMountBroadcastReceiver mountBroadcastReceiver;
private class USBMountBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(final Context context, Intent intent)
{
String action = intent.getAction();
if (action == null)
{
Log.i(TAG, " got NULL action");
return;
}
if (action.equals(Intent.ACTION_MEDIA_MOUNTED))
{
String root = intent.getData().getPath();
Log.d(TAG, "USB mount path is" + root);
}
}
}
@Override
public void onCreate()
{
mountBroadcastReceiver = new USBMountBroadcastReceiver();
IntentFilter usbIntent = new IntentFilter(Intent.ACTION_MEDIA_MOUNTED);
usbIntent.addAction(Intent.ACTION_MEDIA_EJECT);
usbIntent.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
usbIntent.addAction(Intent.ACTION_MEDIA_REMOVED);
usbIntent.addDataScheme("file");
registerReceiver(mountBroadcastReceiver, usbIntent);
}
}
Update 1 : BroadcastReceiver without service :
public class USBBroadcastReceiver extends BroadcastReceiver
{
private static final String TAG = "USBBroadcastReceiver";
/**
* @see android.content.BroadcastReceiver#onReceive(Context,Intent)
*/
@Override public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action!=null) Log.i(TAG, "got action = " + action);
if (action==null)
{
Log.i(TAG, "got NULL action");
}
else if (Intent.ACTION_MEDIA_MOUNTED.equals(action))
{
Log.i(TAG, "Received media mounted : " + action);
}
}
}
In manifest :
<receiver android:name="USBBroadcastReceiver" android:exported="True">
<intent-filter>
<action android:name="android.intent.action.MEDIA_EJECT" />
<action android:name="android.intent.action.MEDIA_REMOVED" />
<action android:name="android.intent.action.MEDIA_MOUNTED" />
<action android:name="android.intent.action.MEDIA_BAD_REMOVAL" />
<data android:scheme="file" />
</intent-filter>
</receiver>
Update 2 : JobIntent service :
public class TestUSB extends JobIntentService
{
private static final String TAG = "TestUSB";
/**
* Unique job ID for this service.
*/
static final int JOB_ID = 1001;
@Override
protected void onHandleWork(Intent intent)
{
Log.i(TAG, "onHandleWork");
String action = intent.getAction();
if (action!=null) Log.i(TAG, "got action = " + action);
}
}
In manifest :
<service android:name="TestUSB"
android:permission="android.permission.BIND_JOB_SERVICE">
<intent-filter>
<action android:name="android.intent.action.MEDIA_MOUNTED" />
</intent-filter>
</service>
Both approaches above are not working.