2

我想做的只是通过服务控制我的应用程序中的背景音乐,这样我就可以启动它并停止它的任何活动。

当我在启动和销毁服务时告诉 Toast 服务时,我的一切都设置得很完美,但是只要我将媒体播放放在那里,它就会开始正常并开始播放音乐,但只要单击一个按钮即可停止服务我得到一个错误并强制关闭。

谁能建议我做错了什么?

这是我的代码:

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

private MediaPlayer player;

@Override    
public IBinder onBind(Intent intent) {
returnnull;
}

@Override    
publicvoid onCreate() { 
super.onCreate(); 
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
MediaPlayer player = MediaPlayer.create(MyService.this, R.raw.oceanwavestest);
player.start();
player.setLooping(true);

}

   @Override    
   publicvoid onDestroy() {
   super.onDestroy();
   player.stop();
   Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
   } 
} 
4

1 回答 1

0

There are a few things that I see in your code that I would check out if I were in your position.

  • You are trying to call "stop" on a member MediaPlayer object "player" in your onDestroy, but in your onCreate you create a MediaPlayer object "player" with your line of code

"MediaPlayer player = MediaPlayer.create(MyService.this, R.raw.oceanwavestest);"

which i believe creates a player object that you will loose scope of outside of the function.

The 1 line fix for this code is to just use "player = MediaPlayer.create(MyService.this, R.raw.oceanwavestest);", this way the member variable is used rather than a local variable

If this were my code I would change the member variable to be called something like m_player or mPlayer so that you know it is a member variable in your code.

  • (probably a typo) "returnnull;" in onBind should be "return null;"

  • you also might want to try calling

player.stop(); Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();

before you call super.onDestroy()

Let me know if this helps at all

于 2010-02-20T05:08:41.763 回答