我正在尝试构建一个简单的应用程序来下载和播放音乐文件。我做了一个代码,但当试图测试它,应用程序冻结并显示'启动超时已过期,放弃唤醒锁'如果任何人有一个想法,请给我一点建议?以下是我的代码。下载时模拟器冻结
顺便说一句,我试图下载的示例文件大小约为9.1MB。
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
try {
setDataSource("http://cfs.tistory.com/custom/blog/66/661632/skin/images/Believe.mp3");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void setDataSource(String path) throws IOException {
URL url = new URL(path);
HttpURLConnection cn = (HttpURLConnection) url.openConnection();
cn.setRequestMethod("GET");
cn.setDoOutput(true);
cn.connect();
String file_path = Environment.getExternalStorageDirectory()+"/download/";
String fileName = "Temp.wav";
File file = new File(file_path);
file.mkdir();
InputStream is = cn.getInputStream();
File output_file = new File(file, fileName);
FileOutputStream fos = new FileOutputStream(output_file);
byte[] buffer = new byte[4096];
int read = 0;
while ((read = is.read(buffer)) > 0){
fos.write(buffer, 0, read);
}
is.close();
fos.close();
mp = new MediaPlayer();
mp.setDataSource(file_path+fileName);
mp.prepare();
mp.start();
}
}
**修改:**贾斯汀教我,如果我只是把它的onCreate(),然后它会导致一个问题。现在,我正在使用带有线程的按钮,但有另一个问题,说只有创建视图层次结构的原始线程可以触及其视图,看起来好像是在'fos.close'处发生的。如果有人知道该怎么做,你能帮我吗?
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) findViewById(R.id.tv1);
tv2 = (TextView) findViewById(R.id.tv2);
tv.setText(Environment.getExternalStorageDirectory()+"/download/");
Button btn = (Button) findViewById(R.id.button1);
btn.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
// TODO Auto-generated method stub
Thread thread;
Runnable r = new Runnable(){
public void run(){
try {
setDataSource("http://cfs.tistory.com/custom/blog/66/661632/skin/images/Believe.mp3");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
thread = new Thread(r);
thread.start();
}
});
}
**错误消息:**
07-15 04:31:45.321: ERROR/AndroidRuntime(313): android.view.ViewRoot$CalledFromWrongThreadException: Only the original thread that created a view hierarchy can touch its views.
谢谢贾斯汀和安妮 – June