I'm new to the Android API and i try hard to start my app (NOT an Activity) from a Broadcast receiver. It's compiling and manualy launching on my Device, but not automatically launching when i plug an USB device in.
My goal : plug usb in -> start app -> "Hello World!"
===============================[edit]======================================
That's the final version that is working for me. If it's not working for you test with an other device.
Works on my Moto G 1st Gen. Android 5.1.1.
Do not work on my S3 I9300 Android 4.4.4
tests :
Reboot -> OS running -> plug USB in -> unlock the screen -> "Hello world"
Unlock -> plug in -> "Hello world"
...
The code :
package com.example.desktop.helloworld;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class HelloworldActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_helloworld);
TextView tv = new TextView(this);
tv.setText("Hello World!");
setContentView(tv);
}
public static class BootUpReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent i = new Intent(context, HelloworldActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(i);
}
}
}
The Manifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.desktop.helloworld">
<uses-feature android:name="android.hardware.usb.host" />
<uses-permission android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".HelloworldActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:enabled="true" android:name=".HelloworldActivity$BootUpReceiver">
<intent-filter>
<action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
<meta-data android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED"
android:resource="@xml/device_filter" />
</receiver>
</application>
device_filter (NOT REQUIERED, then comment the reffence in the manifest):
<?xml version="1.0" encoding="utf-8"?>
<resources>
<usb-device vendor-id="0403" product-id="6001"/>
</resources>
Android Studio 2.0, OTG Cable, Android 4.4.4 .