Android-从onReceive中调用的方法获取上下文?
如何从从从Android-从onReceive中调用的方法获取上下文?,android,broadcastreceiver,android-context,android-broadcastreceiver,Android,Broadcastreceiver,Android Context,Android Broadcastreceiver,如何从从从onReceive调用的方法中检索上下文? 以下是我试图完成的一个例子: @Override public void onReceive(Context context, Intent intent) { ... ... if(...) { callMethodOne(); callMethodTwo(); } else if (...) { callMethodOne(); } ...
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
内部将导致重复性非常高,效率极低。非常感谢您的帮助
谢谢。将
上下文传递给它:
private void callMethodOne(Context context) {
// Can't use getApplicationContext
SharedPreferences getPrefs =
PreferenceManager.getDefaultSharedPreferences(context);
}
注意:为他人澄清-仅在方法()中执行上述操作无法实现这一点。。从onReceive
进行调用时,还必须包括context
,例如callMethodOne(context)
;然后,您还必须在方法中包含上下文
来代替或直接在每个需要它的东西之前,比如上面的,或者像context.getSystemService(通知服务)代码>。。希望这对其他人有帮助。