Android - 从onReceive中调用的方法获取上下文?

问题描述 投票:1回答:1

你如何从context调用的方法中检索onReceive? 以下是我要完成的示例:

@Override
public void onReceive(Context context, Intent intent) {
    ...
    ...
    if(...) {
        callMethodOne();
        callMethodTwo();
    } else if (...) {
        callMethodOne();
    }
    ...
}

private void callMethodOne() {
    // Cant use getApplicationContext
    SharedPreferences getPrefs =
      PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
}

private void callMethodTwo() {
    // Cant use getSystemService
    NotificationManager notificationManager =
      (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

正如您所看到的,由于方法被多次/方式调用,将所有代码移动到onReceive内部将最终变得非常重复并且效率极低。 任何帮助是极大的赞赏! 谢谢。

android broadcastreceiver android-context android-broadcastreceiver
1个回答
2
投票

把它传递给Context

private void callMethodOne(Context context) {
    // Can't use getApplicationContext
    SharedPreferences getPrefs =
        PreferenceManager.getDefaultSharedPreferences(context);
}
© www.soinside.com 2019 - 2024. All rights reserved.