在RxBroadcast.fromBroadcast订阅中检索上下文

时间:2017-02-07 11:11:02

标签: android rx-android android-broadcastreceiver

为Gradle添加了依赖

compile 'com.cantrowitz:rxbroadcast:1.0.0'

在服务中使用RxBroadcast

RxBroadcast.fromBroadcast(this, someFilter)
           .subscribe(new Action1<Intent>() {
                        @Override
                        public void call(Intent intent) {
                           //NOTICE : only intent is received. no Context
                        }
                    });

查看源代码BroadcastProvider.createBroadcastReceiver方法

@NonNull
private BroadcastReceiver createBroadcastReceiver(
        final Subscriber<? super Intent> subscriber) {
    return new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (!subscriber.isUnsubscribed()) {
                //NOTICE : context is discarded here.
                subscriber.onNext(intent);
            }
        }
    };
}

如何在Context订阅中检索fromBroadcast

1 个答案:

答案 0 :(得分:0)

很快 - 你不能,因为只发出了intent。当然,除非您更改源并使用intent和context发出包装器对象。

您可以获取全局应用程序上下文,之后您可以使用该上下文执行getSystemService

您需要做的是在Application

中添加自定义AndroidManifest.xml子类
<application
    android:name="com.your.package.MyApplication"
    ...
    >

并创建继承自android.app.Application

的MyApplication类
public class MyApplication extends Application {
    static MyApplication application;

    @Override
    public void onCreate() {
        application = this;
    }

    public static MyApplication getApplication() {
        return application;
    }
}

现在,您可以在订阅中致电MyApplication.getApplication().getSystemService()

在应用程序生命周期中只有一个Application实例,因此不会因为保持静态引用而发生泄漏。