无法通过LocalBroadcastManager从服务获取意图

时间:2018-12-11 19:47:17

标签: java android android-studio android-intent

所以我有2个活动和1个服务。

  • 主要活动(用于激活服务)
  • 服务(用于检测摇动手势)
  • 目标活动(用于显示多少震动)

我做了很多类似问题的教程和建议,但仍然无法从targetactivity中获得意图

这是我的代码。 Service.java

 @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent, flags, startId);
        mSensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
        mAccelerometer = mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER);
        mShakeDetector = new ShakeDetector();

        mSensorManager.registerListener(mShakeDetector, mAccelerometer, SensorManager.SENSOR_DELAY_UI);
        ShakeListener shakeListener = new ShakeListener(this);
        mShakeDetector.setOnShakeListener(shakeListener);

        return START_STICKY;
    }

ShakeListener.java

@Override
public void onShake(int count) {
        sendCountBroadcast(count);
        if(count == threshold ){
            Intent intent = new Intent(ctx,TargetActivity.class); //showing target activity when shake == threshold
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            ctx.startActivity(intent);


        }

    }

    private void sendCountBroadcast(int count) {
        if (count != 0) {
            Intent intent = new Intent(COUNTER_SHAKE);
            intent.putExtra(EXTRA_COUNT, count);
            //ctx.sendBroadcast(intent);
            LocalBroadcastManager.getInstance(ctx).sendBroadcast(intent);
        }
    }

TargetActivity.java

TextView tvCounter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_target);
        tvCounter = (TextView) findViewById(R.id.tv_counter);
        LocalBroadcastManager.getInstance(this).registerReceiver(receiver, new IntentFilter(ShakeListener.COUNTER_SHAKE));


    }

    private BroadcastReceiver receiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int count = intent.getIntExtra(ShakeListener.EXTRA_COUNT,0);
            tvCounter.setText(count);
        }
    };

服务清单:

<service android:process=":sensordetect"
         android:name=".Service"
         android:enabled="true"></service>

sendCountBroadCast被调用,但OnReceive方法未被调用

有人知道我的代码有什么问题吗?

0 个答案:

没有答案