Activity如何访问NotificationListenerService的方法?

时间:2015-03-20 15:16:12

标签: android android-activity android-service

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

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

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

我的问题是:当我的应用启动时,MyActivity如何调用MyNotificationListenerService' getCurrentInterruptionFilter()

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

1 个答案:

答案 0 :(得分:0)

您想要从您的Activity绑定到该服务。 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;
        }
    }
}

您的服务:

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;
        }
    }
}