有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java Android传感器在服务中不工作

我对安卓编程相当陌生,以下是我的使用案例: 我有一个活动“MainActivity”和一个服务“MyService”。我使用startService方法调用我的服务。在我的服务中。在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);
    }

我的服务。爪哇

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");
    }
}

舱单。xml

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

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

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

        <receiver
            安卓:name=".AlarmReceiver"
            安卓:process=":remote" >

            <!-- define 安卓: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
            安卓:name=".sensorService"
            安卓:exported="false" />
        <!-- exported determines whether or not the service can be executed by other applications. -->

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

</manifest>

这似乎不像MyService中的onSensorChanged方法那样有效。java文件不会被调用。我真的搞不清楚我哪里出了问题。感谢您的帮助。 提前谢谢


共 (1) 个答案

  1. # 1 楼答案

    要调用onSensorChanged(),需要注册一个侦听器。您缺少如下代码:

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