stop service in android

前端 未结 3 1406
有刺的猬
有刺的猬 2020-11-29 04:04

Here I tried simple service program. Start service works fine and generates Toast but stop service does not. The code of this simple service is as below:

pub         


        
相关标签:
3条回答
  • 2020-11-29 04:48
    onDestroyed()
    

    is wrong name for

    onDestroy()  
    

    Did you make a mistake only in this question or in your code too?

    0 讨论(0)
  • 2020-11-29 04:52

    To stop the service we must use the method stopService():

      Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
      //startService(myService);
      stopService(myService);
    

    then the method onDestroy() in the service is called:

      @Override
        public void onDestroy() {
    
            Log.i(TAG, "onCreate() , service stopped...");
        }
    

    Here is a complete example including how to stop the service.

    0 讨论(0)
  • 2020-11-29 05:06

    This code works for me: check this link
    This is my code when i stop and start service in activity

    case R.id.buttonStart:
      Log.d(TAG, "onClick: starting srvice");
      startService(new Intent(this, MyService.class));
      break;
    case R.id.buttonStop:
      Log.d(TAG, "onClick: stopping srvice");
      stopService(new Intent(this, MyService.class));
      break;
    }
    }
     }
    

    And in service class:

      @Override
    public void onCreate() {
        Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onCreate");
    
        player = MediaPlayer.create(this, R.raw.braincandy);
        player.setLooping(false); // Set looping
    }
    
    @Override
    public void onDestroy() {
        Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
        Log.d(TAG, "onDestroy");
        player.stop();
    }
    

    HAPPY CODING!

    0 讨论(0)
提交回复
热议问题