Issue starting activity from non-activity class

夙愿已清 提交于 2020-01-06 15:39:12

问题


I am a noob to android and I have a Map Activity that also uses OverlayItems. Within the onButtonTap method of my overlay class, I want to execute startActivity so i can then use intent.ACTION_CALL.

Intent callIntent = new Intent(Intent.ACTION_CALL);   
callIntent.setData(Uri.parse("tel:"+MapActivity.phonenumber0));
startActivity(callIntent);

in the code above i am asked to create a method for startActivity(Intent), which I don't understand. and when i try...

Intent callIntent = new Intent(Intent.ACTION_CALL);   
callIntent.setData(Uri.parse("tel:"+MapActivity.phonenumber0));
MapActivity.startActivity(callIntent);

It says i cannot make a static reference to a non static reference to a non-static method. And when I try to use the context of the object, which is the button being tapped it won't allow me to do so.

Intent callIntent = new Intent(Intent.ACTION_CALL);   
callIntent.setData(Uri.parse("tel:"+MapActivity.phonenumber0));
ContextObj.startActivity(callIntent);

And of course moving this block of code to the main Activity requires a static method which presents its own set of issues.

How can set the appropriate context for startActivity? Any help is greatly appreciated.


回答1:


you can create method in your MapActivity class like this to get context...

Edit : Take some static variable like this...

public static Context mContext;

In Activity's onCreate() method assign base context to it...

mContext = getBaseContext();

& return mContext...

public static Context getContext() {
    return mContext;
}

& call it in to your non activity class to start activity...

Intent callIntent = new Intent(Intent.ACTION_CALL);   
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
callIntent.setData(Uri.parse("tel:"+MapActivity.phonenumber0));
MapActivity.getContext().startActivity(callIntent);



回答2:


Try this before start the activity set this flag :

intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

Hope it will work.




回答3:


You can pass the context of the activity (Map Activity) to your class and then use it..



来源:https://stackoverflow.com/questions/12319631/issue-starting-activity-from-non-activity-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!