How to create separate class with sensor results - java

I have w problem with simple code: In mainActivity i need check if sensor for example Light sensor is available on phone, and if is available i need to reed and show the results of this senson on screen, but code responsible for read data from sensor must be in separate class. I wrote simple code, but it doesn't work. When i run this code, my phone show me only : "Light level: 0.0". I'm beginner in programming so please help me..
Main class:
public class MainActivity extends Activity {
LightSensor mLightSensor = null;
protected SensorManager mSensorManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView wyswietl = (TextView)findViewById(R.id.res);
mLightSensor = new LightSensor();
mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
if (mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT) != null){
LightSensor lS = new LightSensor();
wyswietl.setText("Light level: " + Float.toString(lS.lux));
}
else{
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
protected void onResume(){
super.onResume();
mLightSensor.register();
}
#Override
protected void onPause(){
super.onPause();
mLightSensor.unregister();
}
}
and LightSensor class:
public class LightSensor implements SensorEventListener {
SensorManager mSensorManager;
Sensor lightManager;
public float lux;
public Context context;
public void onCreateLight(Context context){
this.context = context;
mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
lightManager = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent event) {
// TODO Auto-generated method stub
lux = event.values[0];
}
public void register(){
mSensorManager.registerListener(this, lightManager, SensorManager.SENSOR_DELAY_NORMAL);
}
public void unregister(){
mSensorManager.unregisterListener(this);
}
}

I haven't tested it, but you could possibly make a new method in your LightSensor class to return the lux variable to the main class
Something like:
public float getLux(){
return lux;
}
and then in your "MainActivity" class you can call
float newLux = mLightSensor.getLux();
If it doesn't work I might have a slightly more complex solution.

You never call mLightSensor.onCreateLight();
How about changing onCreateLight to be your LightSensor class' constructor. That would solve the problem and not require you to remember to call onCreateLight.
public LightSensor(Context context){
this.context = context;
mSensorManager = (SensorManager)context.getSystemService(Context.SENSOR_SERVICE);
lightManager = mSensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);
}

Related

Is it possible to send a notification to a user when the barometric pressure gets low?

In my app, I want to send a notification to the user when the barometric pressure gets below a certain number.
I know I have to use an if statement, so I have been trying it for a few days now. I tried using the if statement with a TextView, which gets the barometric pressure, but this hasn't worked......
public class MainActivity extends AppCompatActivity {
private TextView txt;
private SensorManager sensorManager;
private Sensor pressureSensor;
private SensorEventListener sensorEventListener = new SensorEventListener() {
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
float[] values = sensorEvent.values;
txt.setText(String.format("%.3f mbar", values[0]));
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
txt = findViewById(R.id.barometric);
//Here is the code I tried... But it is already underlined in red...
if(barometric < 90.5){
}
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
pressureSensor = sensorManager.getDefaultSensor(Sensor.TYPE_PRESSURE);
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.settings);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startActivity(new Intent(MainActivity.this, Main2Activity.class));
}
});
}
#Override
protected void onResume() {
super.onResume();
sensorManager.registerListener(sensorEventListener, pressureSensor, SensorManager.SENSOR_DELAY_UI);
}
#Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(sensorEventListener);
}
}

How to store steps taken daily and reset the app step count daily?

I am working on a step counter and I want to store the steps taken last day and reset the step count next day while still storing the previous data in another textView.
Here's my code:
public class StepsActivity extends AppCompatActivity implements SensorEventListener {
SensorManager sensorManager;
TextView textView;
boolean running=false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_steps);
textView = (TextView)findViewById(R.id.tv_steps);
sensorManager =(SensorManager)getSystemService(Context.SENSOR_SERVICE);
}
#Override
protected void onResume() {
super.onResume();
running = true;
Sensor countSensor = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
if (countSensor != null) {
sensorManager.registerListener(this, countSensor, SensorManager.SENSOR_DELAY_UI);
} else {
Toast.makeText(this,"Sensor not found", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onPause() {
super.onPause();
running = false;
sensorManager.unregisterListener(this);
}
#Override
public void onSensorChanged(SensorEvent sensorEvent) {
if (running) {
textView.setText(String.valueOf(sensorEvent.values[0]));
}
}
#Override
public void onAccuracyChanged(Sensor sensor, int i) {
}
}

Thread class and pass information to main activity class into TextView

I would like to make method onSenzorChange run into thread. To run more smooth. And get information of x axis everytime change. And pass it to main class (Activity) into TextView.
MainActivity class :
public class MainActivity extends AppCompatActivity {
TextView textView;
TestOfPassUIThread t;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textView);
t = new TestOfPassUIThread(this);
}
public void onStart(View view) {
t.register();
}
}
TestOfPassUIThread class ( not an activity or anything )
public class TestOfPassUIThread implements SensorEventListener {
private SensorManager sensorManager;
private Sensor sensor;
public TestOfPassUIThread (Context context) {
sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
}
public void register(){
sensorManager.registerListener(this, sensor, SensorManager.SENSOR_DELAY_NORMAL);
}
public void unregister() {
sensorManager.unregisterListener(this);
}
// Want this method be in Thread
//How can I do this ?
#Override
public void onSensorChanged(SensorEvent event) {
float xAxis = event.values[0];
// And I want it to display in TextView!
// In main activity would be textView.setText("" + xAxis);
//How to pass it to MainActivity class ?
}
#Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
There are multiple ways to achieve writing on the textview, the following is one way to do it. (you may wanna read about callbacks, check How to implement callbacks in Java).
As for accessing the UI thread from the background, there multiple ways to do it as well (check: Running code in main thread from another thread).
For why we used a HandlerThread below, you can read about it here: Acclerometer Sensor in Separate Thread.
So your listener becomes:
public abstract class TestOfPassUIThread implements SensorEventListener {
private SensorManager sensorManager;
private Sensor sensor;
private HandlerThread handlerThread;
private Context context;
private Runnable uiRunnable;
private float xAxis;
public TestOfPassUIThread (Context context) {
this.context = context;
sensorManager = (SensorManager) context.getSystemService (Context.SENSOR_SERVICE);
sensor = sensorManager.getDefaultSensor (Sensor.TYPE_ACCELEROMETER);
}
public void register () {
initUiRunnable ();
handlerThread = new HandlerThread ("sensorHandler");
handlerThread.start ();
sensorManager.registerListener (
this,
sensor,
SensorManager.SENSOR_DELAY_NORMAL,
new Handler (handlerThread.getLooper ())
);
}
public void unregister () {
sensorManager.unregisterListener (this);
try {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
handlerThread.quitSafely ();
return;
}
handlerThread.quit ();
} finally {
uiRunnable = null;
}
}
#Override
public void onSensorChanged (SensorEvent event) {
xAxis = event.values [0];
// your other background operations
((Activity)context).runOnUiThread (uiRunnable);
// your other background operations
}
#Override
public void onAccuracyChanged (Sensor sensor, int accuracy) {
}
private void initUiRunnable () {
uiRunnable = new Runnable () {
#Override
public void run () {
// ...... your other UI operations
fillTextView (xAxis);
// ...... your other UI operations
}
};
}
public abstract void fillTextView (float xAxis);
}
And your activity:
public class MainActivity extends AppCompatActivity {
private TextView textView;
private TestOfPassUIThread t;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
setContentView (R.layout.activity_main);
textView = (TextView)findViewById (R.id.textView);
t = new TestOfPassUIThread (this) {
#Override
public void fillTextView (float xAxis) {
textView.setText ("Current xAxis: " + xAxis);
}
};
}
#Override
protected void onResume () {
super.onResume ();
t.register ();
}
#Override
protected void onPause () {
t.unregister ();
super.onPause ();
}
}
Also, when you override LifeCycle methods of Activities such as onStart, onResume etc..., make sure to call the super.lifeCycleMethod.

