Search code examples
androidaudioservice

Audio service not stopping android


The audio service starts just fine when the start button is pressed but it will not stop when the stop button is pressed. here is the java activity. I followed an online example for creating a service to play audio.

import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;

public class Ship extends Activity implements View.OnClickListener {
private static final String TAG = "ShipService";
public static final Integer[] TIME_IN_MINUTES = { 30, 45, 60, 180, 360 };
public MediaPlayer mediaPlayer;
public Handler handler = new Handler();
public Button button2;
public Spinner spinner2;

// Initialize the activity
@Override
public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    // wl.acquire();
    setContentView(R.layout.ship);
    button2 = (Button) findViewById(R.id.btn2);
    button2.setOnClickListener(this);
    spinner2 = (Spinner) findViewById(R.id.spinner2);
    ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,
            android.R.layout.simple_spinner_item, TIME_IN_MINUTES);

adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner2.setAdapter(adapter);

}

// Handle button callback
@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.btn2:
        Log.d(TAG, "onClick: starting service");
        startService(new Intent(this, Shipservice.class));
        break;
    case R.id.stop:
        Log.d(TAG, "onClick: stopping srvice");
        stopService(new Intent(this, Shipservice.class));
        break;
    }
}
}

Solution

  • You have not set the click listener of stop button in onCreate() method.

    Create object of stop button

    public Button button2,stopBtn;

    Update your onCreate() Method like below

     button2 = (Button) findViewById(R.id.btn2);
     button2.setOnClickListener(this);
    

    // stop button

     stopBtn= (Button) findViewById(R.id.stop);
     stopBtn.setOnClickListener(this);