【问题标题】:Android - Getting Context from a Method called within onReceive?Android - 从 onReceive 中调用的方法获取上下文?
【发布时间】:2019-02-25 15:30:08
【问题描述】:

如何从 onReceive 调用的方法中检索 context

这是我要完成的示例:

@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】:

    Context 传递给它:

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

    【讨论】:

    • 注意: 为他人澄清 - 您无法通过method() 中执行上述操作来实现此目的。您还必须包括@从onReceive拨打电话时为987654324@,如callMethodOne(context);然后您还必须将context 包含在代替 或直接 到您在方法中需要它的每件事情之前,例如上面,或者喜欢context.getSystemService(NOTIFICATION_SERVICE);.. 希望这对其他人有帮助。
    猜你喜欢
    • 2023-03-27
    • 2011-05-06
    • 1970-01-01
    • 2017-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多