I'm new to Android and I'm trying to make a really simple app. Its just one activity which contains a MediaPlayer for playing audio or video files.
I managed to play a song, but it just won't show me the control elements of the media player!
Here is the code I am using:
public class Player extends Activity implements OnPreparedListener,
MediaPlayerControl {
private static final String TAG = "AudioPlayer";
public static final String AUDIO_FILE_NAME = "audioFileName";
private String audioFile;
private MediaPlayer mediaPlayer;
private Handler handler = new Handler();
private MediaController mediaController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
Uri myUri = Uri.parse("android.resource://com.example.mediaplayer/"
+ R.raw.lied); // initialize Uri here
MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaController = new MediaController(this);
try {
mediaPlayer.setDataSource(getApplicationContext(), myUri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.player, menu);
return true;
}
public void onPrepared(MediaPlayer mediaPlayer) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.mediaController1));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
protected void onStop() {
super.onStop();
mediaPlayer.stop();
mediaPlayer.release();
}
public boolean onTouchEvent(MotionEvent event) {
// the MediaController will hide after 3 seconds - tap the screen to
// make it appear again
mediaController.show();
return false;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
public int getBufferPercentage() {
return 0;
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public void pause() {
mediaPlayer.pause();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public void start() {
mediaPlayer.start();
}
}
And here is my Layout XML:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context=".Player" >
<MediaController
android:id="#+id/mediaController1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:layout_marginLeft="122dp"
android:layout_marginTop="55dp"
android:visibility="visible" >
</MediaController>
<VideoView
android:id="#+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
I think what your looking for is a videoview in Android. It has default controls when playing media.
Create a videoview in your XML layout folder like this:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<VideoView
android:id="#+id/myvideoview"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
Let's say you called that file main.xml
Now create an activity called MediaViewerTest.java like this:
public class MediaViewerTest extends Activity {
String SrcPath = http://myMediaFile.mp3"; // or however your getting your media source, im assuming web here
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
VideoView myVideoView = (VideoView)findViewById(R.id.myvideoview);
myVideoView.setVideoURI(Uri.parse(SrcPath));
myVideoView.setMediaController(new MediaController(this));
myVideoView.requestFocus();
myVideoView.start();
}
}
Related
I have bit of trouble playing back video in my app. I have the very similar code as below playing back my audio files, however, when I try to play video I'm not seeing a picture, I can still hear the narration but no video. Just to exclude encoding, I dropped in my assets a file from my cell that was created on my cell and I was trying to play it back using the above method without luck. Any thoughts would be appreciated, Thank you.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/main_audio_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:orientation="vertical">
<VideoView
android:layout_weight="0.3"
android:id="#+id/videoView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
/>
<ListView
android:id="#+id/fragmentVidListView"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ListView>
public class MediaPlayer extends AppCompatActivity implements OnPreparedListener, MediaController.MediaPlayerControl {
private static final String TAG = "VideoPlayer";
private android.media.MediaPlayer mediaPlayer;
private MediaController mediaController;
private String videoFileName= "test2.mp4";
private Handler handler = new Handler();
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_video_view);
mediaPlayer = new android.media.MediaPlayer();
mediaPlayer.setOnPreparedListener(this);
mediaController = new MediaController(this);
try {
AssetFileDescriptor descriptor = MediaPlayer.this.getAssets().openFd(videoFileName);
long start = descriptor.getStartOffset();
long end = descriptor.getLength();
mediaPlayer.setDataSource(descriptor.getFileDescriptor(), start, end);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (IOException e) {
Log.e(TAG, "Could not open file " + videoFileName + " for playback.", e);
}
}
#Override
public void onPrepared(android.media.MediaPlayer mp) {
Log.d(TAG, "onPrepared");
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(findViewById(R.id.videoView1));
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
#Override
protected void onStop() {
super.onStop();
mediaController.hide();
}
#Override
public boolean onTouchEvent(MotionEvent event) { //the MediaController will hide after 3 seconds - tap the screen to make it appear again
mediaController.show();
return false;
}
public void start() {
mediaPlayer.start();
}
public void pause() {
mediaPlayer.pause();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
#Override
public void onStart() {
super.onStart();
}
}
This code is to read a mp3 from raw folder,But I want to change my mp3 file to another file from sd card
its new code, music played but seekbar does not work properly, when i toch it seekbar come back to frist position
public class MainActivity extends Activity implements OnClickListener {
SeekBar seek_bar;
Button play_button, pause_button;
MediaPlayer mediaPlayer;
TextView text_shown;
Handler seekHandler = new Handler();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
getInit();
seekUpdation();
}
public void getInit() {
seek_bar = (SeekBar) findViewById(R.id.seek_bar);
play_button = (Button) findViewById(R.id.play_button);
pause_button = (Button) findViewById(R.id.pause_button);
text_shown = (TextView) findViewById(R.id.text_shown);
play_button.setOnClickListener(this);
pause_button.setOnClickListener(this);
String filePath = Environment.getExternalStorageDirectory() + "/Android/music.mp3";
mediaPlayer = new MediaPlayer();
try {
mediaPlayer.setDataSource(filePath);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
}
});
mediaPlayer.prepareAsync();
seek_bar.setMax(mediaPlayer.getDuration());
}
Runnable run = new Runnable() {
#Override
public void run() {
seekUpdation();
}
};
public void seekUpdation() {
seek_bar.setProgress(mediaPlayer.getCurrentPosition());
seekHandler.postDelayed(run, 1000);
seek_bar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seek_bar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seek_bar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
seek_bar.setProgress(progress);
}
}
});
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_button:
text_shown.setText("Playing...");
mediaPlayer.start();
break;
case R.id.pause_button:
mediaPlayer.pause();
text_shown.setText("Paused...");
}
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(fromUser){
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onBackPressed() {
mediaPlayer.stop();
finish();
}
}
Just move this line
seek_bar.setMax(mediaPlayer.getDuration());
to seekUpdation() after
seekHandler.postDelayed(run, 1000);
Replace
mediaPlayer = MediaPlayer.create(this, R.raw.my_file);
with:
String filePath = Environment.getExternalStorageDirectory() + "/randomDirectory/yourFile.mp3";
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(filePath);
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
I'm using a media controller associated with a media player to play a sound. The issue is that the media controller is hiding as soon as it loses focus. I have a button which when pressed, the sound is played and the media controller shows up at the bottom of the screen.
But when life pause is pressed, after like 5 seconds, the media controller itself hides.
here are part of my codes. I'm stopping the media player as soon as the media controller hides so that the sound is not continually played
All the codes for the media controller are:
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnPreparedListener(currentFragment);
mediaController = new MediaController(getActivity()){
#Override
public void hide()
{
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
super.hide();
}
};
try {
mediaPlayer.setDataSource(sound.getSound());
mediaPlayer.prepareAsync();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
#Override
public void onPrepared(MediaPlayer mp) {
Log.d("media status", "onPrepared");
handler.post(new Runnable() {
public void run() {
launchMediaController();
progress.dismiss();
}
});
}
void launchMediaController(){
mediaController.setEnabled(true);
mediaPlayer.start();
mediaController.setMediaPlayer(soundController);
mediaController.setAnchorView(getView());
mediaController.show(0);
}
private class SoundController implements MediaController.MediaPlayerControl{
public void start() {
mediaPlayer.start();
}
public void pause() {
mediaPlayer.pause();
}
public int getDuration() {
return mediaPlayer.getDuration();
}
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
public void seekTo(int i) {
mediaPlayer.seekTo(i);
}
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
public int getBufferPercentage() {
return 0;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
// TODO Auto-generated method stub
return 0;
}
}
Edits:
Based on the answer of Libin, I did the following with no success:
Extends MediaController and overrides touch event
private class MyMediaController extends MediaController{
public MyMediaController(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
}
Use extended class
mediaController = new MyMediaController(getActivity()){
#Override
public void hide()
{
if(mediaPlayer.isPlaying()){
mediaPlayer.stop();
}
super.hide();
}
};
launchMediaController() is actually what launches the media controller.
My question, why does the media controller hides by itself after some seconds after the user touches it? Is there any solution to this?
when you call show() , you can set a duration to show the controller on screen. so the controller will automatically hide after 'timeout' milliseconds of inactivity.
You can set the timeout as 0 , to show the controller until the hide is explicitly called.
controller.show(0);
Use 0 to show the controller until hide() is called.
If you use show() method without argument , the default timeout is 3 seconds
Here is some code from show(int timeOut) method call
Message msg = mHandler.obtainMessage(FADE_OUT);
if (timeout != 0) {
mHandler.removeMessages(FADE_OUT);
mHandler.sendMessageDelayed(msg, timeout);
}
The handler is send a delayed message if the timeout id not 0, and in handler if the message is FADE_OUT the hide method is called
EDIT
There is bug in MediaController code. In the onTouchEvent the default timeout is set , which will override the timeout 0.
#Override
public boolean onTouchEvent(MotionEvent event) {
show(sDefaultTimeout);
return true;
}
You can fix this by creating a custom MediaController and override the onTouchEvent
#Override
public boolean onTouchEvent(MotionEvent event) {
return true;
}
How could I make it so that my MediaPlayer continues to play even when the phone is locked and the screen is off, thinking it may have to do something of making it a service but not sure. If so how could I go about changing it to a service or is there a quicker easier fix?
Any help would be great!
Here is code:
public class player2 extends Activity implements Runnable {
private MediaPlayer mp;
private ProgressBar progressBar;
private ImageButton pauseicon;
private final int NUM_SOUND_FILES = 3; //*****REPLACE THIS WITH THE ACTUAL NUMBER OF SOUND FILES YOU HAVE*****
private int mfile[] = new int[NUM_SOUND_FILES];
private Random rnd = new Random();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.player_2);
pauseicon = (ImageButton) findViewById(R.id.pauseicon);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
getActionBar().setDisplayHomeAsUpEnabled(true);
mfile[0] = R.raw.sound04; //****REPLACE THESE WITH THE PROPER NAMES OF YOUR SOUND FILES
mfile[1] = R.raw.sound05; //PLACE THE SOUND FILES IN THE /res/raw/ FOLDER IN YOUR PROJECT*****
mfile[2] = R.raw.sound06;
// Listeners
/**
* Play button click event
* plays a song and changes button to pause image
* pauses a song and changes button to play image
* */
try{
mp = MediaPlayer.create(player2.this, mfile[rnd.nextInt(NUM_SOUND_FILES)]);
mp.seekTo(0);
mp.start(); ;
progressBar.setVisibility(ProgressBar.VISIBLE);
progressBar.setProgress(0);
progressBar.setMax(mp.getDuration());
new Thread(this).start();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
}
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
pauseicon.setImageResource(R.drawable.playicon);
}
});
pauseicon.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// TODO Auto-generated method stub
// No need to check if it is pauseicon
if(mp.isPlaying()){
mp.pause();
((ImageButton) v).setImageResource(R.drawable.playicon);
} else {
mp.start();
((ImageButton) v).setImageResource(R.drawable.pauseicon);
}}});
}
static boolean runThread = true;
public void run() {
while ( runThread ) {
int currentPosition=0;
int total = mp.getDuration();
if ( mp != null && currentPosition <= total ) {
try {
Thread.sleep(1000);
currentPosition= mp.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
progressBar.setProgress(currentPosition);
} else
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
runThread = false;
}
#Override
protected void onStop() {
super.onStop();
if (mp != null && mp.isPlaying()){
mp.pause();
}
}
#Override
public void onResume()
{
super.onResume();
if (mp != null){
if(!mp.isPlaying())
try {
mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.start();
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}
Follow my tutorial below...In following tutorial i have stored .mp3 file in raw folder. if you have stored it in sd card and dynamically fetching that file then put its path in bundle and send it through intent which you can get in onStartCommand() method of your service.
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
Button startPlaybackButton, stopPlaybackButton;
Intent playbackServiceIntent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startPlaybackButton = (Button) this.findViewById(R.id.StartPlaybackButton);
stopPlaybackButton = (Button) this.findViewById(R.id.StopPlaybackButton);
startPlaybackButton.setOnClickListener(this);
stopPlaybackButton.setOnClickListener(this);
playbackServiceIntent = new Intent(this, BackgroundAudioService.class);
}
public void onClick(View v) {
if (v == startPlaybackButton) {
startService(playbackServiceIntent);
finish();
} else if (v == stopPlaybackButton) {
stopService(playbackServiceIntent);
finish();
}
}
}
BackgroundAudioService.java
public class BackgroundAudioService extends Service implements OnCompletionListener {
MediaPlayer mediaPlayer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
mediaPlayer = MediaPlayer.create(this, R.raw.abc);// YOUR FILE NAME
mediaPlayer.setOnCompletionListener(this);
Log.v("TEST", "1");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (!mediaPlayer.isPlaying()) {
Log.v("TEST", "2");
mediaPlayer.start();
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
}
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Background Audio Player"
/>
<Button android:text="Start Playback" android:id="#+id/StartPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Stop Playback" android:id="#+id/StopPlaybackButton" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
Don't forget to declare Service in manifest.xml like below,
<service android:name="com.demo.tute.BackgroundAudioService" />
I have radio app stream, and when open this app, first its open splash layout like this :
splash.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:src="#drawable/loading" />
<ProgressBar
android:id="#+id/progressBar1"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1.67" />
</LinearLayout>
and class for it like :
StartPoint.java
public class StartPoint extends Activity{
ProgressBar progressBar;
private int progressBarStatus = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.splash);
progressBar = (ProgressBar)findViewById(R.id.progressBar1);
Thread timer = new Thread(){
public void run(){
try{
sleep(5000);
while(progressBarStatus < 5000){
StartPoint.this.runOnUiThread(new Runnable(){
public void run()
{
progressBar.setProgress(progressBarStatus);
progressBarStatus += 1000;
}
});
}
}catch(InterruptedException e){
e.printStackTrace();
}finally{
Intent openMainList = new Intent(StartPoint.this,
com.example.kam.MainActivity.class);
startActivity(openMainList);
}
}
};
timer.start();
}
#Override
protected void onStop(){
super.onStop();
finish();
}
}
this class when finished, its call MainActivity.java class, and its show :
MainActivity.java
public class MainActivity extends Activity implements OnClickListener {
// Define ..............................................................
private static ProgressDialog progressDialog;
public MediaPlayer mp;
boolean isPrepared = false;
Button PlayBtn, ExitBtn, PauseBtn, RefreshBtn;
String MEDIA_PATH;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
progressDialog = ProgressDialog.show(MainActivity.this, "",
"Buffering Radio...", true);
progressDialog.setCancelable(false);
// Declare
// ..............................................................
mp = new MediaPlayer();
PlayBtn = (Button) findViewById(R.id.btnPlay);
PlayBtn.setOnClickListener(this);
PauseBtn = (Button) findViewById(R.id.btnPause);
PauseBtn.setOnClickListener(this);
RefreshBtn = (Button) findViewById(R.id.btnRefresh);
RefreshBtn.setOnClickListener(this);
ExitBtn = (Button) findViewById(R.id.btnExit);
ExitBtn.setOnClickListener(this);
MEDIA_PATH = "http://radio.arabhosters.com:8015/";
// Volume Control
// ..............................................................
final AudioManager leftAm = (AudioManager)
getSystemService(Context.AUDIO_SERVICE);
int maxVolume = leftAm.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
int curVolume = leftAm.getStreamVolume(AudioManager.STREAM_MUSIC);
SeekBar volControl = (SeekBar) findViewById(R.id.volumebar);
volControl.setMax(maxVolume);
volControl.setProgress(curVolume);
volControl.setOnSeekBarChangeListener
(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged
(SeekBar arg0, int arg1, boolean arg2) {
// TODO Auto-generated method stub
leftAm.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
}
});
}
#Override
public void onClick(View v) {
if (v == PlayBtn) {
startradio();
}
else if (v == PauseBtn) {
pauseradio();
}
else if (v == ExitBtn) {
exitradio();
}
else if (v == RefreshBtn) {
try {
refreshradio();
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public void onCompletion(MediaPlayer mediaPlayer) {
synchronized (this) {
isPrepared = false;
}
}
protected void onResume() {
super.onResume();
try {
mp.setDataSource(MEDIA_PATH);
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.prepare();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} // also consider mp.prepareAsync().
// defult start stream when start App.
mp.start();
mp.setVolume(100, 100);
progressDialog.dismiss();
}
// method for play stream after stop it.
public void startradio() {
try {
if (mp.isPlaying()) {
return;
}
mp.start();
progressDialog.dismiss();
}
catch (IllegalStateException ex) {
ex.printStackTrace();
}
}
// method for Refresh stream.
public void refreshradio() throws IllegalArgumentException,
SecurityException, IOException {
try {
if (mp.isPlaying()) {
return;
}
mp.reset();
mp.setDataSource(MEDIA_PATH);
mp.prepare();
mp.start();
progressDialog.dismiss();
}
catch (IllegalStateException ex) {
ex.printStackTrace();
}
}
// method for pause stream.
public void pauseradio() {
mp.pause();
}
// method for check is radio paly or not stream
public boolean isPlaying() {
return mp.isPlaying();
}
// method for Looping audio if your record it - Soon :)
public boolean isLooping() {
return mp.isLooping();
}
// method for Looping audio if your record it - Soon :)
public void setLooping(boolean isLooping) {
mp.setLooping(isLooping);
}
// method for volume
public void setVolume(float volumeLeft, float volumeRight) {
mp.setVolume(volumeLeft, volumeRight);
}
// method for stop stream.
public void stopradio() {
if (mp.isPlaying()) {
mp.stop();
}
mp.release();
}
// method for exit.
public void exitradio() {
finish();
System.exit(0);
}
// method for back to main menu "Home".
public void backtomenu() {
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
and layout for it like :
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/bg">
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:orientation="vertical"
>
<LinearLayout
android:layout_weight="6"
android:orientation="vertical"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_width="fill_parent"
android:layout_height="0dip" >
</LinearLayout>
<LinearLayout
android:id="#+id/buttons"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_alignParentLeft="true"
android:layout_weight="0.62"
android:background="#drawable/iconbgrepate"
android:gravity="center"
android:orientation="horizontal"
android:tileMode="repeat"
android:weightSum="5"
android:alpha=".75">
<SeekBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="#+id/volumebar"
android:max="100"
android:paddingBottom="10dip"/>
</LinearLayout>
<LinearLayout
android:id="#+id/buttons"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_alignParentLeft="true"
android:layout_weight="0.62"
android:background="#drawable/iconbgrepate"
android:gravity="center"
android:orientation="horizontal"
android:tileMode="repeat"
android:weightSum="5" >
<Button
android:id="#+id/btnRefresh"
android:layout_width="32dp"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="0.10"
android:background="#drawable/refreshbutton" />
<View android:layout_weight="1"
android:layout_width="0dip"
android:layout_height="0dip" />
<Button
android:id="#+id/btnPause"
android:layout_width="32dp"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="0.05"
android:background="#drawable/pausebutton" />
<View android:layout_weight="1"
android:layout_width="0dip"
android:layout_height="0dip" />
<Button
android:id="#+id/btnPlay"
android:layout_width="32dp"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="0.05"
android:background="#drawable/playbutton" />
<View android:layout_weight="1"
android:layout_width="0dip"
android:layout_height="0dip" />
<Button
android:id="#+id/btnExit"
android:layout_width="32dp"
android:layout_height="match_parent"
android:layout_margin="5dp"
android:layout_weight="0.12"
android:background="#drawable/exitbutton" />
</LinearLayout>
</LinearLayout>
</RelativeLayout>
why when trans from splash.xml to activity_main.xml display black background few min and display app.
Since you are changing activity, its gonna show some animation or black screen like you said. Its the default behavior. You can use a custom dialog with your splash layout on top of main activity. you can trigger the dialog to close on progress complete. Using two activities can have other effects. for instance when the user hits the back button, its gonna go back to splash screen instead of exiting the app.
try it
Thread timer = new Thread(){
public void run(){
try{
while(progressBarStatus < 5000){
StartPoint.this.runOnUiThread(new Runnable(){
public void run()
{
progressBar.setProgress(progressBarStatus);
progressBarStatus += 1000;
}
});
sleep(5000);
}