开发者

"Static" startActivity(Intent) method?

I have a Button. Its View.OnClickHandler-implementing class is instantiated about 3 constructors deep from the nearest reference to an android.app.Activity object. When clicked, I want it to open the Location settings panel so the user can enable GPS and/or network-based location by launching the Settin开发者_开发技巧gs.ACTION_LOCATION_SOURCE_SETTINGS intent.

Short of promiscuously passing that parent Activity object from constructor to constructor to constructor so my onClick() method can see it, is there any way to just reach up into the metaphorical static ether and scream, "Hey, Android... launch Settings.ACTION_LOCATION_SOURCE_SETTINGS" without having to have an actual live Activity object handy to use for its startActivity method?


This worked for me:

public class StartGame extends Activity {

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.start_game_activity);
    }

    public static void nextPass(Activity context) {
        Intent intent = new Intent(context,your.class);
        context.startActivity(intent);
    }

}


I believe you are saying that you need an Activity object for the first parameter of new Intent or some other method to generate intents. Please do correct me if I'm wrong. If that is the case you actually just need a Context object (Activity is a sub-class of Context), that may not help particularly in this case.

I'd need to see the code to be sure there wasn't a way to get at a context object neatly from the spot you need it. There may be some way to do it (e.g. access to outer variable from anonymous object scope; a fairly common pattern with handlers on Android).

I would say that in some of my apps I do pass context objects around quite a bit. Personally I think this practice (known as dependency injection) is not so bad as some engineers think. If you are using managers or state-laden objects deep in the app, concealing this fact with global accessors or automatic dependency injection, is just papering over that fact.

Here are two other similar questions on this topic with respect to Android context objects:

Static way to get 'Context' on Android?

Using Application context everywhere?


Use YourActivity.this as the context instead of this if you're in the same class.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