1.创建项目ServiceDemo01,在Main Activity中布局二个Button:启动Service和停止Service.
2.新建一个Service类:PlayMusicService
1 ackage com.hsiehway.servicedemo01; 2 3 import android.app.Service; 4 import android.content.Intent; 5 import android.media.MediaPlayer; 6 import android.os.IBinder; 7 8 public class PlayMusicService extends Service { 9 10 private MediaPlayer mMediaPlayer; 11 12 public PlayMusicService() { 13 } 14 15 @Override 16 public IBinder onBind(Intent intent) { 17 // TODO: Return the communication channel to the service. 18 throw new UnsupportedOperationException("Not yet implemented"); 19 } 20 21 @Override 22 public int onStartCommand(Intent intent, int flags, int startId) { 23 System.out.println("Service Start"); 24 mMediaPlayer = MediaPlayer.create(this,R.raw.gem);//gem.mp3 25 mMediaPlayer.start(); 26 return super.onStartCommand(intent, flags, startId); 27 } 28 29 @Override 30 public void onDestroy() { 31 System.out.println("Service Stop"); 32 super.onDestroy(); 33 mMediaPlayer.stop(); 34 } 35 }
3.MainActivity 类中代码
1 package com.hsiehway.servicedemo01; 2 3 import android.content.Intent; 4 import android.support.v7.app.AppCompatActivity; 5 import android.os.Bundle; 6 import android.view.View; 7 import android.widget.Button; 8 9 public class MainActivity extends AppCompatActivity { 10 11 private Button startBtn,stopBtn; 12 13 @Override 14 protected void onCreate(Bundle savedInstanceState) { 15 super.onCreate(savedInstanceState); 16 setContentView(R.layout.activity_main); 17 18 startBtn = (Button)findViewById(R.id.startbtn); 19 stopBtn = (Button)findViewById(R.id.stopbtn); 20 21 startBtn.setOnClickListener(new startListener()); 22 stopBtn.setOnClickListener(new stopListener()); 23 } 24 25 class startListener implements View.OnClickListener{ 26 @Override 27 public void onClick(View view) { 28 Intent intent = new Intent(MainActivity.this,PlayMusicService.class); 29 startService(intent); 30 31 } 32 } 33 34 class stopListener implements View.OnClickListener{ 35 @Override 36 public void onClick(View view) { 37 Intent intent = new Intent(MainActivity.this,PlayMusicService.class); 38 stopService(intent); 39 40 } 41 } 42 }
4.运行界面
时间: 2024-10-17 16:12:42