如何从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内部将最终变得非常重复且效率极低。

任何帮助是极大的赞赏!
谢谢。

最佳答案

将其传递给Context

private void callMethodOne(Context context) {
    // Can't use getApplicationContext
    SharedPreferences getPrefs =
        PreferenceManager.getDefaultSharedPreferences(context);
}

关于android - Android-从onReceive中调用的方法获取上下文?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/54869581/

10-11 22:27
查看更多