mediaplayer how to stop all sounds? - java

When I press the mute button on action bar that I have created it only stops the last sound being played and not all the sounds.
Also since the sound doesn't stop if I press the button(5-6 times) to play the sound and press mute on the same activity then go back and choose another activity and press that mute button the app crashes. Any ideas why?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
}
public void pb1(View view) {
mp = MediaPlayer.create(this, R.raw.sound1);
mp.start();
}
//inflates the menu;
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menunot, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_sound:
mp.stop();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
mp.stop();
mp.reset();
mp.release();
mp = null;
}

Just make an array list then stop all,
Take a look at the example below:
private static final int steps[] =
{R.raw.step_1, R.raw.step_2, R.raw.step_3, R.raw.step_4, R.raw.step_5, R.raw.step_6, R.raw.step_7, R.raw.step_8, R.raw.step_9, R.raw.step_10
};
private int i = 0;
private ArrayList<MediaPlayer> voices = new ArrayList<>(10);
private Button btnPlay;
private Button btnStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPlay = (Button) findViewById(R.id.btnPlay);
btnPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(i==10)i=0;
final MediaPlayer voice = MediaPlayer.create(MainActivity.this, steps[i++]);
voice.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
if (voice != null) {
voices.remove(voice);
voice.release();
}
}
});
voice.start();
voices.add(voice);
}
});
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
for (int j = voices.size() - 1; j >= 0; j--) {
if (voices.get(j) != null) {
if (voices.get(j).isPlaying())
voices.get(j).stop();
voices.get(j).release();
voices.remove(j);
}
}
}
});
}

Hey please try the following solution,
SoundPool is a much better alternative for this purpose. I would caution strongly against instantiating multiple MediaPlayer instances as most systems do not have the resources to generate many parallel active instances. You will find on many device that hitting the button upwards of 5 times will cause a memory based crash.
As far as stopping all active streams, there is not baked-in function for this, but it's easy to accomplish in a manner to similar to your existing code. As a side note, there is an autoPause() method, which halts all streams, but it doesn't truly end their playback (as the method name insinuates). Here is a simple example to manage your audio streams:
//SoundPool initialization somewhere
SoundPool pool = new SoundPool(10, AudioManager.STREAM_MUSIC, 0);
//Load your sound effect into the pool
int soundId = pool.load(...); //There are several versions of this, pick which fits your sound
List<Integer> streams = new ArrayList<Integer>();
Button item1 = (Button)findViewById(R.id.item1);
item1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
int streamId = pool.play(soundId, 1.0f, 1.0f, 1, 0, 1.0f);
streams.add(streamId);
}
});
Button stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
for (Integer stream : streams) {
pool.stop(stream);
}
streams.clear();
}
});
It is much more memory efficient to manage a list of streamID values than MediaPlayer instances, and your users will thank you. Also, note that it is safe to call SoundPool.stop() even if the streamID is no longer valid, so you don't need to check for existing playback.
Happy coding :)

Related

Countdown with individual Sound

I have a problem with my countdown and I want to play an individual sound at the end. For this I have created a list. When the corresponding picture is clicked, the selection should be saved and played in this method:
private void loadMusic() {
if (timerStatus == TimerStatus.PAUSED)
new Runnable() {
#Override
public void run() {
playSound(R.raw.sound1);
}
public void playSound(int sound1) {
MediaPlayer mp = MediaPlayer.create(getBaseContext(), (R.raw.sound2));
mp.start();
}
}.run()
}
I tried to solve this with an array in the onCreate method, but this is "void" and therefore I don't get a return:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.sound);
final int[] selection = new int[1];
imageButton1 = findViewById(id.iv_bowl1);
imageButton1.setOnClickListener(v -> {
selection[0] = 1;
Toast.makeText(Sound.this, "1-click", Toast.LENGTH_SHORT).show();
});
return selection[0];
}
Thanks for help.

Playing Multiple Mediaplayers with OnCompletionListener in Android Studio

