MyNotificationListenerService

MyNotificationListenerService

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

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

但是,只有在中断过滤器更改时才调用onInterruptionFilterChanged()。当我的应用启动时,我需要找出中断过滤器的当前值是多少。 NotificationListenerService为此提供了一个方法getCurrentInterruptionFilter()

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

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

最佳答案

您要从“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;
        }
    }
}

09-26 12:26