Need help writing to internal storage - Android Q&A, Help & Troubleshooting

So i need to read a file from a URI and copy it into the internal storage. My function to write to external storage works fine but writing to internal storage has proven to be a difficult task. Nothing i do seems to work. Here's my code below. It doesn't throw any errors but it doesn't write anything.
Code:
public Uri selectedfile;
public void onActivityResult(int requestCode, int resultCode, Intent data) {
//this.onActivityResult(requestCode, resultCode, data);
if(requestCode==123 && resultCode==RESULT_OK) {
selectedfile = data.getData();
try {
InputStream in = getContentResolver().openInputStream(selectedfile);
FileOutputStream out = this.openFileOutput("myFile.txt", Context.MODE_PRIVATE);
out.write(in.toString().getBytes());
out.flush();
out.close();
in.close();
doToast("Success?");
} catch (IOException e) {
doToast(e.getMessage());
}
}
}

Related

[Q] Refer to TTS Object inside inner method.

Well... I am trying to create an application using the TTS Engine.
I can already make it, work, no problem. However I need my buttons to be dinamic, they will come from a database.
**So far you guys have helped me a lot, since now I can do it thanks to the tips I got from you guys.**
**Well.. now I am stuck again.**
Every new button that I create I attach an OnClickListener so it can start the TTS and speak something.
However it's an inner method, so, when I try to run the code below, it gives me a NullPointerException when it tries to "speak" using the TTS. I know the TTS object is out of context, so, **How can I solve this?**
Below the code. It's a little big since I wanted to include everything:
PLEASE JUMP TO THE "HERE IS MY PROBLEM!!!" comment so you guys can see exactly where my problem is. I know where it is, but I don't know how to solve it =(
Any help is appreciatted! =)
Code:
public class LivoxTesteActivity extends Activity implements OnInitListener{
/** Called when the activity is first created. */
private int MY_DATA_CHECK_CODE = 0;
public TextToSpeech tts;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
LinearLayout lgeral = new LinearLayout (this);
lgeral.setOrientation(LinearLayout.VERTICAL);
lgeral.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f));
String array[][] = {{"Comer","eat", "Eu quero comer", "1"},
{"Abraço","hug", "Eu quero um abraço", "2"},
{"Assustado","afraid", "Eu estou com medo", "3"},
{"Beber","drink", "Eu quero beber", "4"}};
int x = array.length;
int qtdeLinhas = 2;
for (int j = 0; j < qtdeLinhas; j++) {
LinearLayout l1 = new LinearLayout (this);
l1.setOrientation(LinearLayout.HORIZONTAL);
l1.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f));
FrameLayout fl;
for (int i = 0; i < array.length; i++) {
fl = (FrameLayout)LayoutInflater.from(getBaseContext()).inflate(R.layout.framelayoutstyle, l1, false);
TextView textoEscrito;
textoEscrito = (TextView)LayoutInflater.from(getBaseContext()).inflate(R.layout.textviewstyle, fl, false);
textoEscrito.setText(array[i][0]);
final String texto = textoEscrito.getText().toString();
final String textoFalar = array[i][2];
ImageButton btn;
btn = (ImageButton)LayoutInflater.from(getBaseContext()).inflate(R.layout.imagebuttonstyle, fl, false);
btn.setImageResource(this.getResources().getIdentifier("drawable/" + array[i][1], null, this.getPackageName()));
btn.setOnClickListener(new Button.OnClickListener(){
public void onClick (View v){
Toast.makeText(getBaseContext(), texto, Toast.LENGTH_SHORT).show();
//*******************************
//HERE IS MY PROBLEM!!!
//*******************************
tts.speak(txtFl, TextToSpeech.QUEUE_ADD, null);
//*******************************
//WHEN I TRY TO RUN THE ABOVE IT GIVES A NULLPOINTEREXCEPTION!!!
//*******************************
}
});
fl.addView(btn);
fl.addView(textoEscrito);
l1.addView(fl);
}
lgeral.addView(l1);
}
setContentView(lgeral);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
else {
// missing data, install it
Intent installIntent = new Intent();
installIntent.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
}
}
@Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
}
else if (status == TextToSpeech.ERROR) {
}
}
@Override
public void onDestroy() {
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
}
By the way... the method Toast.makeText(getBaseContext(), texto, Toast.LENGTH_SHORT).show(); works fine. I believe that's because the Toast is a static class.
So, maybe the solution is to create a static class with the method to speak? Ideas? How can I do it?
Questions or Problems Should Not Be Posted in the Development Forum
Please Post in the Correct Forums
Moving to Q&A

