我已经创建了Android应用程序来流式传输在线广播电台,我想在后台运行它使用service.How如何创建服务以在后台运行媒体播放器?
以下是该应用程序的源代码:
public class MainActivity extends AppCompatActivity
{
private ImageButton buttonPlay,buttonStop,buttonPause;
private String STREAM_URL = "http://178.149.86.162:8000/";
private MediaPlayer mPlayer;
Intent playbackServiceIntent;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
buttonPlay = (ImageButton) findViewById(R.id.buttonPlay);
buttonStop = (ImageButton) findViewById(R.id.buttonStopPlay);
buttonPause = (ImageButton) findViewById(R.id.buttonPause);
mPlayer = new MediaPlayer();
buttonPlay.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
try
{
mPlayer.reset();
mPlayer.setDataSource(STREAM_URL);
mPlayer.prepareAsync();
mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
@Override
public void onPrepared(MediaPlayer mp)
{
mPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
startService();
}
});
buttonStop.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
mPlayer.stop();
stopService();
}
});
buttonPause.setOnClickListener(new OnClickListener()
{
@Override
public void onClick(View v)
{
mPlayer.pause();
stopService();
}
});
playbackServiceIntent = new Intent(this, BackgroundService.class);
}
private void startService()
{
startService(new Intent(MainActivity.this,BackgroundService.class));
}
private void stopService()
{
stopService(new Intent(MainActivity.this,BackgroundService.class));
}
}
public class BackgroundService extends Service implements OnCompletionListener
{
MediaPlayer mediaPlayer;
private String STREAM_URL = "http://178.149.86.162:8000/";
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate()
{
mediaPlayer = new MediaPlayer();
try
{
mediaPlayer.setDataSource(STREAM_URL);
} catch (IOException e)
{
e.printStackTrace();
}
mediaPlayer.setOnCompletionListener(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
try
{
mediaPlayer.reset();
mediaPlayer.setDataSource(STREAM_URL);
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener()
{
@Override
public void onPrepared(MediaPlayer mp)
{
mediaPlayer.start();
}
});
} catch (IOException e)
{
e.printStackTrace();
}
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}