我想将当前 Activity 的引用传递给不扩展 Activity 的类的方法。我需要使用对 Activity Activity 的引用,以便我可以使用 getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
我在类中使用这些 setter 方法将当前上下文和 Activity 传递给类对象:
public class VersionCheck {
public Context context;
public Activity activity;
//---------------------------------------------------------------------------------------------------------
//set the current context
//---------------------------------------------------------------------------------------------------------
public void setContext(Context context) {
this.context = context;
}
//---------------------------------------------------------------------------------------------------------
//set the current activity
//---------------------------------------------------------------------------------------------------------
public void setActivity(Activity activity) {
this.activity = activity;
}
对 Activity 的引用在类中的 AsyncTask 中使用(摘录如下):
//---------------------------------------------------------------------------------------------------------
//asynchronous task to check if there is a newer version of the app available
//---------------------------------------------------------------------------------------------------------
private class UpdateCheckTask extends AsyncTask<String, Void, String> {
HttpClient httpclient;
HttpPost httppost;
HttpResponse response;
InputStream inputStream;
byte[] data;
StringBuffer buffer;
protected void onPreExecute ()
{
VersionCheck vc = new VersionCheck();
//do not lock screen or drop connection to server on login
activity.getWindow().addFlags(LayoutParams.FLAG_KEEP_SCREEN_ON);
//initiate progress dialogue to block user input during initial data retrieval
ProcessingDialog = ProgressDialog.show(context, "Please Wait", "Checking for Updates", true,false);
}
@Override
protected String doInBackground(String... currentVersion)
{
如何获取对 Activity 的引用,以便将其传递给 setActivity(Activity) 方法?我使用 myActivity.this 作为上下文的引用。 Activity 也一样吗?
最佳答案
是的,Activity 也是一样的.................
http://developer.android.com/reference/android/app/Activity.html
看这里Context是Activity的父类(super class)......
java.lang.Object
↳ android.content.Context
↳ android.content.ContextWrapper
↳ android.view.ContextThemeWrapper
↳ android.app.Activity
关于android.content.Context 与 android.app.Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10750064/