Reputation: 121
I wonder if there is a way to get the context of current running activity on android. For example, I have an Activity Class and it is running. What I want is to call another Simple Class to run some functions which called from Activity Class. By doing this, I need to set up a context of Activity Class on Simple Class; On the other way, I need to have the context of Current Running Activity, so that my Simple Class can actually run the functions called from Current Running Activity.
Below is the soft code from my project.
public class Main1 extends Activity {
private static GetAPNsInfo getAPNsInfo = new GetAPNsInfo();
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
getAPNsInfo.doSomething();
}
}
public class GetAPNsInfo {
public void doSomething() {
Button button = currentRunningActivityContext.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
});
}
}
Finally, my purpose of this thread is that I need a good way to get the current running activity info.
This is a solution that I found my self. But it doesn't totally solve this case. We can add a receiver in Manifest.xml. This will run a background application.
<receiver android:name=".RunningActivityCapture">
<intent-filter android:priority="-1">
<action android:name="android.intent.action.NEW_OUTGOING_CALL"></action>
</intent-filter>
</receiver>
The background application interface look like this:
public class RunningActivityCapture extends BroadcastReceiver {
@Override
public void onReceive(Context aContext, Intent intent) {
String action = intent.getAction();
if (action.equals(Intent.ACTION_ALL_APPS)) {
Activity activty = intent.getCurrentActivity();
Session session = new Session();
session.setRunningActivity(activty);
}
return;
}
}
I only get the activity from session class which setting from my background application. This is my first idea to solve this problem. But the code is not correct. So I need your help.
Upvotes: 0
Views: 3388
Reputation: 9908
If you are asking how to use this MainActivity
in your helper class, you can pass the Activity itself into your class, as an activity is a Context. So your constructor will be:
public GetAPNsInfo(Context context) {
...
}
where you store the context in a field and use it later. You will initialize with
private static GetAPNsInfo getAPNsInfo = new GetAPNsInfo(this);
if you are asking how to get the context for ANY activity in your application, I don't think that is recommended.
Upvotes: 3