我写了一个函数来扫描音频文件的所有目录/文件,如果找到任何音频文件,它会被添加到媒体商店。因此,在扫描时我将目录/文件的路径设置为textview。单击按钮时会发生这一切。现在,问题是当我单击该按钮时,应用程序冻结了一段时间然后崩溃(尽管目录和文件的路径是在logcat中打印的)。我认为这是因为它是一个繁重的任务,它在主线程上运行。所以我尝试了:
1)创建一个新线程 2)在N秒后延迟处理程序并调用函数 3)使用AsyncTask
以上所有内容都导致了errora崩溃:
1)Reason: Input dispatching timed out (Waiting to send non-key event because the touched window has not finished processing certain input events that were delivered to it over 500.0ms ago. Wait queue length: 2. Wait queue head age: 12727.2ms.)
2)。 android.view.WindowManager$BadTokenException: Unable to add window -- token android.os.BinderProxy@e22c464 is not valid; is your activity running?
代码:
public void rescanForMedia(View view) {
AlertDialog.Builder rescanInit = new AlertDialog.Builder(this);
LayoutInflater layoutInflator = LayoutInflater.from(this);
View v = layoutInflator.inflate(R.layout.dialog_mediascanner, null);
rescanInit.setView(v);
Button mediaScanButton = v.findViewById(R.id.mediaScanButton);
mediaScaninitBox = rescanInit.create();
mediaScaninitBox.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
mediaScaninitBox.show();
mediaScanButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(SettingsActivity.this, "Scan Started", Toast.LENGTH_SHORT).show();
AlertDialog.Builder rescanRunningBox = new AlertDialog.Builder(SettingsActivity.this);
LayoutInflater layoutInflator = LayoutInflater.from(SettingsActivity.this);
View v = layoutInflator.inflate(R.layout.dialog_scanning, null);
rescanRunningBox.setView(v);
mediaScanRunningBox = rescanRunningBox.create();
mediaScanRunningBox.show();
scannedFiles = v.findViewById(R.id.scannedFiles);
mediaScaninitBox.dismiss();
walkDir(Environment.getExternalStorageDirectory());
}
});
}
public void walkDir(File file){
File[] files = file.listFiles();
if (files != null) {
for (final File filess : files) {
// checking the File is file or directory
// scannedFiles.setText(path);
if (filess.isFile()) {
path = filess.getAbsolutePath();
scannedFiles.setText(path);
// Log.v("Files: ",path);
MediaScannerConnection.scanFile(getApplicationContext(),
new String[]{path},
new String[]{"audio/*"},
new MediaScannerConnection.OnScanCompletedListener() {
public void onScanCompleted(String path, Uri uri) {
mediaScanRunningBox.dismiss();
}
});
}
else{
//if it is a directory
walkDir(filess);
}