android开发 利用Service给游戏添加背景音乐 叁歲伎倆 2022-05-10 21:16 236阅读 0赞 1、增加一个类,这个类是继承Service的,如下。 Java代码 package com.zhw.game8; /** * Created by 得已 on 2018/9/19. */ import android.app.Service; import android.content.Intent; import android.media.MediaPlayer; import android.os.IBinder; public class MusicServer extends Service { private MediaPlayer mediaPlayer; @Override public IBinder onBind(Intent intent) { // TODO Auto-generated method stub return null; } @Override public void onStart(Intent intent,int startId){ super.onStart(intent, startId); if(mediaPlayer==null){ // R.raw.abc是资源文件,MP3格式的 mediaPlayer = MediaPlayer.create(this, R.raw.abc); mediaPlayer.setLooping(true); mediaPlayer.start(); } } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); mediaPlayer.stop(); } } 2在[Android][]Manifest.xml中添加如下代码。 1. <service Android:name=".MusicServer"> 2. <intent-filter> 3. <action Android:name="com.angel.Android.MUSIC"/> 4. <category Android:name="android.intent.category.default" /> 5. </intent-filter> 6. </service> 3.在activity中 package com.zhw.game8; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.os.Bundle; import android.view.View; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout); } public void startGame(View view) { Intent intent = new Intent(this,MusicServer.class); startService(intent); Intent intent1=new Intent(this,StartActivity.class); startActivity(intent1); } @Override protected void onResume() { super.onResume(); Intent intent = new Intent(this,MusicServer.class); stopService(intent); } } [Android]: http://www.linuxidc.com/topicnews.aspx?tid=11
还没有评论,来说两句吧...