stranges with android mediaservice

I've got nexus 4 and have some issue with media servicem cause my MS could not find music on my internal SD card; So I make an app;
Code:
public class SingleMediaScanner implements MediaScannerConnectionClient {
private MediaScannerConnection mMs;
private File mFile;
public SingleMediaScanner(Context context, File f) {
mFile = f;
mMs = new MediaScannerConnection(context, this);
mMs.connect();
}
[user=439709]@override[/user]
public void onMediaScannerConnected() {
Log.v("MS", "connected");
mMs.scanFile(mFile.getAbsolutePath(), "audio/*");
Log.v("MS-file", mFile.getAbsolutePath());
}
[user=439709]@override[/user]
public void onScanCompleted(String path, Uri uri) {
mMs.disconnect();
}
}
Code:
File root = android.os.Environment.getExternalStorageDirectory();
File dir = new File (root.getAbsolutePath()+"/Music/");
for (int i=0;i<dir.listFiles().length;i++)
{
if (dir.listFiles()[i].isFile()==true&&dir.listFiles()[i].getName().endsWith(".mp3"))
{
new SingleMediaScanner(this, dir.listFiles()[i].getAbsoluteFile());
}
Log says that MS was connected and tried to scan media file, but file doesnt appear in Media library , what's the problem? by the way I have CM ROM

[HELP] Hard brick after writing to SD card!

Hello guys, I'd like to ask you for your wisdom and maybe a little help.
After using an application that writes to SD card, my I9100 was bricked. It won't turn on, won't react to power button or any combination (recovery/download mode). When I plug the power, nothing comes up on the screen. I tried jump-starting it and other tricks with the exception of USB jig. The phone is just dead and nothing comes up on screen.
Below I paste a code of the ran application. It writes an image to SD card. The program ran without any problems, but the image was not written. I suppose the dd program somehow wrote to the wrong section and thus bricked the phone. Could someone confirm?
The path to the SD Card was /dev/block/mmcblk0
After the reboot, the phone just went stone cold dead.
Code:
protected void writeImage()
{
// Verify that root access is obtainable
if (!execCommandAsRoot("true")) {
showMessage("Your device is not rooted. Cannot proceed.");
return;
}
// Verify that SD card device exists
File sdDevice = new File(editOutputDevice.getText().toString());
if (!sdDevice.exists()) {
showMessage("SD card device does not exist, or no card inserted");
return;
}
// Progress dialog
final Handler progressHandler = new Handler();
final ProgressDialog progress = new ProgressDialog(this);
progress.setCancelable(false);
progress.setMessage("Starting thread");
progress.show();
// Write image in worker thread
new Thread(new Runnable() {
public void run() {
String imagefile = editImageFile.getText().toString();
String sd = editOutputDevice.getText().toString();
String datadir = getFilesDir().getPath();
/* The image files need to be extracted from the .apk to the data folder
* unless the user has run the app before, and this has already been done.
* We store the version (lastUpdate timestamp) of the extracted files in the preferences.
*/
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
long berrybootVersion = -1;
try {
berrybootVersion = getPackageManager().getPackageInfo(getPackageName(), 0).lastUpdateTime;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if (!new File(datadir+"/a10-patchspl").exists()
|| preferences.getLong("berrybootimgversion", 0) != berrybootVersion)
{
updateProgress("Uncompressing files from .apk");
try {
uncompressFile("berryboot.img", datadir);
uncompressFile("sunxi-spl.bin", datadir);
uncompressFile("a10-patchspl", datadir);
new File(datadir+"/a10-patchspl").setExecutable(true);
new File(datadir+"/mntNand").mkdir();
new File(datadir+"/mntSD").mkdir();
preferences.edit().putLong("berrybootimgversion", berrybootVersion).commit();
} catch (IOException ie) {
error("Error uncompressing files. Check disk space.");
return;
}
}
updateProgress("Unmounting SD card");
execCommandAsRoot("umount "+sd);
execCommandAsRoot("umount "+sd+"p1");
/* Also unmount everything mounted to /mnt/extSdCard,
* as vold seems to mount /dev/vold/somedevice instead of /dev/block/mmcblk0p1 */
String[] extsdFolders = new File("/mnt/extSdCard").list();
for (String extsdFolder : extsdFolders)
{
execCommandAsRoot("umount /mnt/extSdCard/"+extsdFolder);
}
execCommandAsRoot("umount /mnt/extSdCard");
updateProgress("Writing image to SD card");
if (!execCommandAsRoot("dd 'if="+imagefile+"' of="+sd+" bs=1024k"))
{
error("Error writing image file to SD card");
return;
}
if (checkPatch.isChecked())
{
updateProgress("Patching u-boot SPL");
if (!execCommandAsRoot(datadir+"/a10-patchspl "+datadir+"/sunxi-spl.bin "+sd))
{
error("Error patching u-boot SPL");
return;
}
updateProgress("Copying script.bin from NAND to SD");
if (!execCommandAsRoot("mount -t vfat /dev/block/nanda "+datadir+"/mntNand"))
{
error("Error mounting /dev/block/nanda");
return;
}
if (!execCommandAsRoot("mount -t vfat "+sd+"p1 "+datadir+"/mntSD"))
{
error("Error mounting SD card device");
return;
}
String scriptbin;
if ( new File(datadir+"/mntNand/script.bin").exists() )
scriptbin = datadir+"/mntNand/script.bin";
else if ( new File(datadir+"/mntNand/evb.bin").exists() )
scriptbin = datadir+"/mntNand/evb.bin";
else
{
error("Neither script.bin nor evb.bin exists in NAND");
return;
}
if (!execCommandAsRoot("cat "+scriptbin+ " >"+datadir+"/mntSD/script.bin"))
{
error("Error copying "+scriptbin+" to SD");
return;
}
/* Save human readable a10-memdump info to a10-meminfo.txt on the SD card for debugging purposes */
execCommandAsRoot(datadir+"/a10-patchspl -dump > "+datadir+"/mntSD/a10-meminfo.txt");
if (!execCommandAsRoot("umount "+datadir+"/mntNand"))
{
error("Error unmounting /dev/block/nanda");
return;
}
if (!execCommandAsRoot("umount "+datadir+"/mntSD"))
{
error("Error unmounting SD card device");
return;
}
}
updateProgress("Finish writing... (sync)");
execCommandAsRoot("sync");
finished();
}
// Update the progress in the UI thread
protected void updateProgress(final String msg)
{
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.setMessage(msg);
}
});
}
// Show error in UI thread
protected void error(final String msg)
{
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.hide();
showMessage(msg);
}
});
}
// Notify UI thread we are finished
protected void finished() {
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.hide();
askReboot();
}
});
}
/*
* Uncompress utility file stored in .apk to datadir
*/
protected void uncompressFile(String filename, String dest) throws IOException
{
InputStream is = getAssets().open(filename);
OutputStream os = new FileOutputStream(dest+"/"+filename);
byte[] buf = new byte[4096];
int len;
while ((len =is.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.close();
is.close();
}
}).start(); // start thread
}
protected void showMessage(String msg)
{
new AlertDialog.Builder(this)
.setMessage(msg)
.setNeutralButton("Ok", null)
.create().show();
}
protected void askReboot()
{
/* Ask if user wants to reboot */
new AlertDialog.Builder(this)
.setMessage("All done! Reboot now?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
execCommandAsRoot("reboot");
}
})
.setNegativeButton("No", null)
.create().show();
}
protected boolean execCommandAsRoot(String path)
{
try {
String[] cmd = {"su","-c",path};
Process p = Runtime.getRuntime().exec(cmd);
int exitCode = p.waitFor();
return (exitCode == 0);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
If absolutely nothing comes on with the charger or even the power button your phone may truly be bricked. Are you sure you have tried everything? There may be hope yet.
Perhaps the only way is via the USB jig. Try that.
Sent from my ONE TOUCH 4033A using Tapatalk
Service centre = motherboard replacement. Try a jig, but very very unlikely to work.
Vexi said:
Hello guys, I'd like to ask you for your wisdom and maybe a little help.
After using an application that writes to SD card, my I9100 was bricked. It won't turn on, won't react to power button or any combination (recovery/download mode). When I plug the power, nothing comes up on the screen. I tried jump-starting it and other tricks with the exception of USB jig. The phone is just dead and nothing comes up on screen.
Below I paste a code of the ran application. It writes an image to SD card. The program ran without any problems, but the image was not written. I suppose the dd program somehow wrote to the wrong section and thus bricked the phone. Could someone confirm?
The path to the SD Card was /dev/block/mmcblk0
After the reboot, the phone just went stone cold dead.
Code:
protected void writeImage()
{
// Verify that root access is obtainable
if (!execCommandAsRoot("true")) {
showMessage("Your device is not rooted. Cannot proceed.");
return;
}
// Verify that SD card device exists
File sdDevice = new File(editOutputDevice.getText().toString());
if (!sdDevice.exists()) {
showMessage("SD card device does not exist, or no card inserted");
return;
}
// Progress dialog
final Handler progressHandler = new Handler();
final ProgressDialog progress = new ProgressDialog(this);
progress.setCancelable(false);
progress.setMessage("Starting thread");
progress.show();
// Write image in worker thread
new Thread(new Runnable() {
public void run() {
String imagefile = editImageFile.getText().toString();
String sd = editOutputDevice.getText().toString();
String datadir = getFilesDir().getPath();
/* The image files need to be extracted from the .apk to the data folder
* unless the user has run the app before, and this has already been done.
* We store the version (lastUpdate timestamp) of the extracted files in the preferences.
*/
SharedPreferences preferences = getPreferences(MODE_PRIVATE);
long berrybootVersion = -1;
try {
berrybootVersion = getPackageManager().getPackageInfo(getPackageName(), 0).lastUpdateTime;
} catch (NameNotFoundException e) {
e.printStackTrace();
}
if (!new File(datadir+"/a10-patchspl").exists()
|| preferences.getLong("berrybootimgversion", 0) != berrybootVersion)
{
updateProgress("Uncompressing files from .apk");
try {
uncompressFile("berryboot.img", datadir);
uncompressFile("sunxi-spl.bin", datadir);
uncompressFile("a10-patchspl", datadir);
new File(datadir+"/a10-patchspl").setExecutable(true);
new File(datadir+"/mntNand").mkdir();
new File(datadir+"/mntSD").mkdir();
preferences.edit().putLong("berrybootimgversion", berrybootVersion).commit();
} catch (IOException ie) {
error("Error uncompressing files. Check disk space.");
return;
}
}
updateProgress("Unmounting SD card");
execCommandAsRoot("umount "+sd);
execCommandAsRoot("umount "+sd+"p1");
/* Also unmount everything mounted to /mnt/extSdCard,
* as vold seems to mount /dev/vold/somedevice instead of /dev/block/mmcblk0p1 */
String[] extsdFolders = new File("/mnt/extSdCard").list();
for (String extsdFolder : extsdFolders)
{
execCommandAsRoot("umount /mnt/extSdCard/"+extsdFolder);
}
execCommandAsRoot("umount /mnt/extSdCard");
updateProgress("Writing image to SD card");
if (!execCommandAsRoot("dd 'if="+imagefile+"' of="+sd+" bs=1024k"))
{
error("Error writing image file to SD card");
return;
}
if (checkPatch.isChecked())
{
updateProgress("Patching u-boot SPL");
if (!execCommandAsRoot(datadir+"/a10-patchspl "+datadir+"/sunxi-spl.bin "+sd))
{
error("Error patching u-boot SPL");
return;
}
updateProgress("Copying script.bin from NAND to SD");
if (!execCommandAsRoot("mount -t vfat /dev/block/nanda "+datadir+"/mntNand"))
{
error("Error mounting /dev/block/nanda");
return;
}
if (!execCommandAsRoot("mount -t vfat "+sd+"p1 "+datadir+"/mntSD"))
{
error("Error mounting SD card device");
return;
}
String scriptbin;
if ( new File(datadir+"/mntNand/script.bin").exists() )
scriptbin = datadir+"/mntNand/script.bin";
else if ( new File(datadir+"/mntNand/evb.bin").exists() )
scriptbin = datadir+"/mntNand/evb.bin";
else
{
error("Neither script.bin nor evb.bin exists in NAND");
return;
}
if (!execCommandAsRoot("cat "+scriptbin+ " >"+datadir+"/mntSD/script.bin"))
{
error("Error copying "+scriptbin+" to SD");
return;
}
/* Save human readable a10-memdump info to a10-meminfo.txt on the SD card for debugging purposes */
execCommandAsRoot(datadir+"/a10-patchspl -dump > "+datadir+"/mntSD/a10-meminfo.txt");
if (!execCommandAsRoot("umount "+datadir+"/mntNand"))
{
error("Error unmounting /dev/block/nanda");
return;
}
if (!execCommandAsRoot("umount "+datadir+"/mntSD"))
{
error("Error unmounting SD card device");
return;
}
}
updateProgress("Finish writing... (sync)");
execCommandAsRoot("sync");
finished();
}
// Update the progress in the UI thread
protected void updateProgress(final String msg)
{
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.setMessage(msg);
}
});
}
// Show error in UI thread
protected void error(final String msg)
{
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.hide();
showMessage(msg);
}
});
}
// Notify UI thread we are finished
protected void finished() {
progressHandler.post(new Runnable() {
@Override
public void run() {
progress.hide();
askReboot();
}
});
}
/*
* Uncompress utility file stored in .apk to datadir
*/
protected void uncompressFile(String filename, String dest) throws IOException
{
InputStream is = getAssets().open(filename);
OutputStream os = new FileOutputStream(dest+"/"+filename);
byte[] buf = new byte[4096];
int len;
while ((len =is.read(buf)) > 0) {
os.write(buf, 0, len);
}
os.close();
is.close();
}
}).start(); // start thread
}
protected void showMessage(String msg)
{
new AlertDialog.Builder(this)
.setMessage(msg)
.setNeutralButton("Ok", null)
.create().show();
}
protected void askReboot()
{
/* Ask if user wants to reboot */
new AlertDialog.Builder(this)
.setMessage("All done! Reboot now?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
execCommandAsRoot("reboot");
}
})
.setNegativeButton("No", null)
.create().show();
}
protected boolean execCommandAsRoot(String path)
{
try {
String[] cmd = {"su","-c",path};
Process p = Runtime.getRuntime().exec(cmd);
int exitCode = p.waitFor();
return (exitCode == 0);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
}
Click to expand...
Click to collapse
Take your phone to local repair mobile shop.... and asks for POWER IC replacement( if there is problem in it.. ask him to check for it)
or motherboard replacement..
If your finally decision is motherboard replacement.. then in mean time do this on your motherboard may be it'll work :
check out this link-
http://forum.gsmhosting.com/vbb/f258/samsung-galaxy-s2-i9100-short-circuit-solution-1537757/
If your hand are handy to these things you can do it yourself otherwise Ask an technician to do this...
And
Let us know what will happen
Do you think JTAG / RIFF Box will help anything in this situation?
Vexi said:
Do you think JTAG / RIFF Box will help anything in this situation?
Click to expand...
Click to collapse
It doesn't guarantee your phone will be repaired or not.. BUT yes you can give it a chance...
Very very unlikely to work. Don't go out and buy one, put it that way.

Problems with saving photo from Camera

HI developers,
sorry for my bad English. I'm German.
i want to save the full-size image of the Camera into a file but my algorithm doesn't create the file. I read many tutorials about saving full-size photo and also threads with similar problems but they didn't work.
Here is my code. Does anyone know where's the problem?
After the file is saved on the internal storage it's copied into the server (XAMPP). When I create the file only with the thumbnail data it works.
Code:
private void makePhotoClick() {
try {
photoFile = new File(getFilesDir(), "test.jpg");
imageURI = Uri.fromFile(photoFile);
Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageURI);
startActivityForResult(takePictureIntent, 1);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
if (requestCode == 1 && resultCode == RESULT_OK) {
//Intent i=new Intent(Intent.ACTION_VIEW);
BitmapFactory.decodeFile(photoFile.getAbsolutePath()); // it also returns null
}
}
Print 'photoFile.getAbsolutePath()' on logcat console. Open Android Device Monitor (Tools -> Android -> Android Device Monitor) and check if file was created.
You can check also if file was created programmatically:
Code:
photoFile.exists()

Someone can tell me why it wouldn't show USB disk mount after I first read USB disk message?

My OS: Android9
Fuction: Showing USB disk's images and copy images to this device when I insert the usb disk
My question:
1.It can read the disk's path and name when I first insert the usb disk, but I can't showing the image from the disk whether using setImageBitmap(bitmap) and setImageURI(uri) of ImageView control
2.It can't show the path on the adb : /mnt/media_rw/, in commont it is will show the usb disk's name , like this: mnt/media_rw/20D3-1E69
my code is below, someone can help me , thanks!
Java:
public class TestActivity2 extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
activityLoginBinding = ActivityLoginBinding.inflate(LayoutInflater.from(this));
setContentView(activityLoginBinding.getRoot());
activityLoginBinding.button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
sendBroadcast(new Intent(ACTION_USB_PERMISSION));
}
});
}
/**
* 读取u盘文件
* @param device UsbMassStorageDevice实例对象
*/
private void readAllPicFromUSB(UsbMassStorageDevice device) {
// listImageUSBInfo.clear(); //清空list初始化
try { //遍历文件名
device.init();
// 设备分区
partition = device.getPartitions().get(0);
// 文件系统
currentFs = partition.getFileSystem();
// 获取 U 盘的根目录
mRootFolder = currentFs.getRootDirectory();
readAllPicFromUSB(mRootFolder,currentFs); //递归读取文件
Log.i(TAG, "picSize:" + picSize);
Log.i(TAG,"all pic count:" + picCount + ",all size:" + (long)(picSize / 1024) + "M"); //单位大小为M
picCount = 0; //归零
//所有文件加入list后通知livew刷新
Log.i(TAG,"list size----------------" + listImageUSBInfo.size());
sendBroadcast(new Intent(ACTION_USB_UPDATE_LISTVIEW));
//
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG, "readDevice error:" + e.toString());
}
return;
}
/**
* 获取 U盘读写权限的申请
* @param context 上下文对象
*/
private void permissionRequest(Context context) {
Log.i(TAG,"开始申请设备权限");
try {
// 设备管理器
UsbManager usbManager = (UsbManager) context.getSystemService(Context.USB_SERVICE);
// 获取 U 盘存储设备
UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(context.getApplicationContext());
PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(),
0, new Intent(ACTION_USB_PERMISSION), 0);
if(storageDevices.length == 0){
Log.i(TAG,"请插入可用的 U 盘");
}else{
//可能有几个 一般只有一个 因为大部分手机只有1个otg插口
for (UsbMassStorageDevice device : storageDevices) {
if (usbManager.hasPermission(device.getUsbDevice())) {
Log.i(TAG,"USB已经获取权限");
} else {//无权限申请权限
usbManager.requestPermission(device.getUsbDevice(), pendingIntent);
}
}
}
} catch (Exception e) {
Log.i(TAG,"申请权限异常:" +e.toString());
}
}//end permissionRequest
/**
* USBDevice 转换成UsbMassStorageDevice 对象
* @param usbDevice UsbDevice对象
*/
private UsbMassStorageDevice getUsbMass(UsbDevice usbDevice) {
UsbMassStorageDevice[] storageDevices = UsbMassStorageDevice.getMassStorageDevices(mContext);
for (UsbMassStorageDevice device : storageDevices) {
if (usbDevice.equals(device.getUsbDevice())) {
return device;
}
}
return null;
}//end
@Override
protected void onResume() {
super.onResume();
initUSBService();
Log.i(TAG,"enter onResume");
}//end onresume
@Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(usbBroadcast); //注销广播
}
private void initUSBService() { //初始化广播监听器
usbDeviceStateFilter = new IntentFilter();
usbDeviceStateFilter.addAction(ACTION_USB_IN);
usbDeviceStateFilter.addAction(ACTION_USB_OUT);
usbDeviceStateFilter.addAction(ACTION_USB_PERMISSION);
usbDeviceStateFilter.addAction(ACTION_USB_UPDATE_LISTVIEW);
registerReceiver(usbBroadcast,usbDeviceStateFilter);
}
/**
* 广播监听u盘拔插情况
*/
private BroadcastReceiver usbBroadcast = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
mContext=context;
String action=intent.getAction();
switch (action){
case ACTION_USB_PERMISSION: //自定义广播读取u盘文件
try {
UsbDevice usbDevice = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED,
false)){
Log.i(TAG,"已经有权限111111111111");
if (usbDevice != null) {
readAllPicFromUSB(getUsbMass(usbDevice)); //读取u盘文件
}
else
Log.i(TAG,"没有插入U盘");
}else {
Log.i(TAG,"没有获取读写权限!,开始获取22222222222222");
permissionRequest(mContext); //获取权限
}
}catch (Exception e){
Log.i(TAG, "ACTION_USB_PERMISSION error:" + e.toString());
}
break;
case ACTION_USB_IN:
Log.i(TAG, "插入了u盘");
break;
case ACTION_USB_OUT:
Log.i(TAG,"拔出了u盘");
break;
}
}
};
/**
* 获取本机设备读写权限
*/
private static String[] PERMISSIONS_STORAGE = {
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.WRITE_EXTERNAL_STORAGE};
private static int REQUEST_PERMISSION_CODE = 1;
private int ANDROID_VERSION_CURRENT = Build.VERSION.SDK_INT;
private void requestReadAndWriteAccess() {
Log.i(TAG,"now android version is :" + ANDROID_VERSION_CURRENT);
if (ANDROID_VERSION_CURRENT > Build.VERSION_CODES.LOLLIPOP){
if(ActivityCompat.checkSelfPermission(TestActivity2.this, Manifest.permission.WRITE_EXTERNAL_STORAGE)!=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(TestActivity2.this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
Log.i(TAG,"已经获取读写权限");
}
}
}//end requestReadAndWriteAccess
/**
* 递归读取u盘文件图片文件
* @param usbFile 根文件夹
* @param fileSystem 文件系统
*/
private void readAllPicFromUSB(UsbFile usbFile, FileSystem fileSystem) {
try {
long tmp = 0;
String imgPath = "";
String imgName = "";
UsbFile[] usbFileList = usbFile.listFiles();
for (UsbFile usbFileItem:usbFileList){
if (!usbFileItem.isDirectory()){
String FileEnd = usbFileItem.getName().substring(usbFileItem.getName().lastIndexOf(".") + 1,
usbFileItem.getName().length()).toLowerCase(); //后缀名
if(FileEnd.equals("jpg") || FileEnd.equals("png") || FileEnd.equals("gif")
|| FileEnd.equals("jpeg")|| FileEnd.equals("bmp")){ //过滤出照片
tmp = usbFileItem.getLength() / 1024;
imgPath = USB_PATH_PREFIX + usbFileItem.getAbsolutePath(); //需要绝对地址
imgName = usbFileItem.getName();
Log.i(TAG,"img name:" + imgName + ",path:" + imgPath + ",size:" + tmp + "K");
picCount++;
picSize += tmp; //大小为K
// 加入到list
listImageUSBInfo.add(new ImageInfo(imgPath,imgName));
}
}else
readAllPicFromUSB(usbFileItem,fileSystem);
}
} catch (Exception e) {
e.printStackTrace();
Log.i(TAG,"readDevice error:"+e.toString());
}
}//end
}

Categories

Resources