gpt4 book ai didi

android - Activity 如何访问 NotificationListenerService 的方法?

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:43:35 24 4
gpt4 key购买 nike

我有一个 Activity 类需要获取设备当前的中断过滤器设置。

因此我有一个 MyNotificationListenerService 类,它派生自 NotificationListenerService 并实现了 onInterruptionFilterChanged()。

但是 onInterruptionFilterChanged() 仅在中断过滤器更改时被调用。当我的应用程序启动时,我需要找出中断过滤器的当前值是多少。 NotificationListenerService 有一个方法,它是 getCurrentInterruptionFilter()

我的问题是:MyActivity 如何在我的应用启动时调用 MyNotificationListenerServicegetCurrentInterruptionFilter()

操作系统自动创建并启动 MyNotificationListenerServiceMyActivity 是否可以获取该对象的句柄以便调用 getCurrentInterruptionFilter()明确地?如果不是,那么应该有什么通信机制才能让 MyActivity 能够从 MyNotificationListenerService 获取初始中断设置?

.

最佳答案

您想从您的 Activity 绑定(bind)到服务。 Android 文档在 http://developer.android.com/guide/components/bound-services.html 中对此进行了详细解释。

这是它如何工作的示例。

您的 Activity :

public class MyActivity extends Activity {

private MyNotificationListenerService mService;
private MyServiceConnection mServiceConnection;

...

protected void onStart() {
super.onStart();
Intent serviceIntent = new Intent(this, MyNotificationListenerService.class);
mServiceConnection = new MyServiceConnection();
bindService(serviceIntent, mServiceConnection, BIND_AUTO_CREATE);
}

protected void onStop() {
super.onStop();
unbindService(mServiceConnection);
}

private class MyServiceConnection implements ServiceConnection {

@Override
public void onServiceConnected(ComponentName name, IBinder binder) {
mService = ((MyNotificationListenerService.NotificationBinder)binder).getService();
}

@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
}
}

您的服务:

public class MyNotificationListenerService extends NotificationListenerService {

...

private NotificationBinder mBinder = new NotificationBinder();

@Override
public IBinder onBind(Intent intent) {
return mBinder;
}

public class NotificationBinder extends Binder {
public MyNotificationListenerService getService() {
return MyNotificationListenerService.this;
}
}
}

关于android - Activity 如何访问 NotificationListenerService 的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29169921/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com