我正在 android 中开发一个 Radio 应用程序,它将从 url 流式传输,并且在后台将显示进度对话框加载流,但显示 ANR。我正在使用媒体播放器服务来启动和停止。需要帮助。我使用过 asynctask 但无法获得解决方案。MainActivity.class
button_Play.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
new DownloadTask().execute();
}
});
class DownloadTask extends AsyncTask<Void, Void, Void>
{
@Override
protected void onPreExecute()
{
progressDialog = ProgressDialog.show(MainActivity.this , "Android Streaming
Player" , "Connecting to Stream..." , true , false);
Log.d("onPreExecute()----->" , "MainActivity.class");
super.onPreExecute();
}
@Override
protected Void doInBackground(Void... params)
{
Log.d("doInBackground()----->" , "MainActivity.class");
startService(new Intent(MainActivity.this , RadioService.class));
return null;
}
@Override
protected void onPostExecute(Void result)
{
Log.d("onPostExecute()----->" , "MainActivity.class");
progressDialog.dismiss();
super.onPostExecute(result);
}
}
Here is service class:
RadioService.class
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d("onStartCommand------->", "RadioService.class");
try
{
Log.d("MediaPlayer--->TRY BLOCK", "MediaPlayer");
URL url2 = new URL("http://141.139.35.23:8000");
URLConnection urlConnection = url2.openConnection();
player.setDataSource(urlConnection.getURL().toString());
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.prepare();
Log.d("MediaPlayer--->TRY BLOCK AFTER ASYNC", "MediaPlayer");
player.setOnPreparedListener(new OnPreparedListener()
{
@Override
public void onPrepared(MediaPlayer mp)
{
Log.d("MediaPlayer--->ON PREPARED BEGINS", "MediaPlayer");
//mp.setOnErrorListener(MainActivity.this);
mp.start();
//mp.setOnErrorListener(this);
mp.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
Toast.makeText(getApplicationContext() , "Streaming started " , Toast.LENGTH_SHORT).show();
Log.d("MediaPlayer--->ON PREPARED ENDS", "MediaPlayer");
}
});
} catch (Exception e)
{
Log.i("Exception", "Exception in streaming mediaplayer e = " + e);
}
return START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}