Guest User

Untitled

a guest
Aug 8th, 2020
42
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. package com.example.counter;
  2.  
  3. import androidx.appcompat.app.AppCompatActivity;
  4. import androidx.core.content.ContextCompat;
  5.  
  6. import android.Manifest;
  7. import android.content.pm.PackageManager;
  8. import android.hardware.Sensor;
  9. import android.hardware.SensorEvent;
  10. import android.hardware.SensorEventListener;
  11. import android.hardware.SensorManager;
  12. import android.os.Bundle;
  13. import android.view.WindowManager;
  14. import android.widget.TextView;
  15.  
  16. public class MainActivity extends AppCompatActivity implements SensorEventListener {
  17. private static final int PHYISCAL_ACTIVITY = 0;
  18. private TextView textKroki;
  19. private SensorManager sensorManager;
  20. private Sensor mLiczKrok;
  21. private boolean x;
  22. int LiczKroki;
  23. @Override
  24. protected void onCreate(Bundle savedInstanceState) {
  25. super.onCreate(savedInstanceState);
  26. setContentView(R.layout.activity_main);
  27. if(ContextCompat.checkSelfPermission(this,
  28. Manifest.permission.ACTIVITY_RECOGNITION) == PackageManager.PERMISSION_DENIED){
  29. //ask for permission
  30. requestPermissions(new String[]{Manifest.permission.ACTIVITY_RECOGNITION}, PHYISCAL_ACTIVITY);
  31. }
  32. getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
  33. textKroki= findViewById(R.id.textKroki);
  34. sensorManager= (SensorManager) getSystemService(SENSOR_SERVICE);
  35.  
  36. if(sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)!=null){
  37.  
  38. mLiczKrok = sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER);
  39. x= true;
  40. }
  41. else {
  42.  
  43. textKroki.setText("Brak sensora."); x=false;
  44. }
  45. }
  46.  
  47. @Override
  48. public void onSensorChanged(SensorEvent sensorEvent) {
  49. if (sensorEvent.sensor==mLiczKrok){
  50. LiczKroki= (int) sensorEvent.values[0];
  51. textKroki.setText(String.valueOf(LiczKroki));
  52. }
  53. }
  54.  
  55. @Override
  56. public void onAccuracyChanged(Sensor sensor, int i) {
  57.  
  58. }
  59.  
  60. @Override
  61. protected void onResume() {
  62. super.onResume();
  63. if(sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)!=null){
  64.  
  65. sensorManager.registerListener(this,mLiczKrok,SensorManager.SENSOR_DELAY_NORMAL);
  66. }
  67. }
  68. @Override
  69. protected void onPause() {
  70. super.onPause();
  71. if(sensorManager.getDefaultSensor(Sensor.TYPE_STEP_COUNTER)!=null){
  72. sensorManager.unregisterListener(this,mLiczKrok);
  73.  
  74. }
  75. }
  76. }
RAW Paste Data