所以我有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
方法未被调用
有人知道我的代码有什么问题吗?