[英]In Android, Is there any way to listen Network Changes in the InputMethodService class?
我在 Android 中創建了一個自定義鍵盤,每當彈出鍵盤時,我想在網絡連接中斷時顯示彈出窗口,我已經在基於活動的類中嘗試過,但這是一個不同的場景,因為它是一個服務 class。
但是當它開始運行時,鍵盤崩潰並收到此錯誤消息
錯誤
Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:1159)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:399)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:133)
at android.app.Dialog.show(Dialog.java:345)
at com.prasath.openaikeyboard.util.NetworkChangeListener.onReceive(NetworkChangeListener.java:25)
at android.app.LoadedApk$ReceiverDispatcher$Args.lambda$getRunnable$0$LoadedApk$ReceiverDispatcher$Args(LoadedApk.java:1679)
提前致謝
輸入法服務 class
public class MyInputMethodService extends InputMethodService implements KeyboardView.OnKeyboardActionListener {
private static final String TAG = "MyInputMethodService";
private NetworkChangeListener networkChangeListener=new NetworkChangeListener();
@Override
public View onCreateInputView() {
KeyboardView keyboardView=(KeyboardView) getLayoutInflater().inflate(R.layout.keyboard_view,null);
Keyboard keyboard=new Keyboard(this,R.xml.numberpad);
keyboardView.setKeyboard(keyboard);
keyboardView.setOnKeyboardActionListener(this);
networkChangeListener=new NetworkChangeListener();
return keyboardView;
}
NetworkChangeListener class
public class NetworkChangeListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(!Common.isConnectedToInternet(context)){
AlertDialog.Builder builder=new AlertDialog.Builder(context);
View view= LayoutInflater.from(context).inflate(R.layout.check_internet_dialog,null);
builder.setView(view);
Button button=view.findViewById(R.id.btnrefreshid);
AlertDialog alertDialog=builder.create();
alertDialog.show();
alertDialog.setCancelable(false);
alertDialog.getWindow().setGravity(Gravity.CENTER);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
alertDialog.dismiss();
onReceive(context,intent);
}
});
}
}
}
Dialog
及其子類型,如AlertDialog
,只能在Activity
中使用,而不能在Context
的其他 forms 中使用。
任何一個:
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.