音楽ファイルをダウンロードして再生する簡単なアプリケーションを構築しようとしています。コードを作りましたが、テストしようとするとアプリケーションがフリーズして表示されます'起動時間切れが期限切れになって、スリープ解除を諦めてください'誰かがアイデアを持っていれば、少しアドバイスをお願いしますか?以下は私のコードです。ダウンロード中にエミュレータがフリーズする
ところで、私がダウンロードしようとしているサンプルファイルのサイズは約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.
ありがとう、Justin and anil – June