【问题标题】:Android Background Service didn't stop/terminateAndroid 后台服务没有停止/终止
【发布时间】:2012-09-25 06:19:37
【问题描述】:

我正在使用服务来播放背景音乐。问题是我完成活动后音乐继续播放。

这是来自 Main Activity 的代码,用于启动服务

            Intent svc=new Intent(HomeActivity.this, BackgroundSoundService.class);
    startService(svc);

BackgroundSoundService.java

         public class BackgroundSoundService extends Service {
             private static final String TAG = null;
             public static MediaPlayer player;
             public IBinder onBind(Intent arg0) {

                 return null;
             }
             @Override
             public void onCreate() {
                 super.onCreate();
                 Log.d("atMedia", "Backround Music playing");
                 player = MediaPlayer.create(this, R.raw.background);
                 player.setLooping(true); // Set looping
                 player.setVolume(100,100);

             }
             public int onStartCommand(Intent intent, int flags, int startId) {
                 player.start();
                 return 1;
             }

             public void onStart(Intent intent, int startId) {
                 // TO DO
             }
             public IBinder onUnBind(Intent arg0) {
                 // TO DO Auto-generated method
                 return null;
             }

             public void onStop() {

             }
             public void onPause() {

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

             @Override
             public void onLowMemory() {

             }

}

【问题讨论】:

    标签: java android android-service


    【解决方案1】:

    尝试从您的 MainActivity 停止服务:

    Intent svc=new Intent(HomeActivity.this, BackgroundSoundService.class);     
    stopService(svc);
    

    【讨论】:

      【解决方案2】:

      你必须在你的服务中调用 selfStop() 方法。 或使用 stopService() API

      【讨论】:

      • 是的 stopService(),谢谢你的回答 :-)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-12-17
      • 2011-11-20
      • 1970-01-01
      • 2020-08-09
      • 1970-01-01
      • 2023-04-03
      • 2018-11-11
      相关资源
      最近更新 更多