Tecnologia do Blogger.
RSS

Re: [androidbrasil-dev] Re: Ajuda com multithreading para tentar entender o que acontece num cenário específico de streaming com a lib AACDecoder

Essa exceção android.os.NetworkOnMainThreadException indica que o aplicativo tentou executar uma operação de rede no thread principal do sistema e não em um thread secundário, que seria o mais apropriado (o thread principal, também chamado de thread de UI, é responsável por atualizar a tela e portanto não deve ser ocupado com esse tipo de operação demorada sob pena do aplicativo deixar de responder ao usuário). Thread secundário é qualquer thread que não seja o thread principal.

No caso o que aconteceu foi que o seu handler solicitou ao thread principal para executar o método MultiPlayer.play(String url), que tenta acessar uma URL. Provavelmente você está declarando esse handler assim: 

handler = new Handler(Looper.getMainLooper()) {  ...
Isso faz o handler executar código no thread principal. A questão então é, como criar um handler que execute em um thread secundário? Bem, a má notícia é que eu pessoalmente nunca tentei fazer isso, então não sei exatamente como se faz. :( Mas o conhecimento para se fazer isso passa pelas seguintes ideias: um thread pode ser preparado para ficar em loop, tendo uma fila de mensagens associada a ele e executando em sequência cada uma dessas mensagens (que são essencialmente trechos de código que você deseja executar, ou seja, Runnables; a diferença entre uma mensagem e um Runnable é que a mensagem guarda a referência a algum objeto que é importante para o código que vai ser executado; mas se um Runnable resolve o seu problema, use-o chamando handler.post() no lugar de handler.sendMessage()). O thread principal por exemplo fica em loop, por isso um handler declarado como você declarou pode incluir mensagens na fila desse thread. Já um thread secundário precisa ser "preparado" para ficar em loop e ter sua fila de mensagens.

Encontrei a classe HandlerThread que auxilia na criação de um thread em loop. Ela é usada assim:

HandlerThread ht = new HandlerThread();
ht.start();
Hander handler = new Handler(ht.getLooper());
handler.post(...);

Declare a variável handler como de instância ou global, para que você possa utilizá-la em várias partes do código.

Para mais detalhes, essas duas mensagens no stackoverflow podem ajudar:

Espero ter ajudado.

Rodrigo

On Wed, Aug 19, 2015 at 11:03 AM, Matheus Henrique da Silva <matheustargaryen@gmail.com> wrote:
Complementando, agora estou usando incializando um handler no onStartCommand() e utilizando ele pra mandar os comandos:

public void playPlayer() {
        stopPlayer
();

        mPlayerHandler
.post(new Runnable() {
           
@Override
           
public void run() {

               
try {
                    mPlayer
= new MultiPlayer(MyService.this, MultiPlayer.DEFAULT_AUDIO_BUFFER_CAPACITY_MS, MultiPlayer.DEFAULT_DECODE_BUFFER_CAPACITY_MS);
                    mPlayer
.play(getResources().getString(R.string.url_streaming));

                   
String stringTimeLimit = PreferenceManager.getDefaultSharedPreferences(MyService.this)
                           
.getString(getResources().getString(R.string.PREFKEY_LIMITCONNECTION), "10");

                   
int limit = Integer.parseInt(stringTimeLimit);

                    startTimeLimitCountDown
(limit);

               
} catch (Exception e) {
                    e
.printStackTrace();

                    playerException
(null);
               
}


           
}
       
});


   
}

   
public void stopPlayer() {

        mPlayerHandler
.post(new Runnable() {
           
@Override
           
public void run() {

               
if (mPlayer != null) {
                    mPlayer
.stop();
               
}

           
}
       
});

   
}

Mas ao tentar dar play estou recebendo no logcat:

08-19 10:59:28.229  31666-31666/com.informatheus.webradiosertaovibe W/System.err android.os.NetworkOnMainThreadException
08-19 10:59:28.229  31666-31666/com.informatheus.webradiosertaovibe W/System.err at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1147)
08-19 10:59:28.229  31666-31666/com.informatheus.webradiosertaovibe W/System.err at java.net.InetAddress.lookupHostByName(InetAddress.java:418)
08-19 10:59:28.229  31666-31666/com.informatheus.webradiosertaovibe W/System.err at java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
08-19 10:59:28.229  31666-31666/com.informatheus.webradiosertaovibe W/System.err at java.net.InetAddress.getAllByName(InetAddress.java:215)
08-19 10:59:28.229  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.android.okhttp.HostResolver$1.getAllByName(HostResolver.java:29)
08-19 10:59:28.229  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.android.okhttp.internal.http.RouteSelector.resetNextInetSocketAddress(RouteSelector.java:232)
08-19 10:59:28.229  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.android.okhttp.internal.http.RouteSelector.next(RouteSelector.java:124)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:272)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:211)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:382)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:106)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.spoledge.aacdecoder.AACPlayer.openConnection(AACPlayer.java:551)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.spoledge.aacdecoder.AACPlayer.play(AACPlayer.java:328)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.spoledge.aacdecoder.AACPlayer.play(AACPlayer.java:313)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.informatheus.webradiosertaovibe.service.MyService$1.run(MyService.java:135)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at android.os.Handler.handleCallback(Handler.java:739)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at android.os.Handler.dispatchMessage(Handler.java:95)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at android.os.Looper.loop(Looper.java:135)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at android.app.ActivityThread.main(ActivityThread.java:5254)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at java.lang.reflect.Method.invoke(Native Method)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at java.lang.reflect.Method.invoke(Method.java:372)
08-19 10:59:28.230  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:903)
08-19 10:59:28.231  31666-31666/com.informatheus.webradiosertaovibe W/System.err at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:698)



--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

--
You received this message because you are subscribed to the Google Groups "Android Brasil - Dev" group.
To unsubscribe from this group and stop receiving emails from it, send an email to androidbrasil-dev+unsubscribe@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

  • Digg
  • Del.icio.us
  • StumbleUpon
  • Reddit
  • RSS

0 comentários:

Postar um comentário