Android 四大组件之Service学习

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.运行界面

版权声明:本文为博主原创文章,遵循版权协议,转载请附上原文出处链接和本声明。
本文链接:
快乐赛车投注 秒速时时彩 优优彩票官网 三分快3 秒速快3 极速PK拾 大乐购彩票计划群 快乐赛车 欢乐生肖 快乐赛车投注