Activity如何访问NotificationListenerService的方法?

Gru*_*kes 6 android android-service android-activity

我有一个活动类,需要获取设备的当前中断过滤器设置.

因此,我有一个MyNotificationListenerService派生自NotificationListenerService 的类,并实现onInterruptionFilterChanged().

但是onInterruptionFilterChanged()只有在中断过滤器发生变化时才会调用.当我的应用程序启动时,我需要找出中断过滤器的当前值是什么.NotificationListenerService有一个方法getCurrentInterruptionFilter().

我的问题是:如何能MyActivity调用MyNotificationListenerServicegetCurrentInterruptionFilter()时候,我的应用程序启动?

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

.

And*_*rry 0

您想要从您的活动绑定到服务。Android 文档对此有详细说明:http://developer.android.com/guide/components/bound-services.html

下面是它如何工作的示例。

您的活动:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

您的服务:

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;
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

  • 感谢您的回答。但是我发现添加此代码似乎会阻止NotificationListenerService 实际工作。如果没有上述代码,当应用程序运行时,NLS 不会执行任何操作,直到用户授予对应用程序的通知访问权限,一旦他们这样做,就会调用 NLS 的 onListenerConnected() ,并且对中断过滤器的更改会导致 onInterruptionFilterChanged() 获取但是,如果添加上述代码,那么当用户授予通知访问权限时,onInterruptionFilterChanged() 就不会被调用。 (2认同)