我有一个播放music.i的Android服务。我的主要活动开始使用此代码:
Intent service = new Intent(MainMenu.this, musicservice.class);
MainMenu.this.startService(service);
这是我的服务:
public class musicservice extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
MediaPlayer mp;
mp = MediaPlayer.create(musicservice.this, R.raw.music);
mp.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
mp.start();
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
它可以很好地工作,但当我开始另一项活动时,我的音乐会消失,似乎我的服务会破坏!但不要这样,我希望我的服务只在我的申请结束时停止。音乐仅在用户使用app时播放。即使应用程序在后台我希望我的音乐不播放!我该如何实现呢?答案 0 :(得分:1)
如果您希望自己的应用在播放活动时播放音乐,请尝试bind it。
看起来应该是这样的:
服务:
package com.example.service;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Binder;
import android.os.IBinder;
import com.example.playmusic.R;
public class PlayMusicService extends Service {
private final IBinder binder = new LocalBinder();
private MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return binder;
}
public class LocalBinder extends Binder {
public PlayMusicService getService() {
return PlayMusicService.this;
}
}
public void play() {
player = MediaPlayer.create(this, R.raw.music);
player.setOnCompletionListener(new OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
player.start();
}
public void pause() {
player.pause();
}
}
的活动:
package com.example.playmusic;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import com.example.service.PlayMusicService;
import com.example.service.PlayMusicService.LocalBinder;
public class MainActivity extends Activity {
private PlayMusicService service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onPause() {
super.onPause();
service.pause();
}
@Override
protected void onStart() {
super.onStart();
if (service != null) {
service.play();
} else {
bindService();
}
}
private void bindService() {
bindService(new Intent(this, PlayMusicService.class), new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
service = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
LocalBinder localBinder = (LocalBinder) binder;
service = localBinder.getService();
service.play();
}
}, Context.BIND_AUTO_CREATE);
}
}
答案 1 :(得分:0)
当您从活动开始服务时,您的活动销毁时服务会被破坏。
使用AlarmManager
重复安排服务。