help me, I'm a beginner, I'm trying to make an application in which there is audio that needs to be played, I try to use MediaPlayer, so that the audio can be played and paused, I have implemented these 3 mediaplayer with setOnCompletion and array methods when calling the audio folder,like this:
mediaPlayer.setOnCompletionListener(completionListener);
MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
play++;
if (play < playList.length) {
mediaPlayer = MediaPlayer.create(BackGroundSound.this, playList[play]);
mediaPlayer.start();
} else {
play = 0;
mediaPlayer = MediaPlayer.create(BackGroundSound.this, playList[play]);
mediaPlayer.start();
}
}
};
and this array for file MediaPlayer:
int[] playList = new int[3];
playList[0] = R.raw.madtarqiqc1;
playList[1] = R.raw.madtarqiqc2;
playList[2] = R.raw.madtarqiqc3;
but when I clicked button, the program that I made does not work, the medialayer and button no response, what should I add, I have redesigned this code many times but the results remain the same, is there a code or method that was missed?
This is for the full source code that I have:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
MediaPlayer mediaPlayer;
ImageButton btn1, btn2, btn3;
int[] playList;
int play = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (ImageButton) findViewById(R.id.play_toggle_ratarqiq1);
btn2 = (ImageButton) findViewById(R.id.play_toggle_ratarqiq2);
btn3 = (ImageButton) findViewById(R.id.play_toggle_ratarqiq3);
int[] playList = new int[3];
playList[0] = R.raw.madtarqiqc1;
playList[1] = R.raw.madtarqiqc2;
playList[2] = R.raw.madtarqiqc3;
mediaPlayer = MediaPlayer.create(this, playList[play]);
mediaPlayer.setOnCompletionListener(completionListener);
}
MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
play++;
if (play < playList.length) {
mediaPlayer = MediaPlayer.create(MainActivity.this, playList[play]);
mediaPlayer.start();
} else {
play = 0;
mediaPlayer = MediaPlayer.create(MainActivity.this, playList[play]);
mediaPlayer.start();
}
}
};
#Override
public void onClick(View view) {
switch (view.getId()){
case R.id.play_toggle_ratarqiq1:
playMusic(0);
break;
case R.id.play_toggle_ratarqiq2:
playMusic(1);
break;
case R.id.play_toggle_ratarqiq3:
playMusic(2);
break;
}
}
private void playMusic(int position) {
mediaPlayer.stop();
mediaPlayer = MediaPlayer.create(this, playList[position]);
mediaPlayer.start();
changeView(position);
}
private void changeView(int position) {
if (position == 0) {
btn1.setImageResource(R.drawable.ic_play_circle_outline_black_24dp);
btn2.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
btn3.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
} else if (position == 1) {
btn1.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
btn2.setImageResource(R.drawable.ic_play_circle_outline_black_24dp);
btn3.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
} else if (position == 2) {
btn1.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
btn2.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
btn3.setImageResource(R.drawable.ic_play_circle_outline_black_24dp);
}
}
}
There are few crucial things that you missed :
to set onClickListner() in those Button objects
to reuse the MediaPlayer instance(you created new one everytime you need)
to properly update the play variable which I believe is the index of currently played song
I tried to make it fully readable as I can. Here is the code for MainActivity:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private MediaPlayer mediaPlayer;
private ImageButton btn1, btn2, btn3;
private int[] playList;
// initializing it to -1 so that it is out of bounds of the array playList
private int play = -1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = findViewById(R.id.play_toggle_ratarqiq1);
btn2 = findViewById(R.id.play_toggle_ratarqiq2);
btn3 = findViewById(R.id.play_toggle_ratarqiq3);
// you forgot to setonclicklistener in these buttons thats why they were not reponding
btn1.setOnClickListener(this);
btn2.setOnClickListener(this);
btn3.setOnClickListener(this);
playList = new int[3];
playList[0] = R.raw.madtarqiqc1;
playList[1] = R.raw.madtarqiqc2;
playList[2] = R.raw.madtarqiqc3;
// use constructor to create a mediaplayer object rather than this static create method
// mediaPlayer = MediaPlayer.create(this, playList[play]);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnCompletionListener(completionListener);
}
MediaPlayer.OnCompletionListener completionListener = new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
play++;
if (play < playList.length) {
// we will not assign mediaPlayer to new instance instead we will only change data source
// and reuse the single instance everywhere in this activity
// mediaPlayer = MediaPlayer.create(MainActivity.this, playList[play]);
try {
mediaPlayer.setDataSource(MainActivity.this, Uri.parse("android.resource://" + getPackageName() + "/res/raw/"
+ getResources().getResourceName(playList[play])));
mediaPlayer.start();
} catch (IOException e) {
// if things goes wrong we will show Toast
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
} else {
play = 0;
try {
mediaPlayer.setDataSource(MainActivity.this, Uri.parse("android.resource://" + getPackageName() + "/res/raw/"
+ getResources().getResourceName(playList[play])));
mediaPlayer.start();
} catch (IOException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
}
};
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.play_toggle_ratarqiq1:
// you can check to see if the song that we want to play is already being played
// so that in that case you can pause it and resume on next click later
// but I leave it to you for the implementation
playMusic(0);
break;
case R.id.play_toggle_ratarqiq2:
playMusic(1);
break;
case R.id.play_toggle_ratarqiq3:
playMusic(2);
break;
}
}
private void playMusic(int position) {
// with the code below, for the first time the mediaplayer wouldn't have started playing
// and you would have already called stop() on it.
// mediaPlayer.stop();
// Also, assigning mediaPlayer obj to new instance will wipe out the onCompletionListener
// you set earlier.
// mediaPlayer = MediaPlayer.create(this, playList[position]);
// check to see if mediaplayer is playing to reset it if it is
if (mediaPlayer.isPlaying() || mediaPlayer.)
mediaPlayer.reset();
// now that it is in idle state, set data source in it
try {
mediaPlayer.setDataSource(this, Uri.parse("android.resource://" + getPackageName() + "/res/raw/"
+ getResources().getResourceName(playList[position])));
// start playback and change btn images accordingly
mediaPlayer.start();
changeView(position);
// also you forgot to update play variable to indicate the index of current song
// that is being played
play = position;
} catch (IOException e) {
Toast.makeText(MainActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void changeView(int position) {
// I guess this needs a little bit of modification as
// For eg: if btn1 is clicked, btn1 should show pause img in theory
// same goes for all other buttons
// try to handle it yourself
if (position == 0) {
btn1.setImageResource(R.drawable.ic_play_circle_outline_black_24dp);
btn2.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
btn3.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
} else if (position == 1) {
btn1.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
btn2.setImageResource(R.drawable.ic_play_circle_outline_black_24dp);
btn3.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
} else if (position == 2) {
btn1.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
btn2.setImageResource(R.drawable.ic_pause_circle_outline_black_24dp);
btn3.setImageResource(R.drawable.ic_play_circle_outline_black_24dp);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
// releasing the mediaplayer is must so that you do not leak resources
if (mediaPlayer != null)
mediaPlayer.release();
}
}

Questions about my memory problem for my soundboard android app (E/MediaPlayerNative: error (1, -19))

i have buttons to play sounds, they all works individually, after 14+ uses they dont work anymore if i doesn't restart the app
already tried to mediaplayer.realease after each use, doesnt work, think it is a memory problem dont know how do deal with it
MediaPlayer SonDeadliest
protected void onCreate(Bundle savedInstanceState)
{
boutonDeadliest.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
SonDeadliest = MediaPlayer.create(getApplicationContext(),R.raw.themostdeadliestganginuganda);
SonDeadliest.start();
fin(SonDeadliest);
}
});
public void fin(MediaPlayer m)
{
if(m.isPlaying())
{
}
else
{
m.stop();
m.release();
}
}
i have like 24 buttons, i'm trying to get an app with everything that works without having to restart the application thank you :)
The problem is that using MediaPlayer repeatedly in this way can be misleading:
SonDeadliest = MediaPlayer.create(getApplicationContext(),R.raw.themostdeadliestganginuganda);
SonDeadliest.start();
It will consume unnecessary resources.
For a better understanding I suggest that you read this post. It is written using Kotlin but with a little of kotlin study you can understand.
Here is a implementation in Java, trying to use your scenario:
MediaPlayer myMediaPlayer;
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//Media Player setup
myMediaPlayer = new MediaPlayer();
myMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
myMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mp.reset();
}
});
//Buttons
Button button1 = view.findViewById(R.id.button_record1);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playSound(R.raw.record1);
}
});
Button button2 = view.findViewById(R.id.button_record2);
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
playSound(R.raw.record2);
}
});
}
void playSound(int rawResId) {
try {
AssetFileDescriptor afd = getContext().getResources().openRawResourceFd(rawResId);
if (afd != null) {
myMediaPlayer.reset();
myMediaPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
myMediaPlayer.prepareAsync();
}
} catch (Exception ex) {
Log.d("MediaPLayer", "playSound exception: " + ex.getMessage());
}
}
The code can be improved, but my intention here was just to facilitate the comprehension. I'm using only 2 buttons for simplification. But I suggest you to consider using better solutions instead of creating a listener to each one of the 24 buttons. (Take a look on DataBinding, passing the resource as reference).

