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;@Overridepublic IBinder onBind(Intent intent) { // TODO Auto-generated method stubreturn null;}@Overridepublic 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();}}@Overridepublic void onDestroy() { // TODO Auto-generated method stubsuper.onDestroy();mediaPlayer.stop();} }
2在AndroidManifest.xml中添加如下代码。
- <service Android:name=".MusicServer">
- <intent-filter>
- <action Android:name="com.angel.Android.MUSIC"/>
- <category Android:name="android.intent.category.default" />
- </intent-filter>
- </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 {@Overrideprotected 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);}@Overrideprotected void onResume() {super.onResume();Intent intent = new Intent(this,MusicServer.class);stopService(intent);} }
本文链接:https://my.lmcjl.com/post/9426.html
展开阅读全文
4 评论