首页 > 代码库 > Android 四大组件之Service学习
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 @Override16 public IBinder onBind(Intent intent) {17 // TODO: Return the communication channel to the service.18 throw new UnsupportedOperationException("Not yet implemented");19 }20 21 @Override22 public int onStartCommand(Intent intent, int flags, int startId) {23 System.out.println("Service Start");24 mMediaPlayer = MediaPlayer.create(this,R.raw.gem);//gem.mp325 mMediaPlayer.start();26 return super.onStartCommand(intent, flags, startId);27 }28 29 @Override30 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 @Override14 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 @Override27 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 @Override36 public void onClick(View view) {37 Intent intent = new Intent(MainActivity.this,PlayMusicService.class);38 stopService(intent);39 40 }41 }42 }
4.运行界面
Android 四大组件之Service学习
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。