Search This Blog

Showing posts with label Handler. Show all posts
Showing posts with label Handler. Show all posts

Saturday, March 30, 2013

Streaming songs from Url in Default Media Player

Here i am posting with the example code of the streaming the songs from the Url in android with android default media player. 

First of all you just have to make the XML file with the following lines

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 
xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="fill_parent" 
android:layout_height="fill_parent" 
android:focusable="true">
<EditText 
android:text="The song URL" 
android:layout_width="fill_parent" 
android:layout_height="wrap_content" 
android:id="@+id/EditTextSongURL"/>
<ImageButton 
android:layout_below="@+id/EditTextSongURL"
android:id="@+id/ButtonTestPlayPause" 
android:layout_height="wrap_content" 
android:layout_width="match_parent"
android:src="@drawable/button_play"/>
<SeekBar 
android:layout_below="@+id/ButtonTestPlayPause"
android:id="@+id/SeekBarTestPlay" 
android:layout_height="wrap_content" 
android:layout_width="match_parent"
android:thumb="@drawable/thumb_transparent"/>
</RelativeLayout>

Now in you main Activity class replace with the following code and enter the URL of your server song and hit play.

public class StreamingPlayer extends Activity implements OnClickListener, OnTouchListener, OnCompletionListener, OnBufferingUpdateListener{

private ImageButton buttonPlayPause;
private SeekBar seekBarProgress;
public EditText editTextSongURL;

private MediaPlayer mediaPlayer;
// this value contains the song duration in milliseconds. Loook at getDuration() method in MediaPlayer class
private int mediaFileLengthInMilliseconds; 

private final Handler handler = new Handler();

** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
             super.onCreate(savedInstanceState);
             setContentView(R.layout.main);
             initView();
}

/** This method initialise all the views in project*/
private void initView() {
             buttonPlayPause = (ImageButton)findViewById(R.id.ButtonTestPlayPause);
             buttonPlayPause.setOnClickListener(this);

             seekBarProgress = (SeekBar)findViewById(R.id.SeekBarTestPlay);
             seekBarProgress.setMax(99); // It means 100% .0-99
             seekBarProgress.setOnTouchListener(this);
             editTextSongURL = (EditText)findViewById(R.id.EditTextSongURL);
             editTextSongURL.setText(R.string.testsong_20_sec);

             mediaPlayer = new MediaPlayer();
             mediaPlayer.setOnBufferingUpdateListener(this);
             mediaPlayer.setOnCompletionListener(this);
}

/** Method which updates the SeekBar primary progress by current song playing position*/
private void primarySeekBarProgressUpdater() {
              seekBarProgress.setProgress((int)                                     (((float)mediaPlayer.getCurrentPosition()/mediaFileLengthInMilliseconds)*100)); // This math construction give a percentage of "was playing"/"song length"
                     if (mediaPlayer.isPlaying()) {
                                     Runnable notification = new Runnable() {
                                                         public void run() {
                                                                    primarySeekBarProgressUpdater();
                                                         }
                                     };
                    handler.postDelayed(notification,1000);
       }
}

@Override
public void onClick(View v) {

           if(v.getId() == R.id.ButtonTestPlayPause){
/** ImageButton onClick event handler. Method which start/pause mediaplayer playing */
             try {
                   // setup song URL to mediaplayer data source
                  mediaPlayer.setDataSource(editTextSongURL.getText().toString());
                  mediaPlayer.prepare();
                 } catch (Exception e) {
                  e.printStackTrace();
               }

mediaFileLengthInMilliseconds = mediaPlayer.getDuration();

           if(!mediaPlayer.isPlaying()){
                mediaPlayer.start();
                buttonPlayPause.setImageResource(R.drawable.button_pause);
           }else {
                mediaPlayer.pause();
                buttonPlayPause.setImageResource(R.drawable.button_play);
          }

          primarySeekBarProgressUpdater();
     }
}

@Override
public boolean onTouch(View v, MotionEvent event) {
           if(v.getId() == R.id.SeekBarTestPlay){
             /** Seekbar onTouch event handler. Method which seeks MediaPlayer to seekBar        primary progress position*/
                    if(mediaPlayer.isPlaying()){
                          SeekBar sb = (SeekBar)v;
                          int playPositionInMillisecconds = (mediaFileLengthInMilliseconds / 100) * sb.getProgress();
                         mediaPlayer.seekTo(playPositionInMillisecconds);
                    }
               }
          return false;
     }


