sd表示是SATA硬盘. a表示第一个硬盘 后面的数字是表示硬盘里的分区. |
public class USBStatesReceiver extends BroadcastReceiver {
public Intent registerReceiver(Context context) {
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_MEDIA_CHECKING);//表明对象正在磁盘检查
filter.addAction(Intent.ACTION_MEDIA_MOUNTED);//表明sd对象是存在并具有读/写权限
filter.addAction(Intent.ACTION_MEDIA_EJECT);//物理的拔出 SDCARD
filter.addAction(Intent.ACTION_MEDIA_REMOVED);//完全拔出
filter.addDataScheme("file");
return context.registerReceiver(this, filter);
}
public void unregisterReceiver(Context context) {
context.unregisterReceiver(this);
}
@Override
public void onReceive(Context context, Intent intent) {
Editor editor = context.getSharedPreferences(Constants.TAG_KV_CACHE, Context.MODE_PRIVATE).edit();
if (intent.getAction().equals(Intent.ACTION_MEDIA_MOUNTED) ) {
editor.putString(Constants.USB_PATH, intent.getData().getPath());
} else {
editor.putString(Constants.USB_PATH, "");
}
editor.commit();
};
}
package com.example.storageusbtest;
import java.io.File;
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
import com.example.stbusbtest.R;
public class StorageMainActivity extends Activity{
public TextView usbstates;
public File file;
public String[] string;
MyThread thread;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.storage_main);
usbstates = (TextView)findViewById(R.id.storageusbstates);
file = new File("/sdcard/video/");
string = file.list();
thread = new MyThread();
}
@Override
protected void onStart() {
// TODO Auto-generated method stub
File[] rootfile;
rootfile = File.listRoots();
for(String str:string){
System.out.println("------------------"+str);
}
super.onStart();
thread.start();
}
class MyThread extends Thread{
public MyThread(){};
@Override
public void run() {
// TODO Auto-generated method stub
super.run();
System.out.println("=====================start test:"+string.length);
usbstates.setText("hahaha");
while (true) {
String[] string1 = file.list();
boolean sign = false;
if (string1.length > string.length) {
for (int i = string1.length -1; i >= 0; i--) {
sign = false;
for(int j = string.length -1; j >= 0; j--) {
if(string1[i].equals(string[j])) {
sign = true;
}
}
if (sign == false) {
usbstates.setText("插入盘符:"+string1[i].toString());
}
}
string=file.list();//更新roots
} else {
for (int i = string.length - 1;i >= 0; i--) {
sign = false;
for(int j = string1.length- 1; j >= 0; j--) {
if(string1[j].equals(string[i])) {
sign = true;
}
}
if (sign == false) {
usbstates.setText("退出盘符:"+string[i].toString());
}
}
string=file.list();//更新roots
}
try {
sleep(1000);
} catch (InterruptedException ex) {
}
}
}
}
}