您的位置:首页 > 其它

利用Service后台播放音乐实例

2015-10-29 07:10 417 查看
AndroidManifest.xml //在这个文件中建立service标签<?xml version="1.0" encoding="utf-8"?> //建立service标签名称是music 这个地方的名称就是 com.example.onroad中的程序.java文件名称 //建立动作名称 在程序中运行名字叫".player2"的intent 就可以调用上面的.java文件 MainActivity.java 文件package com.example.onroad;import android.os.Bundle;import
android.app.Activity;import android.view.Menu;import android.widget.Button;import android.view.View;import android.view.View.OnClickListener;import android.content.Intent;public class MainActivity extends Activity {//获取AndroidManifest.xml 中的action定义的名称 private
Intent intent=new Intent(".player2"); private Button playButton; private Button pauseButton; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); @ playButton = (Button)findViewById(R.id.button1);
pauseButton = (Button)findViewById(R.id.button1); viewHolder.button1.setOnClickListener(new OnClickListener(){ //设置button1在服务中播放音乐 public void onClick(View v) { startService(intent); } }); viewHolder.button2.setOnClickListener(new OnClickListener(){ //设置button2在服务停止音乐
public void onClick(View v) { stopService(intent); } @ });//@--@区间的代码也可以不要改为startService(intent);或stopService(intent); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main,
menu); return true; }}music.javapackage com.example.onroad;import android.app.Service;import android.content.Intent;import android.media.MediaPlayer;import android.os.IBinder;public class wudi extends Service { private MediaPlayer player; public IBinder onBind(Intent
intent) { // TODO Auto-generated method stub return null; } public void onStart(Intent intent, int startId) { //startService(intent);运行onStart() // TODO Auto-generated method stub super.onStart(intent, startId); if(player==null) { //在res下建立raw文件夹,然后把音乐放到这里面;系统会自动在gen/J.java里面建立raw对立的音乐名称
player=MediaPlayer.create(this, R.raw.happybirthday); player.start(); } } @Override public void onDestroy() { //stopService(intent); //运行onDestroy(); // TODO Auto-generated method stub super.onDestroy(); player.stop(); }} activity_main.xml
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: