检测手机是否已插入电脑

时间:2013-10-02 13:57:29

标签: java android

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

<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));
}

我的Broadcastreceiver:

@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);

}

但是当我插上手机时,我从未见过Toast,任何人都知道为什么?!

2 个答案:

答案 0 :(得分:1)

您忘了show() Toast

Toast.makeText(ctx, "Received", Toast.LENGTH_SHORT).show();

答案 1 :(得分:0)

尝试使用此

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

this post中所述。