在android中广播

时间:2015-07-06 12:50:15

标签: android broadcastreceiver sharedpreferences sensor

我写的程序与Android中的Proximity Sensors一起工作,一切似乎都是真的,但是当我运行我的应用程序时这是第一次工作,意味着当用户调用我的应用程序时检查框是错误的侦探服务并且不要使用接近传感器来接听电话,当复选框为真时,这意味着我的服务处于活动状态,当用户呼叫时,应答呼叫使用了接近传感器。 但所有这种情况 JUST 累计一次,其他时间处于错误或真实状态,我的app接听电话接近传感器 这是我的代码:

public class main extends PreferenceActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.setting);
    findPreference("AIR_CALL").setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
        @Override
        public boolean onPreferenceChange(Preference preference, Object newValue) {
            if (newValue.toString().equals("true")){
                Log.i("tag","start");
                Intent intent = new Intent(main.this,CallReceiver.class);
                startService(intent);
            }else{

            }
        return true;
        }
    });
}}

我的广播接收器:

public class CallReceiver extends BroadcastReceiver implements SensorEventListener {
     private SensorManager mSensorManager;
     private Sensor mSensor;
     public static boolean isAirAnswerOn = G.preferences.getBoolean("AIR",false);
     String phoneState;
      @Override
      public void onReceive(Context context, Intent intent) {
        Log.i("TAG", "Call Recieve");
        mSensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
        mSensor = mSensorManager.getDefaultSensor(android.hardware.Sensor.TYPE_PROXIMITY);
        mSensorManager.registerListener(this, mSensor, SensorManager.SENSOR_DELAY_NORMAL);
        phoneState = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
}
    @Override
    public void onSensorChanged (SensorEvent event) {
        if (event.values[0] == 0.0F) {

            if ((!isAirAnswerOn) | (!phoneState.equals(TelephonyManager.EXTRA_STATE_RINGING))) {
                Log.i("ACR", "Action Phone UP");
                Intent localIntent = new Intent("android.intent.action.MEDIA_BUTTON");
                localIntent.putExtra("android.intent.extra.KEY_EVENT", new KeyEvent(1, 79));
                G.context.sendOrderedBroadcast(localIntent, null);
                SharedPreferences.Editor editor = G.preferences.edit();
                editor.putBoolean("AIR", true);
                editor.commit();
            }
        } else {
            Log.i("TAG", "FALSE");

        }
    }
@Override
public void onAccuracyChanged (Sensor sensor,int accuracy){
}

}

谢谢你:)

1 个答案:

答案 0 :(得分:1)

您需要使用OnPreferenceChangeListener中止更改return false中的值。否则,该值将设置为true,并忽略对true的后续更改。