gpt4 book ai didi

android - 停止音乐和服务

转载 作者:行者123 更新时间:2023-11-30 01:30:48 25 4
gpt4 key购买 nike

我正在尝试使用 Android 中的服务播放音乐。我正在努力的是停止服务和音乐。这是我的服务:

MediaPlayer mediaPlayer;

public SoundService() {
super("SoundService");
}

@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}

@Override
protected void onHandleIntent(Intent intent) {

}

@Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(getApplicationContext(),R.raw.zenenegy);
}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
return START_STICKY;
}

public void stopp(){
Log.d("SERVICE","STOP");
stopSelf();
}

@Override
public void onDestroy() {
super.onDestroy();
}

当我调用“stopp”方法时,我得到了日志,所以服务应该已经停止,但音乐还在继续。我不知道如何停止音乐,因为当我尝试使用 mediPlayer.stop();方法 我总是收到错误消息,所以如果我可以随时停止服务就太好了。这是 Activity 的代码:

public Button zene;
public boolean hang = true;
SoundService soundService;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fomenu);

if(hang){
startService();
}
}

@Override
protected void onResume() {
zene = (Button)findViewById(R.id.zene);

zene.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(hang){
soundService.stopp();
//soundService.onDestroy();
}
hang = !hang;
}
});
super.onResume();
}

public void startService(){
startService(new Intent(getBaseContext(), SoundService.class));
}

public void stopService(){
stopService(new Intent(getBaseContext(),SoundService.class));
}

我试过使用 stopService();方法也一样,但是没用。如果有人知道如何停止服务中的音乐,请回复。

最佳答案

声音服务.java

public void stop(){
Log.d("SERVICE","STOP");
mp.stop();
//release the media player if you want to
stopSelf();
}

一些停止方法是使用 Bound Services或者在您的 onStartCommand 中识别 Intent 操作,然后调用 stop()

看起来像这样

InYourActivity.java

public void stopService(){
Intent stopIntent = new Intent(getBaseContext(),SoundService.class);
intent.setAction(SoundService.ACTION_STOP);
stopService(stopIntent);
}

声音服务.java

public static final String ACTION_STOP = "stop_music_service";

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(intent.getAction()!=null && intent.getAction().equals(ACTION_STOP)){
stop();
}
mediaPlayer.start();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
mp.release();
}
});
return START_STICKY;
}

关于android - 停止音乐和服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35785025/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com