android - Android 在 android Service 中使用 LocalBroadcastManager
问题描述
我正在尝试在 android 服务中使用 LocalBroadcastManager。
public class WebSocketService extends Service {
private static final String TAG = "WebSocketService";
private WebSocketClient mWebSocketClient;
public WebSocketService() {
connectWebSocket();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
private void connectWebSocket() {
URI uri;
try {
uri = new URI("wss://echo.websocket.org");
} catch (URISyntaxException e) {
e.printStackTrace();
return;
}
mWebSocketClient = new WebSocketClient(uri) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
Log.i(TAG, "Websocket Opened");
mWebSocketClient.send("Hello from " + Build.MANUFACTURER + " " + Build.MODEL);
}
@Override
public void onMessage(String message) {
Log.i(TAG, "Websocket Received: " + message);
Intent broadcastIntent = new Intent("custom-event");
broadcastIntent.putExtra("message", message);
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent);
}
@Override
public void onClose(int code, String reason, boolean remote) {
Log.i(TAG, "Websocket closed: " + reason);
}
@Override
public void onError(Exception ex) {
Log.i(TAG, "Websocket error");
}
};
}
public void sendMessage(String message) {
mWebSocketClient.send(message);
}
}
创建 websocket 的主要活动。
public class MainActivity extends Activity {
private WebSocketService webSocketService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webSocketService = new WebSocketService();
}
public void send(View view) {
webSocketService.sendMessage("socket message");
}
}
及其xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="send"
tools:layout_editor_absoluteX="166dp"
tools:layout_editor_absoluteY="288dp" />
</androidx.constraintlayout.widget.ConstraintLayout>
以上没有异常编译
改成LocalBroadcastManager.getInstance(this).sendBroadcast(broadcastIntent);
之后
LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(broadcastIntent);
我得到错误
Error Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
我的问题是是否可以在创建时传递上下文
mWebSocketClient = new WebSocketClient(uri) {
}
这样可以使用 LocalBroadcastManager 吗?
一般的问题是,是否有可能在一个令人讨厌的命名空间中获取 applicationContext。
解决方案
要在任何 java 类的烦人方法/内部类中获取 outerScope this ,您可以调用WebSocketService.this
LocalBroadcastManager.getInstance(WebSocketService.this).sendBroadcast(broadcastIntent);
或为相同声明一个私有辅助方法
private WebSocketService getOuterWebSocketService() {
return this;
}
现在您可以在onMessage中使用此方法,如下所示
@Override
public void onMessage(String message) {
Log.i(TAG, "Websocket Received: " + message);
Intent broadcastIntent = new Intent("custom-event");
broadcastIntent.putExtra("message", message);
LocalBroadcastManager.getInstance(getOuterWebSocketService()).sendBroadcast(broadcastIntent);
}
推荐阅读
- javascript - 如何在角度指令(即 ng-init)r 的字符串插值中使用对象?
- alibaba-cloud-ecs - 阿里云ECS中的云盘一式三份
- ios - LLDB:查看 UIModalPresentationStyle 枚举的实际值
- typescript - 在多个级别上推断 TypeScript 中的泛型类型参数
- jquery - 使用 jQuery 和 Ajax 上传 SQL 文件
- laravel - Laravel 一对多质量解离()
- javascript - 以人工顺序对 JavaScript 数组进行排序
- c++ - 计算所有对之间的曼哈顿距离
- java - 战舰坐标输入(带字母)Java
- python-3.x - Python 多处理 - 类型错误:腌制 AuthenticationString