【问题标题】:NetworkOnMainThreadException While read Audio temp file from cache [duplicate]NetworkOnMainThreadException 从缓存中读取音频临时文件[重复]
【发布时间】:2014-07-15 12:42:12
【问题描述】:

我尝试像这样从缓存中播放 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

我怎样才能在没有任何错误的情况下播放不在主线程中的临时文件?

【问题讨论】:

  • 如果要使用Service,请使用IntentService

标签: java android exception android-mediaplayer networkonmainthread


【解决方案1】:

裸服务不会自动为您启动后台线程,因此您的代码在应用程序主线程上运行,不应进行网络调用。开始使用服务的更好方法是扩展 IntentService,它会为您启动一个后台线程。

然后把你的代码放到handleIntent方法而不是onStartCommand方法中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多