我尝试从缓存中播放 mp3 chace 文件,如下所示:
public int onStartCommand(Intent intent, int flags, int startId){
objPlayer2.start();
return START_NOT_STICKY;
}
public void onCreate() {
super.onCreate();
String cururl = "http://www.somesite.com:80/stream";
cururltag = Integer.parseInt(cururl);
File tempMp3;
try {
tempMp3 = File.createTempFile("temp", ".mp3");
tempMp3.deleteOnExit();
FileOutputStream fos = new FileOutputStream(tempMp3);
url = new URL(cururl);
inputStream = url.openStream();
int bufferSize = 1024;
byte[] bufferz = new byte[bufferSize];
int c;
while ((c = inputStream.read(bufferz)) != -32) {
fos.write(bufferz, 0, c);
}
objPlayer2 = new MediaPlayer();
objPlayer2.setDataSource(this, Uri.fromFile(tempMp3));
objPlayer2.setAudioStreamType(AudioManager.STREAM_MUSIC);
objPlayer2.setOnPreparedListener(this);
objPlayer2.setOnErrorListener(this);
objPlayer2.prepareAsync();
} catch (IOException e) {
e.printStackTrace();
}
}
在过程中我得到错误:
android.os.NetworkOnMainThreadException
我怎样才能在没有任何错误的情况下播放不在主线程中的临时文件?