Android Wear App Crashes when Register a Sensor Listener

I'm trying to create a step counter app for Android Wear. My problem is when I Register a Sensor Listener
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_FASTEST);
}
The app crash but if I deleted the code above the app works but of curse the sensor listener don't work so how can I make it work and here is the code
public class WearMainActivity extends Activity implements SensorEventListener {
private SensorManager mSensorManager;
private Sensor mStepDetectorSensor;
TextView stepNum;
int steps = 12;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_wear_main);
final WatchViewStub stub = (WatchViewStub) findViewById(R.id.watch_view_stub);
stub.setOnLayoutInflatedListener(new WatchViewStub.OnLayoutInflatedListener() {
#Override
public void onLayoutInflated(WatchViewStub stub) {
stepNum = (TextView) findViewById((R.id.stepNum));
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mStepDetectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
}
});
}
protected void onResume() {
super.onResume();
mSensorManager.registerListener(this, mStepDetectorSensor, SensorManager.SENSOR_DELAY_FASTEST);
}
#Override
public void onSensorChanged(SensorEvent event) {
if (event.sensor.getType() == Sensor.TYPE_STEP_DETECTOR) {
stepNum.setText(String.valueOf(steps));
}
}
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
protected void onStop() {
super.onStop();
mSensorManager.unregisterListener(this,mStepDetectorSensor);
}
}
You should declare these two variables inside the onResume method:
protected void onResume() {
super.onResume();
mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
mStepDetectorSensor = mSensorManager.getDefaultSensor(Sensor.TYPE_STEP_DETECTOR);
mSensorManager.registerListener(this, mStepDetectorSensor, SensorManager.SENSOR_DELAY_FASTEST);
}
and unregister the sensor in onPause

Sensor_Service cannont be resolved as a variable

I'm getting an error on sensor service. I'm pretty sure that's the right syntax, unless I'm missing something. Just need that part for the accelerometer. Greatly appreciate if you could post thoughts.
public class AskQuestions extends Fragment {
private SensorManager mSensorManager;
private Sensor mAccelerometer;
private ShakeDetector mShakedetector;
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_questions, container, false);
//Error
mSensorManager = getSystemService(SENSOR_SERVICE);
mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
mShakedetector = new ShakeDetector(new OnShakeListener() {
#Override
public void onShake() {
// TODO Auto-generated method stub
handleNewAnswer();
}
});
return rootView;
}
#Override
public void onResume(){
super.onResume();
mSensorManager.registerListener(mShakedetector, mAccelerometer,
SensorManager.SENSOR_DELAY_UI);
}
#Override
public void onPause(){
super.onPause();
mSensorManager.unregisterListener(mShakedetector);
}
private void handleNewAnswer() {
if(makeMethink == true) {
result = answer.makeMeThink();
}else if(WhatsTheAnswer == true){
result = answer.whatsTheAnswer();
} else if (inspireMe){
result = answer.inspireQuotes();
}
displayAnswer.setText(result);
}
}
Use this instead:
mSensorManager = (SensorManager) getActivity().getSystemService(Context.SENSOR_SERVICE);
The problem is the code you used only works in a subclass of Context (e.g. Activity). Fragment is not a subclass of Context, so you have to get an object of that type in order to get the system service. Luckily, in a Fragment, you can easily get the container Activity with getActivity().
SENSOR_SERVICE is a constant that is defined in Context, so you have to write Context.SENSOR_SERVICE whenever you use it from outside a subclass of Context.

Categories

Resources