Java 关闭应用程序后在后台播放音乐

Java 关闭应用程序后在后台播放音乐,java,android,android-mediaplayer,Java,Android,Android Mediaplayer,我这里的问题是关于在用户关闭应用程序后播放音乐(应用程序选项卡未显示在当前打开的应用程序列表中) 我创建了一个类来处理针对媒体播放器播放铃声音乐的服务: public class RingService extends Service { private MediaPlayer player; @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public int

我这里的问题是关于在用户关闭应用程序后播放音乐(应用程序选项卡未显示在当前打开的应用程序列表中)

我创建了一个类来处理针对媒体播放器播放铃声音乐的服务:

public class RingService extends Service {

private MediaPlayer player;


@Nullable
@Override
public IBinder onBind(Intent intent) {
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    player = MediaPlayer.create(this,
            Settings.System.DEFAULT_RINGTONE_URI);
    player.setLooping(true);
    player.start();
    return START_STICKY;

}


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

}
在我的主要活动中,我使用一个按钮开始播放音乐。在我关闭应用程序之前,它工作正常

public class MainActivity extends AppCompatActivity {

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

}

@Override
protected void onStart() {
    super.onStart();
}


public void onRing(View view) {
 Intent intent = new Intent(this, RingService.class);
    startService(intent);

}

public void onStop(View view) {
    Intent intent = new Intent(this, RingService.class);
    stopService(intent);
}
}
有没有人能告诉我,我做错了什么?我将不胜感激。
只是不想为这个应用启动另一个主题,我会在这里问它-在用户关闭活动后10秒内是否可以重新启动活动?

我想你错过了要实现的onCreate

我的应用程序使用以下代码运行良好:

public class BackgroundMusicService extends Service {
MediaPlayer musicPlayer;
public IBinder onBind(Intent arg) {
    return null;
}
@Override
public void onCreate() {
    super.onCreate();
    musicPlayer = MediaPlayer.create(this, R.raw.your_music_file);
    musicPlayer.setLooping(true); // Set looping
    musicPlayer.setVolume(100,100);

}
public int onStartCommand(Intent intent, int flags, int startId) {
    musicPlayer.start();
    return 1;
}
@Override
public void onDestroy() {
    musicPlayer.stop();
    musicPlayer.release();
}
在你的清单中:

<service android:enabled="true" android:name=".BackgroundSoundService" />

因此,在关闭应用程序后,您希望使用铃声服务播放一些铃声,但当用户关闭应用程序时,会在MainActivity中调用
onStop()
方法,并使用此代码
Intent Intent=new Intent(这是RingService.class);
停止服务(意向)。如果您同时停止服务,服务将如何播放您的音乐。
尝试从
onStop()
中删除此代码(不确定它是否能解决问题,但值得尝试)

此外,我建议使用Logcat测试您的代码


您需要使用
开始前台(id,通知)
将您的服务放在前台,请查看参考

当您在前台有一个服务时,您的进程被终止的可能性会大大降低,因为您的进程不会被认为是在后台。缺点是您必须显示一个永久通知,在您的情况下,这甚至可能是可取的,因为您可能需要对播放器进行控制