Change file used in a sound service programmatically - java

I'm using the BackgroundSoundService for playing music in a background of my activity. However, when I switch to another activity, I would like to use another sound.
This is how my class looks like. I need to change that "R.raw.sound" programmatically.
public class BackgroundSoundService extends Service {
MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(this, R.raw.sound);
mediaPlayer.setLooping(true); // Set looping
mediaPlayer.setVolume(100, 100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
mediaPlayer.start();
return startId;
}
#Override
public void onDestroy() {
mediaPlayer.stop();
mediaPlayer.release();
}
#Override
public void onLowMemory() {
}}

Related

Change background music volume from activity to service

I'm new to android, and working on a project where I have to implement background music in our app. I've already implemented background music using service, the problem is: I don't know how to change the volume of the music dynamically using a seekbar from an activity.
My service looks like this:
package hu.szoftverprojekt.holdemfree.controller;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import androidx.annotation.Nullable;
import hu.szoftverprojekt.holdemfree.R;
public class PlaySound extends Service {
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, R.raw.ss);
player.setLooping(true);
player.start();
player.setVolume(SettingsScreen.volume, SettingsScreen.volume);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
player.stop();
}
}
Well once you have the SeekBar and the OnSeekBarChangeListener being called as you change the SeekBar, the next major thing is communicating this from your activity to your service this change.
Have a look at the android docs Creating a bound service for the offical way to communicate between an Activity and Service using no 3rd party libraries.
HOWEVER
You could also use a 3rd party library like EventBus (which I'd recommend as it's much easier to use and implement in my opinion).
Here is an example using EventBus:
build.gradle:
dependencies {
implementation 'org.greenrobot:eventbus:3.2.0'
}
MediaVolumeEvent.java:
public class MediaVolumeEvent {
private int volume;
public MediaVolumeEvent(int volume) {
this.volume = volume;
}
public int getVolume() {
return volume;
}
}
PlaySound.java:
public class PlaySound extends Service {
#Override
public void onCreate() {
super.onCreate();
EventBus.getDefault().register(this);
}
#Override
public void onDestroy() {
EventBus.getDefault().unregister(this);
player.stop();
super.onDestroy();
}
#Subscribe(threadMode = ThreadMode.MAIN)
public void onEvent(MediaVolumeEvent event){
player.setVolume(event.getVolume(), event.getVolume());
}
}
In your activity inside the OnSeekBarChangeListener:
SeekBar seekBar= (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
EventBus.getDefault().post(new MediaVolumeEvent(progress));
}
});

Method does not override method from its super class & cannot resolve symbol

In Override, I get a "Method does not override method from its super class" error. I also get "onResume cannot resolve method" error in super.onResume ();
It was working on MainActivity but when I move the code to Service class, I got this error.
As you can see:
public class Servis extends Service implements SensorEventListener{
SensorManager mgr;
Sensor temp;
TextView text;
StringBuilder msg = new StringBuilder(2048);
MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
mediaPlayer = MediaPlayer.create(Servis.this, R.raw.warning);
mgr = (SensorManager) this.getSystemService(SENSOR_SERVICE);
temp = mgr.getDefaultSensor(Sensor.TYPE_AMBIENT_TEMPERATURE); }
#Override
protected void onResume() {
mgr.registerListener(this, temp, SensorManager.SENSOR_DELAY_NORMAL);
super.onResume();
}
#Override
protected void onPause() {
mgr.unregisterListener(this, temp);
super.onPause();
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
public void onSensorChanged(SensorEvent event) {
float fahrenheit = event.values[0] * 9 / 5 + 32;
if(fahrenheit < 68)
mediaPlayer.start();
}
}
A Service is not an Activity, that's why these methods cannot be overridden. You can safely remove them and instead have to let the Activity implement them. When a Service implements SensorEventListener, this would look alike this:
public class Servis extends Service implements SensorEventListener {
#Override
public void onCreate() {
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
}
#Override
public void onDestroy() {
}
#Override
public IBinder onBind(Intent intent) {
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
}
}
As noted above, Services class does not include the methods you so there is no override to be performed. Refer to Service documentation
The closes method you might want to consider it to override
onStart(Intent intent, int startId)
It's perhaps the closest to OnResume

mediaplayer starts a new instance when i return to the app

Im making a simple radio streaming app. Everything works great but having a few buggy issues.
When i press the home screen of my device i want the radio to carry on playing. which it does, But as soon as i go to my app history and re-open the app. It starts a new session. this make for a very Un-Pleasurble piece of music lol.
The app is very simple in the way it works i have a media player and a media controller which is attached to a surfaceView in my xml.
Can some one please tell me the correct way to fix this issue as this is the first time making an app that contains a live stream.
Thanks as always guys
my code for the media player and controller
public class radiostation extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener,
MediaController.MediaPlayerControl {
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private Handler handler = new Handler();
String videoSource =
"my radio station source address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radiostation);
surfaceView = (SurfaceView)findViewById(R.id.surface);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(mediaController != null){
mediaController.show();
}
return false;
}
});
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Toast.makeText(radiostation.this,
"Media Controls active lets mash it up", Toast.LENGTH_LONG).show();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(this);
try {
mediaPlayer.setDataSource(videoSource);
mediaPlayer.prepare();
mediaController = new MediaController(this);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(radiostation.this,
"Radio Station off Air or no internet connection!\n" + e.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
Toast.makeText(radiostation.this,
"You are now connected ", Toast.LENGTH_LONG).show();
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(surfaceView);
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
#Override
public void start() {
mediaPlayer.start();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return false;
}
#Override
public boolean canSeekForward() {
return false;
}
#Override
public int getAudioSessionId() {
return mediaPlayer.getAudioSessionId();
}
#Override
public void onBackPressed() {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
finish();
}

How to perform/run background services in a custom Android OS like MIUI?

I am trying to implement a simple service demo in Android. When I start the service, it should run in the background even if I close the activity.
However on my Redmi phone (running MIUI OS) my service does not show as running when I close the activity.
It works with the stock OS like on a Moto phone.
Can you guys tell me how to do that?
Here is my activity:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start(View v)
{
Intent i=new Intent(this,MyService.class);
startService(i);
}
public void stop(View v)
{
Intent i=new Intent(this,MyService.class);
stopService(i);
}
}
Here is my Service:
public class MyService extends Service {
public MyService() {
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"hello",Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
Toast.makeText(this,"stopped",Toast.LENGTH_LONG).show();
}
}

Replay on BG Music

I made a service that play background music, but when the music finished I want to replay it again. Which method can I use in my service?
public class BackgroundSoundService extends Service {
private static final String TAG = null;
MediaPlayer player;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setVolume(100,100);
}
public int onStartCommand(Intent intent, int flags, int startId) {
player.start();
return 1;
}
public void onStart(Intent intent, int startId) {
// TODO
}
public IBinder onUnBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public void onStop() {
}
public void onPause() {
}
#Override
public void onDestroy() {
player.stop();
player.release();
}
#Override
public void onLowMemory() {
}
}
Just use MediaPlayer.setLooping() method.
Sample code:
#Override
public void onCreate() {
super.onCreate();
player = MediaPlayer.create(this, R.raw.idil);
player.setVolume(100,100);
player.setLooping(true);
}
Set OnCompletionListener via setOnCompletionListener. And it he callback you can start it again.

Categories

Resources