1 <Button
2 android:id="@+id/btn_play"
3 android:text="播放"
4 android:layout_width="match_parent"
5 android:layout_height="wrap_content" />
1 public class MainActivity extends AppCompatActivity {
2
3 ImageView ivPlay = null,ivRePlay = null;
4 @Override
5 protected void onCreate(Bundle savedInstanceState) {
6 super.onCreate(savedInstanceState);
7 setContentView(R.layout.activity_main);
8
9 ivPlay = (ImageView) findViewById(R.id.btn_play);
10 ivPlay.setOnClickListener(new View.OnClickListener() {
11 @Override
12 onClick(View view) {
13 Intent intent = new Intent(MainActivity.this,MediaPlayService.class);
14 startService(intent)
15 }
16 });
17 }
18 }
class MediaServiceA Service {
2
3 MediaPlayer mediaPlayer;
4 public MediaServiceA() {
5 6 7 IBinder onBind(Intent intent) {
8 // TODO: Return the communication channel to the service.
9 throw new UnsupportedOperationException("Not yet implemented"10 11
12 13 int onStartCommand(Intent intent,int flags,1)">int startId) {
14
15 if (mediaPlayer==) {
16 mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.ylzs);
17 }对mediaPlayer是否为空进行一个判断,如果不为空就不再Create,否则会重复播放
18 if (mediaPlayer!=19 mediaPlayer.start();
20 }
21 return .onStartCommand(intent,flags,startId);
22 23 }
service
2 android:name=".service.MediaServiceA"
android:enabled="true"
android:exported="true" />