0

我想检测手机是否插入电脑或将被拔出......所以在我的清单中我有:

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="de.name.usbtest.MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        <intent-filter>
        <action android:name="android.hardware.usb.action.USB_DEVICE_ATTACHED" />
    </intent-filter>
    </activity>

    <service
        android:name=".MyService"
        >
    </service>
</application>

我的服务等级:

@Override
public void onCreate() {
    USBBroadcast usbTrigger = null;
    // create new USBTrigger()() and register for ACTION_USB_DEVICE_ATTACHED broadcasts
    usbTrigger = new USBBroadcast();
    registerReceiver(usbTrigger, new IntentFilter(UsbManager.ACTION_USB_DEVICE_ATTACHED));
}

我的广播接收器:

@Override
public void onReceive(Context ctx, Intent intent) {
    String action = intent.getAction();
    Toast.makeText(ctx, "Received", Toast.LENGTH_SHORT).show();
}

和我的主要活动:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Intent serviceIntent = new Intent(this, MyService.class);

    startService(serviceIntent);

    setContentView(R.layout.activity_main);

}

但是当我插入手机时,我从来没有看到过吐司……有人知道为什么吗?!

4

2 回答 2

1

你忘show()Toast

Toast.makeText(ctx, "Received", Toast.LENGTH_SHORT).show();
于 2013-10-02T14:01:31.023 回答
0

尝试使用这个

<intent-filter>
<action android:name="android.intent.action.ACTION_UMS_CONNECTED"/>
<action android:name="android.intent.action.ACTION_UMS_DISCONNECTED"/>

本文所述。

于 2013-10-02T14:34:22.413 回答