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

标签 android android-activity android-service

我有一个 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/

相关文章:

android - Google Play应用内结算v3,签名为空白

java - 如何在 Activity 上设置进度条

Android 应用程序在后台

android - 在后台运行的服务中需要帮助

android - 停止的前台服务自行重启

android - 使用 Root 权限运行服务或使用 root 添加权限

java - 按仅更新一个字段的日期对 ParseQuery 进行排序

android - Textview maxlines 取决于它的高度

android - 写入数据库时​​,注册后数据库仍然是空的。如何正确地将数据存储到我的数据库中?

android - 启用 ALWAYS_FINISH_ACTIVITIES 的常见场景是什么?