Android 如何从正在使用的特定 class 获取上下文

Android how get Context from specific class being in Service

我创建了服务 class。 我可以 运行 它在我想要的任何地方,但我总是需要来自 MainMenuActivity.class 的上下文。 我尝试使用 getApplicationContext 和 getBaseContext 但它们显示另一个 class.

感谢回答

public class MainActivity extends ActionBarActivity {

    protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            startService(new Intent(this, MyService.class));
    }

}


public class MyService extends Service  {
    private Handler handler = new Handler();
    private MyLocationListener mylistener;
        public void onCreate() {
            handler.postDelayed(new runnable(), 10000);
    }

    private class runnable implements Runnable {
            @Override
            public void run() {
            mylistener = new MyLocationListener();
        }
    }
}

public class MyLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location loc) {
        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
    }
}

[编辑] 当我使用 getApplicationContext() 或 getBaseContext 或 MainActivity.this 来获取 DefaultSharedPreferences 时,它总是一样吗?

解法:1

在那种情况下你必须使用,defaultSharedPreferences。您可以通过以下方式访问默认共享首选项实例:

PreferenceManager.getDefaultSharedPreferences(Context context):

示例:

SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);

您的所有 Activity 和 class 服务都共享此偏好设置。

解:2

您可以在您的应用程序中创建 sharedPreference 实例 class 如:

public class MyApplication 扩展应用程序 { public 静态 SharedPreferences 首选项;

@Override
public void onCreate() {
    super.onCreate();

    preferences = getSharedPreferences("Preferences", MODE_PRIVATE);
}

}

然后您可以将您的偏好设置为:

MyApplication.preferences.getString("key", "default");

将上下文参数添加到您的服务class 方法

public void myMethodInsideServiceClass(Context context){
   //bluh bluh
}

这样您就可以像这样从 Activity Class 调用

myMethodInsideServiceClass(this);

你也可以试试

public class MyActivity extends Activity {
     public static myActivity;
     protected void onCreate(Bundle savedInstanceState) {
         super.onCreate(savedInstanceState);
         myActivity=this;
     }
}

以便您可以在整个应用程序中使用 myActivity (我没有使用编辑器输入代码,很抱歉语法错误)