我是靠谱客的博主 谨慎草莓,最近开发中收集的这篇文章主要介绍android psensor测试,android传感器Gsensor和Psensor的使用举例,觉得挺不错的,现在分享给大家,希望可以做个参考。

概述

今天leader给的任务是这样的,做一个开机自启动的后台Service,实现对重力及距离的检测

当手机屏幕朝下时,让Psensor可用。否则不可用

实现代码如下:

SensorFunctionService.java

package com.sensor.demo;

import android.app.Service;

import android.content.Context;

import android.content.Intent;

import android.hardware.Sensor;

import android.hardware.SensorEvent;

import android.hardware.SensorEventListener;

import android.hardware.SensorManager;

import android.os.IBinder;

import android.os.PowerManager;

public class SensorFunctionService extends Service {

private static final String LOG_TAG = "SensorDemoActivity";

private static final int PROXIMITY_SCREEN_WAKE_LOCK = 32;

private static final float CRITICAL_ANGLE = -5.0f;

private static final int Z_ORATIATION = 2;

private SensorManager mSensorManager;

private Sensor mGsensor;

private SensorEventListener mGsensorListener;

private PowerManager pm;

private PowerManager.WakeLock mProximityWakeLock;

private boolean pSensorOpened;

@Override

public void onCreate() {

super.onCreate();

pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

mProximityWakeLock =

pm.newWakeLock(PROXIMITY_SCREEN_WAKE_LOCK, LOG_TAG);

mSensorManager= (SensorManager) getSystemService(SENSOR_SERVICE);

mGsensor = mSensorManager.getDefaultSensor(Sensor.TYPE_GRAVITY);

mGsensorListener = new SensorEventListener() {

@Override

public void onAccuracyChanged(Sensor sensor, int accuracy) {

}

@Override

public void onSensorChanged(SensorEvent event) {

if(event.values[Z_ORATIATION] < CRITICAL_ANGLE){//screen up

if(!pSensorOpened){

pSensorOpened = true;

mProximityWakeLock.acquire();//open PSensor function

}

} else if(pSensorOpened){//screen down

pSensorOpened = false;

mProximityWakeLock.release();//close PSensor function

}

}

};

mSensorManager.registerListener(mGsensorListener, mGsensor, SensorManager.SENSOR_DELAY_GAME);

}

@Override

public IBinder onBind(Intent arg0) {

return null;

}

}

BootCompletedReceiver.java

package com.sensor.demo;

import com.sensor.demo.SensorFunctionService;

import android.content.BroadcastReceiver;

import android.content.Context;

import android.content.Intent;

import android.util.Log;

public class BootCompletedReceiver extends BroadcastReceiver{

@Override

public void onReceive(Context context, Intent intent) {

// TODO Auto-generated method stub

Intent mIntent = new Intent(context, SensorFunctionService.class);

context.startService(mIntent);

}

}

Manifest.xml

package="com.sensor.demo"

android:versionCode="1"

android:versionName="1.0" >

android:icon="@drawable/ic_launcher"

android:label="@string/app_name" >

最后

以上就是谨慎草莓为你收集整理的android psensor测试,android传感器Gsensor和Psensor的使用举例的全部内容,希望文章能够帮你解决android psensor测试,android传感器Gsensor和Psensor的使用举例所遇到的程序开发问题。

如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(76)

评论列表共有 0 条评论

立即
投稿
返回
顶部