1. Introduction to Demo
Use AIDL to bind the activity service, use the Handler mechanism to send messages to update the SeekBar's UI, and use the timer to update the SeekBar's progress regularly. Implements the functions of starting playback, pausing, continuing, and stopping the playback of music. And the function of dragging the progress bar to play music.
2.AIDL interface
Use the AIDL mechanism to provide MainActivity with a method to access MyMusicService, and realize playback pause and other functions.
3. Main class code
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; /** * Created by c_ljf on 16-12-26. */ public class MyMusicService extends Service { private String tag="MyMusicService"; private MediaPlayer mediaPlayer; @Override public void onCreate() { (); mediaPlayer = new MediaPlayer(); } @Nullable @Override public IBinder onBind(Intent intent) { return new MyMusicBinder(); } class MyMusicBinder extends { @Override public void play() throws RemoteException { playmusic(); } @Override public void pause() throws RemoteException { pausemusic(); } @Override public void stop() throws RemoteException { stopmusic(); } @Override public void continuePlay() throws RemoteException { rePlayMusic(); } @Override public void seekPlayProgress(int position) throws RemoteException { seekPlayPositiom(position); } } //Play music public void playmusic(){ (); String url = "sdcard/Music/Fade.mp3"; (tag,url); try { (url); (); } catch (IOException e) { (); } // might take long! (for buffering, etc) (); //Update the playback progress bar seekPlayProgress(); } public void pausemusic(){ (); (tag,"Pause playback"); } public void stopmusic(){ (); (tag,"Stop Playing"); (); } @Override public void onDestroy() { (); } public void seekPlayPositiom(int positon){ (tag,"Set playback position"); (positon); } public void seekPlayProgress(){ /*1. Get the total duration of the current song*/ final int duration=(); //Timer object final Timer timer=new Timer(); final TimerTask task=new TimerTask() { @Override public void run() { //Open thread timing to get the current playback progress int currentposition=(); //Use message to send a message to the main thread to update the seekbar progress Message ms=(); Bundle bundle=new Bundle(); ("duration",duration); (tag,"Total song length"+duration); ("currentposition",currentposition); (tag,"Current length"+currentposition); //Set the message content to be sent (bundle); //Send a message (ms); } }; (task,300,500); //Stop playback when playback is over (new () { @Override public void onCompletion(MediaPlayer mp) { (tag,"Cancel timed task"); (); (); } }); } public void rePlayMusic() { (tag, "Continue to play music"); (); } }
package ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import ; import .; import .; import ; import ; import ; public class MainActivity extends AppCompatActivity { private IMyMusicService iMyMusicService; private static SeekBar seekBar; private Button btpause_play; private boolean b=true;//Judge pause and continue playing public static Handler handler=new Handler(){ @Override public void handleMessage(Message msg) { //Processing messages Bundle bundle=(); //Get the song length and current playback position and set it to the progress bar int duration=("duration"); int currentposition=("currentposition"); (duration); (currentposition); } }; @Override protected void onCreate(Bundle savedInstanceState) { (savedInstanceState); setContentView(.activity_main); verifyStoragePermissions(); //Get play pause button btpause_play=(Button) findViewById(.bt_pause); Intent intent=new Intent(,); bindService(intent,new MyConn(),BIND_AUTO_CREATE); seekBar=(SeekBar) findViewById(); (new () { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { try { (()); } catch (RemoteException e) { (); } } }); } //Define the service connection class class MyConn implements ServiceConnection{ @Override public void onServiceConnected(ComponentName name, IBinder service) { iMyMusicService=(service); } @Override public void onServiceDisconnected(ComponentName name) { } } public void play(View v){ try { (); } catch (RemoteException e) { (); } } public void pause(View v){ try { if(b) { (); b=false; btpause_play.setText("Continue to play"); } else{ b=true; (); btpause_play.setText("Pause playback"); } } catch (RemoteException e) { (); } } public void stop(View v){ try { (); } catch (RemoteException e) { (); } } // Storage Permissions private static final int REQUEST_EXTERNAL_STORAGE = 1; private static String[] PERMISSIONS_STORAGE = { .READ_EXTERNAL_STORAGE, .WRITE_EXTERNAL_STORAGE, }; /** * Checks if the app has permission to write to device storage * * If the app does not has permission then the user will be prompted to grant permissions * * @param activity */ public static void verifyStoragePermissions(Activity activity) { // Check if we have write permission int permission = (activity, .WRITE_EXTERNAL_STORAGE); if (permission != PackageManager.PERMISSION_GRANTED) { // We don't have permission so prompt the user ( activity, PERMISSIONS_STORAGE, REQUEST_EXTERNAL_STORAGE ); } } }
4. Layout files
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:andro xmlns:tools="/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" android:paddingBottom="@dimen/activity_vertical_margin" tools:context=""> <LinearLayout android:orientation="horizontal" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentTop="true" android:layout_alignParentLeft="true" android:layout_alignParentStart="true" android:> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Start Play" android:onClick="play" android:/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Pause playback" android:layout_weight="1" android:onClick="pause" android:/> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_weight="1" android:text="Stop Playing" android:onClick="stop" android:/> </LinearLayout> <SeekBar android:layout_width="match_parent" android:layout_height="wrap_content" android: android:layout_below="@+id/linearLayout" android:layout_alignParentLeft="true" android:layout_alignParentStart="true"/> </RelativeLayout>
5. Registration Service
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:andro package=""> <uses-permission android:name=".READ_EXTERNAL_STORAGE"/> <uses-permission android:name=".WRITE_EXTERNAL_STORAGE"/> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:supportsRtl="true" android:theme="@style/AppTheme"> <activity android:name=".MainActivity"> <intent-filter> <action android:name=""/> <category android:name=""/> </intent-filter> </activity> <service android:name=".MyMusicService"/> </application> </manifest>
The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.