Esqueci de dizer que quando o player para ocorre o erro:
current context mark for deletion.
2016-03-14 8:33 GMT-03:00 Willian do Amor <willsazon@gmail.com>:
Bom dia a todos,--estou desenvolvendo um media play para Streaming de uma web rádio usando o aacdecoder seguindo esses dois exemplos.Funciona perfeitamente até a Activity ser destruída. Quando a Activity é destruída o player para de receber os dados da url da rádio, como se o serviço estivesse parado, mas não está.Alguém pode dizer o que estou fazendo de errado?Será que é por que eu não achei o player.setWakeMode?Classe Principal.
package br.com.loadti.radio;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
/**
* Created by TI on 14/09/2015.
*/
public class Principal extends Activity {
Intent ServiceIntent;
private Button btnPlayer;
public boolean boolMusicPlayer = false;
private boolean isOnline = false;
private static final int NOTIFICATION_ID = 1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_principal);
inicializaComponentes();
/*Verifica se a internet esta conectada*/
isOnline = AndroidUtils.isNeworkAvailable(Principal.this);
/*Verifica se o serviço do player esta online*/
try {
if (isMyServiceRunning()) {
boolMusicPlayer = true;
Log.d("PlayerService", "boolMusicPlayerService " + boolMusicPlayer);
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getClass().getName() + " " + e.getMessage(), Toast.LENGTH_LONG).show();
}
Log.d("Principal", "OnCreate");
setListener();
mostrarDensidade();
ServiceIntent = new Intent(this, PlayerService.class);
}
/*Verifica se o serviço do Media Player da rádio liberdade está em execução*/
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
String STRmanager = (String) manager.toString();
Log.d("POW", "STRmanager = " + STRmanager);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if ("br.com.loadti.radio.liberdadefm.PlayerService".equals(service.service.getClassName())) {
Log.d("Principal", "Serviço liberdadeFM está em execução");
return true;
}
}
Log.d("Principal", "Serviço liberdadeFM não está em execução");
return false;
}
private void inicializaComponentes() {
if (!boolMusicPlayer) {
btnPlayer = (Button) findViewById(R.id.btnPlayer);
btnPlayer.setBackgroundResource(R.drawable.btn_play);
} else {
if (boolMusicPlayer) {
btnPlayer = (Button) findViewById(R.id.btnPlayer);
btnPlayer.setBackgroundResource(R.drawable.btn_pause);
}
}
}
private void setListener() {
btnPlayer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
btnPlayerStopClick();
}
});
}
private void btnPlayerStopClick() {
if (!boolMusicPlayer) {
if (isOnline) {
btnPlayer.setBackgroundResource(R.drawable.btn_pause);
playAudio();
boolMusicPlayer = true;
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("INFORMAÇÂO");
alertDialog.setMessage("Vi que você não está conectado a internet. Conecte-se para continuar-mos.");
alertDialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
btnPlayer.setBackgroundResource(R.drawable.btn_play);
AlertDialog alert = alertDialog.create();
alert.show();
}
} else {
if (boolMusicPlayer) {
btnPlayer.setBackgroundResource(R.drawable.btn_play);
stopPlayerService();
boolMusicPlayer = false;
}
}
}
private void mostrarDensidade() {
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
Log.i(getString(R.string.app_name), "densityDpi -> " + metric.densityDpi);
}
private void playAudio() {
/*Se a internet estiver conectada, chama o serviço para começar a transmitir o audio*/
if (isOnline) {
stopPlayerService();
try {
startService(ServiceIntent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getClass().getName() + " " + e.getMessage(), Toast.LENGTH_LONG).show();
}
} else {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(this);
alertDialog.setTitle("INFORMAÇÂO");
alertDialog.setMessage("Vi que você não está conectado a internet. Conecte-se para continuar-mos.");
alertDialog.setNeutralButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
btnPlayer.setBackgroundResource(R.drawable.btn_play);
AlertDialog alert = alertDialog.create();
alert.show();
}
}
private void stopPlayerService() {
/*Finaliza o servico*/
try {
stopService(ServiceIntent);
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(getApplicationContext(), e.getClass().getName() + " " + e.getMessage(), Toast.LENGTH_LONG).show();
}
boolMusicPlayer = false;
}
@Override
public void onBackPressed() {
super.onBackPressed();
if (!boolMusicPlayer) {
AlertDialog.Builder altSair = new AlertDialog.Builder(this);
altSair.setTitle("CONFIRMA");
altSair.setMessage("Poxa, você que mesmo ir embora?");
altSair.setPositiveButton("Sim", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(Principal.this, "Obrigado pela companhia. Volte logo.", Toast.LENGTH_LONG).show();
finish();
}
});
altSair.setNeutralButton("Não", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
AlertDialog alert = altSair.create();
alert.show();
} else {
if (boolMusicPlayer) {
AndroidUtils.criarNotificacao(this, NOTIFICATION_ID, Principal.class);
}
finish();
}
}
}Casse Player Service
Digite o código package br.com.loadti.radio;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.AudioTrack;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import com.spoledge.aacdecoder.MultiPlayer;
import com.spoledge.aacdecoder.PlayerCallback;
import radioservice.src.main.java.co.mobiwise.library.radio.StreamLinkDecoder;
/**
* Created by TI on 14/09/2015.
*/
public class PlayerService extends Service implements PlayerCallback {
/*Cria um novo media Player*/
private MultiPlayer player;
/*Cria uma instancia de Audio Manager para controlar o volume do player*/
/**
* Radio buffer and decode capacity(DEFAULT VALUES)
*/
private final int AUDIO_BUFFER_CAPACITY_MS = 800;
private final int AUDIO_DECODE_CAPACITY_MS = 400;
/*Variaveis para exibir notificacao*/
private static final int NOTIFICATION_ID = 1;
/*Verifica o status do telefone*/
private boolean isPauseInCall = false;
/**
* Will be controlled on incoming calls and stop and start player.
*/
private TelephonyManager mTelephonyManager;
/*Endereco do striming*/
private static final String urlRadio = "http://stm4.srvstm.com:16194";
/*Faz com que o wi-fi nao seja desligado pelo android*/
/**
* Stream url suffix
*/
private final String SUFFIX_PLS = ".pls";
private final String SUFFIX_RAM = ".ram";
private final String SUFFIX_WAX = ".wax";
/**
* State enum for Radio Player state (IDLE, PLAYING, STOPPED, INTERRUPTED)
*/
public enum State {
IDLE,
PLAYING,
STOPPED,
}
/**
* Radio State
*/
private State mRadioState;
/**
* While current radio playing, if you give another play command with different
* source, you need to stop it first. This value is responsible for control
* after radio stopped.
*/
private boolean isSwitching;
/**
* Incoming calls interrupt radio if it is playing.
* Check if this is true or not after hang up;
*/
private boolean isInterrupted;
/**
* If play method is called repeatedly, AAC Decoder will be failed.
* play and stop methods will be turned mLock = true when they called,
*
* @onRadioStarted and @onRadioStopped methods will be release lock.
*/
private boolean mLock;
//OnCreate
public void onCreate() {
Log.d("PlayerService", "onCreate Service");
mRadioState = State.IDLE;
isSwitching = false;
isInterrupted = false;
mLock = false;
getPlayer();
mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mTelephonyManager != null)
mTelephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
/*Inicializa o serviço*/
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("PlayerService", "Inicializando Listener");
if (isPlaying()) {
stop();
}
if (isPlaying())
stop();
else if (urlRadio != null)
play(urlRadio);
/*Metodo que inicializa a notificacao*/
//AndroidUtils.criarNotificacao(this, NOTIFICATION_ID, Principal_1.class);
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if (player != null) {
if (isPlaying()) {
player.stop();
}
/*Cancela a notificacao do aplicativo*/
cancelarNoficacao();
}
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
/*Cancela a notificacao do player Service*/
private void cancelarNoficacao() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager nNotificationManager = (NotificationManager) getSystemService(ns);
nNotificationManager.cancel(NOTIFICATION_ID);
}
@Override
public void playerStarted() {
mRadioState = State.PLAYING;
mLock = false;
Log.d("Player started. tate : ", " " + mRadioState);
if (isInterrupted)
isInterrupted = false;
}
public boolean isPlaying() {
if (State.PLAYING == mRadioState)
return true;
return false;
}
/**
* This method is called periodically by PCMFeed.
*
* @param isPlaying false means that the PCM data are being buffered,
* but the audio is not playing yet
* @param audioBufferSizeMs the buffered audio data expressed in milliseconds of playing
* @param audioBufferCapacityMs the total capacity of audio buffer expressed in milliseconds of playing
*/
public void playerPCMFeedBuffer(final boolean isPlaying,
final int audioBufferSizeMs, final int audioBufferCapacityMs) {
}
@Override
public void playerStopped(int i) {
mRadioState = State.STOPPED;
/**
* If player stopped from notification then dont
* call buildNotification().
*/
mLock = false;
Log.d("Player stopped. State :", " " + mRadioState);
if (isSwitching)
play(urlRadio);
}
@Override
public void playerException(Throwable throwable) {
mLock = false;
player = null;
getPlayer();
//notifyErrorOccured();
Log.d("PlayerService ", "Ocorreu um erro..");
}
/**
* Play url if different from previous streaming url.
*
* @param mRadioUrl
*/
public void play(String mRadioUrl) {
if (checkSuffix(mRadioUrl))
decodeStremLink(mRadioUrl);
else {
isSwitching = false;
if (isPlaying()) {
Log.d("Switching Radio", "PlayerService");
isSwitching = true;
stop();
} else if (!mLock) {
Log.d("Play requested.", "PlayerService");
mLock = true;
getPlayer().playAsync(mRadioUrl);
}
}
}
@Override
public void playerMetadata(String s, String s1) {
}
@Override
public void playerAudioTrackCreated(AudioTrack audioTrack) {
}
private void stop() {
if (player != null) {
player.stop();
player = null;
}
}
/**
* Return AAC player. If it is not initialized, creates and returns.
*
* @return MultiPlayer
*/
private MultiPlayer getPlayer() {
try {
java.net.URL.setURLStreamHandlerFactory(new java.net.URLStreamHandlerFactory() {
public java.net.URLStreamHandler createURLStreamHandler(String protocol) {
Log.d("LOG", "Asking for stream handler for protocol: '" + protocol + "'");
if ("icy".equals(protocol))
return new com.spoledge.aacdecoder.IcyURLStreamHandler();
return null;
}
});
} catch (Throwable t) {
Log.w("LOG", "Cannot set the ICY URLStreamHandler - maybe already set ? - " + t);
}
if (player == null) {
player = new MultiPlayer(this, AUDIO_BUFFER_CAPACITY_MS, AUDIO_DECODE_CAPACITY_MS);
player.setResponseCodeCheckEnabled(false);
player.setPlayerCallback(this);
}
return player;
}
PhoneStateListener phoneStateListener = new PhoneStateListener() {
@Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
/**
* Stop radio and set interrupted if it is playing on incoming call.
*/
if (isPlaying()) {
isInterrupted = true;
stop();
}
} else if (state == TelephonyManager.CALL_STATE_IDLE) {
/**
* Keep playing if it is interrupted.
*/
if (isInterrupted)
play(urlRadio);
} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
/**
* Stop radio and set interrupted if it is playing on outgoing call.
*/
if (isPlaying()) {
isInterrupted = true;
stop();
}
}
super.onCallStateChanged(state, incomingNumber);
}
};
/**
* If stream link is a file, then we
* call stream decoder to get HTTP stream link
* from that file.
*
* @param streamLink
*/
private void decodeStremLink(String streamLink) {
new StreamLinkDecoder(streamLink) {
@Override
protected void onPostExecute(String s) {
super.onPostExecute(s);
play(s);
}
}.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}
/**
* Check supported suffix
*
* @param streamUrl
* @return
*/
public boolean checkSuffix(String streamUrl) {
if (streamUrl.contains(SUFFIX_PLS) ||
streamUrl.contains(SUFFIX_RAM) ||
streamUrl.contains(SUFFIX_WAX))
return true;
else
return false;
}}aqui...
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.
0 comentários:
Postar um comentário