I am trying to play music continuously in background without any button click,it should play on launching activity,and again it can be stopped by stop button.But it is not stopping as it is placed in Oncreate() ,what can be the solution for this. Please anyone tell me how to stopservice.Thankyou in advance.
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start = findViewById(R.id.startbutton);
stop = findViewById(R.id.stopbutton);
Intent i = new Intent(this, Service.class);
this.startService(i);
stop.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(view.getContext(), Service.class);
stopService(i);
Toast.makeText(MainActivity.this, "stop service called", Toast.LENGTH_SHORT).show();
}
});
start.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent i = new Intent(view.getContext(), Service.class);
startService(i);
}
});
}
Below is my Service code
private MediaPlayer player;
public Service() {
super();
}
@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();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}