Android mediaplayer next song onButton Click

Button btnPlayPause, btnNext, btnPrevious;
Bundle b;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song);
btnPlayPause = (Button) findViewById(R.id.btnPlayPause);
btnNext = (Button) findViewById(R.id.btnNext);
btnPrevious = (Button) findViewById(R.id.btnPrevious);
Intent currSong = getIntent();
b = currSong.getExtras();
btnPlayPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
if (mediaPlayer != null) {
if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
btnPlayPause.setText("Play");
} else {
mediaPlayer.start();
btnPlayPause.setText("Stop");
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btnPlayPause.setText("Play");
}
});
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
int songIndex = (int) b.get("songIndex");
#Override
public void onClick(View v) {
if (songIndex < songList.size() - 1) {
songIndex = songIndex + 1;
Toast.makeText(getApplicationContext(), "You Clicked " + songIndex , Toast.LENGTH_SHORT).show();
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.setDataSource(songList.get(songIndex).getData());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}else{
songIndex=0;
}
}
});
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (songIndex > 0){
songIndex = songIndex-1;
Toast.makeText(getApplicationContext(), "You Clicked " + songIndex , Toast.LENGTH_SHORT).show();
try {
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.setDataSource(songList.get(songIndex).getData());
mediaPlayer.prepareAsync();
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}else {
songIndex = songList.size() - 1;
}
}
});
}
}
So when i click on the next button, it plays the second song, but at the end of my songlist it skips the first song from the list stored in [0] and on second click it goes to [1] so there is always one song not playing.
How can i solve this or is there an easier way too go to the next song?
Thanks,
-Vince
EDIT;
Problem 2; when i choose a song, lets say with position 37, and i click on previous it goes to 36, but if i then click on next it goes to 38, so it skips the song i played first.
EDIT 2 ;
Ok problems still persists, but i found out that when i click a few times on previous btn let's say i start from position 25 and go to 15 with the previous btn, and when i then click on next again it just starts to count from 25. How can i solve this? Thanks in advance, - vince
Ok, you have several problems here:
i found out that when i click a few times on previous btn let's say i start from position 25 and go to 15 with the previous btn, and when i then click on next again it just starts to count from 25
In PlayNext's first line, you reassign songIndex to the original songIndex passed to the activity. PlayPrevious uses another songIndex that I can't see where is defined. If you had followed Android guidelines to always prefix with an "m" the class properties vs local variables, you'd easily have realised it.
So when i click on the next button, it plays the second song, but at the end of my songlist it skips the first song from the list stored in [0] and on second click it goes to [1]
The edge cases where user plays the next after the last song, or the previous after the first are incorrectly coded. In those cases you correctly update songIndex, but do not call play.
Besides the problems, what you should do is to rework your code a little using functions, to avoid repeating functionality. That is always prone to these kind of errors. I'd suggest something like this:
int mCurrentIndex; // always prefix class properties with an "m"
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_song);
Button btnPlayPause = (Button) findViewById(R.id.btnPlayPause),
btnNext = (Button) findViewById(R.id.btnNext),
btnPrevious = (Button) findViewById(R.id.btnPrevious);
Intent currSong = getIntent();
Bundle b = currSong.getExtras();
// load initial index only once
mCurrentIndex = (int) b.get("songIndex");
btnPrevious.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex = mCurrentIndex > 0 ? mCurrentIndex - 1 : mSongList.size() - 1;
playSongNumber(mCurrentIndex);
}
}
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mCurrentIndex++;
mCurrentIndex %= mSongList.size();
playSongNumber(mCurrentIndex);
}
}
}
private void playSongNumber(int index) {
try {
mMediaPlayer.stop();
mMediaPlayer.reset();
mMediaPlayer.setDataSource(mSongList.get(index).getData());
mMediaPlayer.prepareAsync();
mMediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
slightly cleaner, isn't it?

My step counter does not reset the steps, even after uninstall

I use Sensor.TYPE_STEP_COUNTER I know it only resets when rebooting. Is there an alternative way to reset the steps to 0 when pressing a button?
Please see my code, you will find the Runactivity.class
Maybe I can do it in another way which resets the steps.
without having me to reboot every time.
public class RunActivity extends AppCompatActivity implements SensorEventListener{
private SensorManager sensorManager;
private TextView count;
boolean activityRunning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_run);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
Bundle bundle = getIntent().getExtras();
final String naam = bundle.getString("naam");
TextView NaamView = null;
Button stopRun = (Button) findViewById(R.id.stopRun);
count = (TextView) findViewById(R.id.countView);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
NaamView = (TextView) findViewById(R.id.naamRunText);
NaamView.setText(naam);
stopRun.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String countValue = count.getText().toString();
Log.d("countVAL", String.valueOf(countValue));
Intent myIntent = new Intent(RunActivity.this, HomeScreenActivity.class);
Bundle bundle = new Bundle();
bundle.putString("naam", naam);
sensorManager.flush(RunActivity.this);
sensorManager.unregisterListener(RunActivity.this);
count.setText("0");
onStop();
myIntent.putExtras(bundle);
startActivity(myIntent);
}
});
}
#Override
protected void onResume() {
super.onResume();
activityRunning = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if(countSensor != null){
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
}else{
Toast.makeText(this, "Jouw apparaat heeft geen sensor!", Toast.LENGTH_LONG) .show();
}
}
#Override
public void onSensorChanged(SensorEvent event) {
if(activityRunning){
count.setText(String.valueOf(event.values[0]));
}else{
event.values[0] = 0;
}
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
activityRunning = false;
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
protected void onDestroy() {
super.onDestroy();
}
}
When you click the reset button in the app save the current step count to SharedPreferences. And you'll need a way to find out when was the last reboot because every time you reboot the saved count number gets invalid.
private Integer stepsInSensor;
private Integer stepsAtReset;
void onCreate() {
SharedPreferences prefs = getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE);
stepsAtReset = prefs.getInt("stepsAtReset", 0);
}
public void onClick(View v) {
stepsAtReset = stepsInSensor;
if (stepsAtReset != null) {
SharedPreferences.Editor editor =
getSharedPreferences(MY_PREFS_NAME, MODE_PRIVATE).edit();
editor.putInt("stepsAtReset", stepsAtReset);
editor.commit();
}
// you can now display 0:
count.setText(String.valueOf(0));
}
#Override
public void onSensorChanged(SensorEvent event) {
if(activityRunning){
stepsInSensor = Integer.valueOf(event.values[0]);
if (stepsAtReset = null) {
stepsAtReset = stepsInSensor;
}
int stepsSinceReset = stepsInSensor - stepsAtReset;
if (stepsSinceReset < 0) {
stepsAtReset = stepsInSensor;
stepsSinceReset = 0;
}
count.setText(String.valueOf(stepsSinceReset));
}else{
event.values[0] = 0;
}
}
I searched on it and tried to do it with different ways. Nothing Helped.
Then I found the most simple way possible.
In onSensorChanged() just add the counter so when ever onSensorChanged() will be called (it will be called on every step), counter will simply count the steps then show this counter to your UI instead of showing the value of event.values[0]
on your Reset button make the counter 0 again.
Nope, based on the Sensor API
A sensor of this type returns the number of steps taken by the user
since the last reboot while activated. The value is returned as a
float (with the fractional part set to zero) and is reset to zero only
on a system reboot.
It can only be reset when the system is rebooted

Categories