当方法不在活动中时,如何将其传递给活动



我有一个自定义类SettingsPreferences,用于更改我的录音机应用程序的一些设置。目前,我正在努力处理"请勿打扰"模式的打开和关闭。

我创建了一个由另一个方法checkIfNotifGranted调用的方法requestAccessNotificationPermission,用于检查是否授予通知策略访问权限。

@RequiresApi(api = Build.VERSION_CODES.M)
void checkIfNotifGranted() {
if (!notificationManager.isNotificationPolicyAccessGranted()) {
requestAccessNotificationPermission();
}
}
@RequiresApi(api = Build.VERSION_CODES.M)
private void requestAccessNotificationPermission(Activity activity) {
Intent intent = new Intent(Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
activity.startActivity(intent);
}

我的计划是,如果这能奏效,我会使用以下两种方法来处理"请勿打扰"模式的关闭和打开。

@RequiresApi(api = Build.VERSION_CODES.M)
void doNotDisturbOff() {
notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE);
}
@RequiresApi(api = Build.VERSION_CODES.M)
void doNotDisturbOn() {
notificationManager.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_ALL);
}

然而,我不知道如何处理这个Activity问题。我试图将this作为调用requestAccessNotificationPermission的参数,但它不起作用。

我不能在SettingsFragment中使用这些方法,因为我不能从静态上下文调用非静态方法。因此,我有下面的代码来调用我的自定义类中的方法。

final Preference dnd = findPreference("doNotDisturb");
assert  dnd != null;
dnd.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
@Override
public boolean onPreferenceChange(Preference preference, Object newValue) {
String boolCheck = newValue.toString();
if (boolCheck.equals("true")) {
new SettingsPreferences().checkIfNotifGranted();
new SettingsPreferences().doNotDisturbOn();
}
else if (boolCheck.equals("false")) {
new SettingsPreferences().checkIfNotifGranted();
new SettingsPreferences().doNotDisturbOff();
}
return false;
}
});

任何帮助或解释都将不胜感激,因为我真的被这个难住了。

谢谢。

不能在匿名内部类中使用this。您必须使用MainActivity.this

您可以传递createApplication类并将MyApplication.getInstance()传递给您的方法。

如果你正在使用kotlin,那么简单地设置applicationContext

希望它能有所帮助。

最新更新