Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
246 views
in Technique[技术] by (71.8m points)

android - How can I start an Activity from a non-Activity class?

I have a map view activity that shows a few OverlayItems. In the onTap method of an overlay, I want to trigger a new activity that shows this overlay photo as a fullscreen, for example.

When I do this inside my overlay class:

Intent intent = new Intent();
intent.setClass(getApplicationContext, FullscreenView.class);
startActivity(intent);

.. it can't find an application context, as I am not in the scope of an activity.

When I add a method to my main activity, let's say startFullscreen:

public static void startFullscreen() {
    if (sCurrentPhoto != null) {
        Intent intent = new Intent();
        intent.setClass(getApplicationContext(), FullscreenView.class);
        startActivity(intent);          
    }
}

I can not call getApplicationContext() and startActivity(), because I am in a static context. I need the static method however to call it in the Overlay class like MainView.startFullscreen().

Put simply: How can I start an Activity from a non-Activity class?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Once you have obtained the context in your onTap() you can also do:

Intent myIntent = new Intent(mContext, theNewActivity.class);
mContext.startActivity(myIntent);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...