سؤال

I need to start an Activity in case of device shake in my Android application.

This feature should work in my whole app and in all activities.

Now sure how to provide a good architecture for it, because the detecting shake and starting an Activity needs context instance.

I don't want to pass my current Activity instance to the my ShakeListener each time I change the activity.

What will you suggest?

Thanks.

هل كانت مفيدة؟

المحلول

You would certainly have to keep around something that monitors sensor data, like a background Service. You service must continuously monitor sensor events, pass it through a noise filter, detect a shake and send out a Broadcast.

The Activity on the other hand can implement a matching BroadcastReciever.

If you don't want to add BroadcastRecievers for Activities, then you can just register interested activities in init() code of library:

public void init(Context context){ 
    SensorTester st = new SensorTester(context);

    st.registerActivity(MainActivity.class);
    st.registerActivity(OtherActivity.class);
}

And start them from library service using the Context you received in init() code:

for(Class c : registeredClasses){
     context.startActivity(new Intent(this,c));
}

Where you want to place init() code in target App is your choice.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top