@Override
public void onCompletion(MediaPlayer mp) {
       /** MediaPlayer onCompletion event handler. Method which calls then song playing is complete*/
           buttonPlayPause.setImageResource(R.drawable.button_play);
}

@Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
/** Method which updates the SeekBar secondary progress by current song loading from URL position*/
             seekBarProgress.setSecondaryProgress(percent);
      }
}

Thursday, March 8, 2012

Run the ProgresBar using the Handler

First of all create tha main.xml file and insert the following code into it.


<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"                              android:layout_width="fill_parent" 
android:layout_height="fill_parent"
android:orientation="vertical" >
 <ProgressBar android:id="@+id/progressBar1" style="?       
          android:attr/progressBarStyleHorizontal" 
          android:layout_width="match_parent" 
          android:layout_height="wrap_content" 
          android:indeterminate="false" 
          android:max="10" 
          android:padding="4dip" >
 </ProgressBar>
      <Button android:id="@+id/button1" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:onClick="startProgress" 
        android:text="Start Progress" > 
</Button> 
</LinearLayout>

Now make an java file and insert the following code into it.

public class ProgressBar extends Activity { 
                             private Handler handler; 
                             private ProgressBar progress;
/** Called when the activity is first created. */ 
                @Override  
                 public void onCreate(Bundle savedInstanceState) { 
                     super.onCreate(savedInstanceState); 
                     setContentView(R.layout.main); 
                     progress = (ProgressBar) findViewById(R.id.progressBar1); 
                     handler = new Handler(); 
             } 

    public void startProgress(View view) { 
                 // Do something long 
                 Runnable runnable = new Runnable() { 
                           @Override public void run() 
                            { 
                                    for (int i = 0; i <= 10; i++) { 
                                             final int value = i; 
                                             try { 
                                                   Thread.sleep(2000); 
                                                   }
                                             catch (InterruptedException e) { 
                                                     e.printStackTrace(); 
                                              }
                  handler.post(new Runnable() { 
                                @Override public void run() { 
                                                 progress.setProgress(value); 
                                     } 
                            }); 
                        }
                   } 
               }; 
                    new Thread(runnable).start(); 
               }
}

Run your application. Once you press your button the ProgressBar will get updated from the background thread.

Wednesday, February 29, 2012

Progressbar using Thread

Here i am going to give the example of the Progress bar using thread.

ProgressBar is a visual indicator of progress in some operation. Displays a bar to the userrepresenting how far the operation has progressed; the application can change the amount of progress (modifying the length of the bar) as it moves forward.

First of all make an .xml file and insert the following into it



<?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="@string/hello"
/>
<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressbar_default"
/>
<ProgressBar
android:layout_width="fill_parent"
android:layout_height="wrap_content"
style="?android:attr/progressBarStyleHorizontal"
android:id="@+id/progressbar_Horizontal"
android:max="100"
/>
</LinearLayout>


make an JAVA file and enter the following code into it.

package com.exercise.AndroidProgressBar;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.ProgressBar;

public class AndroidProgressBar extends Activity {

         ProgressBar myProgressBar;
         int myProgress = 0;

         /** Called when the activity is first created. */
         @Override
        public void onCreate(Bundle savedInstanceState) {
                        super.onCreate(savedInstanceState);
                        setContentView(R.layout.main);

                        myProgressBar=(ProgressBar)findViewById(R.id.progressbar_Horizontal);

                        new Thread(myThread).start();
         }

         private Runnable myThread = new Runnable(){

         @Override
         public void run() {
                   // TODO Auto-generated method stub
                   while (myProgress<100){
                   try{
                        myHandle.sendMessage(myHandle.obtainMessage());
                        Thread.sleep(1000);
                        }
                   catch(Throwable t){
                     }
            }
 }

          Handler myHandle = new Handler(){

         @Override
          public void handleMessage(Message msg) {
                       // TODO Auto-generated method stub
                       myProgress++;
                       myProgressBar.setProgress(myProgress);
           }

        };
   };
}