package com.example.usbtest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Message;
import android.util.Log;
public class UsbStatesReceiver extends BroadcastReceiver {
MainActivity execactivity;
public static final int USB_STATE_MSG = 0x00020;
public static final int USB_STATE_ON = 0x00021;
public static final int USB_STATE_OFF = 0x00022;
public IntentFilter filter = new IntentFilter();
public UsbStatesReceiver(Context context){
execactivity = (MainActivity)context;
filter.addAction(Intent.ACTION_MEDIA_CHECKING);
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);
filter.addAction(Intent.ACTION_MEDIA_EJECT);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addDataScheme("file");
}
public Intent registerReceiver() {
return execactivity.registerReceiver(this, filter);
}
public void unregisterReceiver() {
execactivity.unregisterReceiver(this);
}
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
if(execactivity.mhandler == null){
return;
}
Message msg = new Message();
msg.what = USB_STATE_MSG;
if( intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED ) ||
intent.getAction().equals(Intent.ACTION_MEDIA_CHECKING)){
msg.arg1 = USB_STATE_ON;
msg.obj=intent.getData().getPath();
}else{
msg.arg1 = USB_STATE_OFF;
}
execactivity.mhandler.sendMessage(msg);
};
}
package com.example.usbtest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.view.Menu;
import android.widget.TextView;
public class MainActivity extends Activity {
MyHandler mhandler;
UsbStatesReceiver usbstates;
TextView Usb;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mhandler = new MyHandler();
usbstates = new UsbStatesReceiver(this);
Usb = (TextView)findViewById(R.id.usbstates);
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
usbstates.registerReceiver();
}
@Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
usbstates.unregisterReceiver();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
class MyHandler extends Handler{
public MyHandler(){};
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
System.out.println("=============mainactivity handler");
if(msg.arg1 == 0x00021) Usb.setText("Usb is mounted"+msg.obj.toString());
else if(msg.arg1 == 0x00022) Usb.setText("Usb is out");
}
}
}