I created a simple app to learn how to use sensor heart beat with one button and label here is my code:
public class MainActivity extends AppCompatActivity implements SensorEventListener {
Button show;
TextView showHeartRate;
SensorManager sensorMgr;
Sensor heartRate;
String heartRateValue;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
show = (Button) findViewById(R.id.button);
show.setOnClickListener(displayHeartRate);
showHeartRate = (TextView) findViewById(R.id.showHeartRate);
sensorMgr = (SensorManager)this.getSystemService(SENSOR_SERVICE);
heartRate = sensorMgr.getDefaultSensor(Sensor.TYPE_HEART_RATE);
}
View.OnClickListener displayHeartRate = new View.OnClickListener() {
#Override
public void onClick(View view) {
showHeartRate.setText(heartRateValue);
}
};
#Override
protected void onResume() {
super.onResume();
sensorMgr.registerListener(this,heartRate,SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onPause() {
super.onPause();
sensorMgr.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
heartRateValue = Integer.toString(sensorEvent.sensor.getType());
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
I add to the manifest:
<uses-permission android:name="android.permission.BODY_SENSORS"/>
the problem is that the onSensorChanged() is not called.
i check a lot of solutions here but i did not find anything
First, why would you expect it to ask permissions to use your camera if its heartrate sensor that you are trying to use?
Second, I think by the time you click 'display heartrate', you just don't have any data from the sensor yet (heartRateValue is empty), and when data finally comes you don't really update UI, you only update your state. What I suggest is to update your UI state on every sensor change, for example:
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
heartRateValue = Integer.toString(sensorEvent.sensor.getType());
showHeartRate.setText(heartRateValue);
}
or you can avoid code duplication (even thought its only one line), create a setter and and call it from both click handler and sensor handler:
private void setHeartrate(String rate) {
showHeartRate.setText(rate);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
heartRateValue = Integer.toString(sensorEvent.sensor.getType());
setHeartrate(heartRateValue);
}
View.OnClickListener displayHeartRate = new View.OnClickListener() {
#Override
public void onClick(View view) {
setHeartrate(heartRateValue);
}
};
Third, you are not using data from your sensor, look at SensorEvent, data comes in values array and you are only trying to displat sensor type, why? Try this:
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
heartRateValue = Integer.toString(sensorEvent.values.length > 0 ? sensorEvent.values[0] : 0.0f);
showHeartRate.setText(heartRateValue);
}
Related
I am trying to make a button in activity2(settings page), when the button is clicked, then the title of activity1(MainActivity) will change to what I set to. I have been trying to use interface to carry out the function but it gives me a null pointer exception error.
MainActivity
#Override
public void changeActionBarTitle(String editText){
actionTitle = editText;
setTitle(actionTitle);
};
Interface
public interface ActionBarInterface {
void changeActionBarTitle(String editText);
}
Setting page (activity 2)
public class SettingsPage extends AppCompatActivity {
ActionBarInterface actionBarInterface;
Button editCompanyNameButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings_page);
setTitle("Settings");
editCompanyNameButton = findViewById(R.id.editCompanyNameButton);
editCompanyNameButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
actionBarInterface.changeActionBarTitle("test");
}
});
}
}
Thanks.
You can try this code without using the interface
MainActivity:
#Override
protected void onResume() {
setTitle(Main2Activity.title);
super.onResume();
}
activity2:
public class SettingsPage extends AppCompatActivity {
Button editCompanyNameButton;
static String title;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
setTitle("Settings");
editCompanyNameButton = findViewById(R.id.editCompanyNameButton);
editCompanyNameButton.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view){
title = "test";
}
});
}
}
It gives a null pointer exception error because actionBarInterface was not initialised.
Check out topics on 'Getting a Result from an Activity', making use of classes and functions such as Intent, startActivityForResult, onActivityResult.
Android: how to make an activity return results to the activity which calls it?
I was working in a very simple music player with a seek bar. But I got a problem with playing music,it doesn't work correctly every second - it backwards a while, then remain again like it's a buggy.
I know why but I can't solve it.
When the progress bar moves forward, the music recalibrates and vice versa, when the music moves forward, the progress bar recalibrates.
It's probably because of that that every time it goes back.
But I tried several things and still have the same problem.
Another problem is that when the music is paused, the progress bar goes in the opposite direction until it reaches zero. It doesn't stay where it was before the break.
The full code :
public class MainActivity extends AppCompatActivity {
private MediaPlayer mediaPlayer;
private SeekBar seekBar;
private boolean bool = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.seekBar = (SeekBar) findViewById(R.id.sound_bar);
this.mediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.music);
Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition() * seekBar.getMax() / mediaPlayer.getDuration());
}
}, 500, 500);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
mediaPlayer.seekTo(seekBar.getProgress() * mediaPlayer.getDuration() / seekBar.getMax());
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
}
public void playSound(View view) {
Button button = (Button) view;
if(bool) {
mediaPlayer.pause();
bool = false;
button.setText("Jouer le son");
} else {
mediaPlayer.start();
bool = true;
button.setText("Mettre en pause");
}
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.pause();
}
#Override
protected void onStart() {
super.onStart();
if(bool) {
mediaPlayer.start();
}
}
}
Maybe use another thread to control the seekbar would help.
Take a look at this
Here is my code. I'm very new to Java and I know that this question is already been posted but still I didn't get the expected outpost so I had to post.
public class MainActivity extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final MediaPlayer policeSound = MediaPlayer.create(this, R.raw.police);
Button policeSounds = (Button) this.findViewById(R.id.police);
policeSounds.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (policeSound.isPlaying()){
policeSound.stop();
}
else {
policeSound.start();
}
}
});
}
}
I tried adding onBackPressed() code to this but it couldn't detect the 'policeSound' as it was detected in the previous method!
And someone please even teach me how to use #Override annotations!
To detect the 'policeSound' in other methods you need to make it be a field of a class:
private MediaPlayer policeSound;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
policeSound = MediaPlayer.create(this, R.raw.police);
Button policeSounds = (Button) this.findViewById(R.id.police);
policeSounds.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (policeSound.isPlaying()) {
policeSound.stop();
} else {
policeSound.start();
}
}
}
);
}
In your codes policeSound is a local variable which is be seen only in Oncreate() method,as Oleh Sokolov said, you should declare policeSound as a field of class.
About #Override , you could see this good explanation
and in android studio , when you press ctrl + o in java class file, you can override superclass method, and IDE will add #Override automatically for you.
I just started out on android and java yesterday, and i'm having a problem. I'm trying to output a sensor's values to some TextViews. The text updates, but with the values set at definition. onSensorChanged should update these values right?
import [...]
public class MainActivity extends Activity implements SensorEventListener {
public float[] gravity = {0,0,0};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView gravxTxtView = (TextView) findViewById(R.id.gravxTxtView);
final TextView gravyTxtView = (TextView) findViewById(R.id.gravyTxtView);
final TextView gravzTxtview = (TextView) findViewById(R.id.gravzTxtView);
final Handler handler = new Handler();
handler.postDelayed(
new Runnable() {
#Override
public void run() {
gravxTxtView.setText("Gravity x: " + Float.toString((gravity[0])));
gravyTxtView.setText("Gravity y: " + Float.toString((gravity[1])));
gravzTxtview.setText("Gravity z: " + Float.toString((gravity[2])));
}
}, 500);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
#Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
gravity[0] = event.values[0];
gravity[1] = event.values[1];
gravity[2] = event.values[2];
}
}
}
There are some serious steps you are missing
1. Get the instance of sensor manager
SensorManager sensorManager=(SensorManager)getSystemService(SENSOR_SERVICE);
2. Get the instance of the sensor
Sensor accel=sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
3. Register sensor to the lister class which implements SensorEventListener in your case you have implemented on the MainActivity so it will be this
sensorManager.registerListener(this, accel, SensorManager.SENSOR_DELAY_NORMAL);
now when certain change will happen it will call the onSensorChanged method ,please let me know its working or not
I want to add my recorded audio in background of the activity in which I am explaining an example. Problem is that audio do not stop after ending the activity and it keeps on playing. I want audio only to be played when my activity is at front. Kindly put the service class in following code
public class exp extends Activity {
ImageView imview1,imview2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addexample);
imview2 = (ImageView) findViewById(R.id.imageView2);
imview2.setVisibility(View.INVISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
imview2.setVisibility(View.VISIBLE);
}
}, 2000);
}
}
In onResume start your audio
#Override
protected void onResume() {
super.onResume();
//start your audio track here
}
Stop the same in onPause
#Override
protected void onPause() {
//Sop it over here
super.onPause();
}
Create the player instances in onCreate
public class exp extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addexample);
//player starting code goes here.
}
protected void onPause() {
//stop the music player here.
}
}
Try to stop your audio in onPause:
public class exp extends Activity {
ImageView imview1,imview2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.addexample);
imview2 = (ImageView) findViewById(R.id.imageView2);
imview2.setVisibility(View.INVISIBLE);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
imview2.setVisibility(View.VISIBLE);
}
}, 2000);
}
#Override
public void onPause(){
super.onPause();
//Kill your audio
}
}
I think your solution is something like that. Try it and comment
Good look!