Service服务的使用

mac2024-03-21  28

Service

分两种开启服务的方法

1.startService

开启服务

Intent intent = new Intent(MainActivity.this,MusicService.class); startService(intent); //在fragment中 getActivity.startService(intent);

停止服务

stopService(intent); // 在fragment中 getActivity.stopService(intent);

2.bindService

创建service类

package com.example.haoji.Service; import android.app.Service; import android.content.Context; import android.content.Intent; import android.media.MediaPlayer; import android.net.Uri; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import java.io.IOException; /** * Created by HAOJI on 2019/9/7. */ public class MusicServices extends Service { private static final String TAG = "myservice"; public MyBinder mbinder = new MyBinder(); private MediaPlayer mediaPlayer =new MediaPlayer(); private String path; @Nullable @Override public IBinder onBind(Intent intent) { path = intent.getStringExtra("path"); Log.e(TAG, "path:" +path); Log.e(TAG, "onBind" ); prepare_play(); return mbinder; } public class MyBinder extends Binder { public MusicServices getService() { return MusicServices.this; } public void start(){ Log.e(TAG, "start:" ); } public void end(){ Log.e(TAG, "end:" ); } } @Override public void onCreate() { super.onCreate(); Log.e(TAG, "onCreate" ); } public void prepare_play(){ try { Uri uri = Uri.parse(path); mediaPlayer.reset(); mediaPlayer.setDataSource(this,uri); mediaPlayer.prepareAsync(); Log.e(TAG,"-prepare_play-"); } catch (IOException e) { e.printStackTrace(); } } public void play(){ if(!mediaPlayer.isPlaying()){ mediaPlayer.start(); Log.e(TAG,"play--"); } } public void stop(){ if(mediaPlayer.isPlaying()){ mediaPlayer.stop(); Log.e(TAG,"stop"); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { return super.onStartCommand(intent, flags, startId); } @Override public void onDestroy() { super.onDestroy(); Log.e(TAG,"onDestroy"); } @Override public boolean onUnbind(Intent intent) { if (mediaPlayer.isPlaying()){ mediaPlayer.release(); } Log.e(TAG,"onUnbind"); mediaPlayer=null; return super.onUnbind(intent); } }

绑定服务

private ServiceConnection con = new ServiceConnection() { @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { MusicServices.MyBinder myBinder = (MusicServices.MyBinder) iBinder; musicService = myBinder.getService(); } @Override public void onServiceDisconnected(ComponentName componentName) { } }; Intent intent =new Intent(MainActivity.this,MusicService.class); bindServices(intent,con,BIND_AUTO_CREATE); // 在fragment中 getActivity.bindServices(intent,con,BIND_AUTO_CREATE);

解绑服务

unbindService(con); // 在fragment中 getActivity.unbindService(con);
最新回复(0)