如何检测Android设备中的USB连接,并使用USB线将数据从Android设备传输到PC?提前致谢
答案 0 :(得分:0)
This code is working which can automatically detect when usb is connected and disconnected..
Receiver:
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.Gravity;
import android.widget.TextView;
import android.widget.Toast;
public class DetactUSB extends BroadcastReceiver
{
private static final String TAG = "DetactUSB";
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(intent.getExtras().getBoolean("connected"))
{
TextView textView = new TextView(context);
textView.setBackgroundColor(Color.MAGENTA);
textView.setTextColor(Color.BLUE);
textView.setPadding(10,10,10,10);
textView.setText("USB connected..........");
Toast toastView = new Toast(context);
toastView.setDuration(Toast.LENGTH_SHORT);
toastView.setGravity(Gravity.CENTER, 0,0);
toastView.setView(textView);
toastView.show();
}
else{
TextView textView = new TextView(context);
textView.setBackgroundColor(Color.BLUE);
textView.setTextColor(Color.YELLOW);
textView.setPadding(10,10,10,10);
textView.setText("USB not connected..........");
Toast toastView = new Toast(context);
toastView.setDuration(Toast.LENGTH_SHORT);
toastView.setGravity(Gravity.CENTER, 0,0);
toastView.setView(textView);
toastView.show();
}
}
}
manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.usbdetectiondemo"
android:versionCode="1"
android:versionName="1.0" >
<uses-permission android:name="android.permission.INTERNET" >
</uses-permission>
<uses-permission android:name="android.permission.RECORD_AUDIO" >
</uses-permission>
<application
android:icon="@drawable/ic_launcher"
android:label="@string/app_name" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".DetactUSB" >
<intent-filter>
<action android:name="android.hardware.usb.action.USB_STATE" />
</intent-filter>
</receiver>
</application>
</manifest>
And There is no need to do any thing in the activity..