Android传感器无法在服务中运行

Himanshu Tyagi

我是android编程的新手,以下是我的用例:我有一个活动“ MainActivity”和一个服务“ MyService”。我使用startService方法调用服务在MyService.java中,我注册了2个不同的传感器(加速度计和灯光),并尝试获取传感器值。这似乎很基本,我通过以下方式进行编码:MainActivity.java

public class MainActivity extends AppCompatActivity{
@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Intent i = new Intent(MainActivity.this, MyService.class);

        startService(i);
    }

MyService.java

public class MyService extends Service implements SensorEventListener{
    public MyService() {
    }

    private SensorManager sensorManager;    // this instance of SensorManager class will be used to get a reference to the sensor service.
    private Sensor mSensor,lSensor;         // this instance of Sensor class is used to get the sensor we want to use.
    private float[] mGravity;
    private float mAccel;
    private float mAccelCurrent;
    private float mAccelLast;

    public void onAccuracyChanged(Sensor sensor,int accuracy){

    }

    //    // if sensor value is changes, change the values in the respective textview.
    public void onSensorChanged(SensorEvent event){
        Log.d("sensorService", "onSensorChanged.");
        Toast.makeText(MyService.this, "onSensorChanged", Toast.LENGTH_SHORT).show();

        /* check sensor type */
        if(event.sensor.getType()==Sensor.TYPE_ACCELEROMETER){

            mGravity = event.values.clone();
            // assign directions
            float x=event.values[0];
            float y=event.values[1];
            float z=event.values[2];

            float x1=event.values[0];
            float y1=event.values[1];
            float z1=event.values[2];
            mAccelLast = mAccelCurrent;
            mAccelCurrent = (float)Math.sqrt(x*x + y*y + z*z);      // we calculate the length of the event because these values are independent of the co-ordinate system.
            float delta = mAccelCurrent - mAccelLast;
            mAccel = mAccel*0.9f + delta;
            if(mAccel > 3)
            {
                Toast.makeText(MyService.this, "Movement Detected.", Toast.LENGTH_SHORT).show();
            }
        }
        else if(event.sensor.getType()==Sensor.TYPE_LIGHT)
        {
            float l = event.values[0];
        }

        /* unregister if we just want one result. */
//        sensorManager.unregisterListener(this);

    }

    @Override
    public void onCreate() {
        super.onCreate(); // if you override onCreate(), make sure to call super().
        // If a Context object is needed, call getApplicationContext() here.
        Log.d("MyService", "onCreate");
        sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);          // get an instance of the SensorManager class, lets us access sensors.
        mSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);    // get Accelerometer sensor from the list of sensors.
        lSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);            // get light sensor from the list of sensors.
        mAccel = 0.00f;
        mAccelCurrent = SensorManager.GRAVITY_EARTH;
        mAccelLast = SensorManager.GRAVITY_EARTH;

    }

    public int onStartCommand(Intent intent, int flags, int startId){
        Log.d("MyService", "onStartCommand");
        sensorManager=(SensorManager) getSystemService(SENSOR_SERVICE);          // get an instance of the SensorManager class, lets us access sensors.
        mSensor = sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);    // get Accelerometer sensor from the list of sensors.
        lSensor = sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT);            // get light sensor from the list of sensors.
        mAccel = 0.00f;
        mAccelCurrent = SensorManager.GRAVITY_EARTH;
        mAccelLast = SensorManager.GRAVITY_EARTH;
        return START_STICKY;
    }



    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

Manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.tyagi.smartalarm" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/web_hi_res_512"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:theme="@style/AppTheme.NoActionBar" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name=".AlarmReceiver"
            android:process=":remote" >

            <!-- define android:process=":remote" so that the BroadcastReceiver will run in a separate process -->
            <!-- so that it will continue to stay alive if the app has closed. -->
        </receiver>

        <service
            android:name=".sensorService"
            android:exported="false" />
        <!-- exported determines whether or not the service can be executed by other applications. -->

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true" >
        </service>
    </application>

</manifest>

由于onSensorChanged未调用MyService.java文件中方法,因此这似乎不起作用我真的无法弄清楚哪里出了问题。任何帮助表示赞赏。提前致谢。

大卫·水

您需要注册一个监听器onSensorChanged()才能被调用。您缺少这样的代码:

sensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
sensorManager.registerListener(this, lSensor, SensorManager.SENSOR_DELAY_NORMAL);

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

Android无法从片段启动传感器服务类

来自分类Dev

获取Android中的传感器列表

来自分类Dev

如何打开 GPS 传感器并从 Android M 中的服务获取位置?

来自分类Dev

android服务记录传感器数据不间断

来自分类Dev

android服务记录传感器数据不间断

来自分类Dev

为什么在Android中缺少传感器类型3?

来自分类Dev

TYPE_SIGNIFICANT_MOTION传感器在Android中的实现

来自分类Dev

如何在Android中检测双击接近传感器?

来自分类Dev

Android接近传感器问题仅在Samsung设备中

来自分类Dev

ListView名称传感器Android中的错误

来自分类Dev

Android传感器registerListener在单独的线程中

来自分类Dev

如何在Android中检测双击接近传感器?

来自分类Dev

为什么在Android中缺少传感器类型3?

来自分类Dev

触摸传感器无法正常工作

来自分类Dev

Ubuntu无法读取温度传感器?

来自分类Dev

触摸传感器无法正常工作

来自分类Dev

lm传感器无法检测风扇

来自分类Dev

Android如何设置传感器延迟?

来自分类Dev

Android传感器和线程

来自分类Dev

Android传感器直立旋转

来自分类Dev

Android传感器和线程

来自分类Dev

Android传感器直立旋转

来自分类Dev

如何注销多个传感器的android

来自分类Dev

Android上的冗余运动传感器?

来自分类Dev

Moto 360中的传感器列表

来自分类Dev

Webots与Pycharm中的马达/传感器

来自分类Dev

消除传感器测量中的峰值

来自分类Dev

当应用程序在后台运行时,Android传感器会监听

来自分类Dev

我可以在同一服务中收听两个传感器吗?