programing

안드로이드 1.6: "android.view.WindowManager $BadToken 예외:창을 추가할 수 없습니다. 토큰 null은 응용 프로그램을 위한 것이 아닙니다."

lastcode 2023. 9. 9. 09:32
반응형

안드로이드 1.6: "android.view.WindowManager $BadToken 예외:창을 추가할 수 없습니다. 토큰 null은 응용 프로그램을 위한 것이 아닙니다."

대화창을 열려고 하는데 열려고 할 때마다 다음과 같은 예외가 발생합니다.

Uncaught handler: thread main exiting due to uncaught exception
android.view.WindowManager$BadTokenException: 
     Unable to add window -- token null is not for an application
  at android.view.ViewRoot.setView(ViewRoot.java:460)
  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:177)
  at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
  at android.app.Dialog.show(Dialog.java:238)
  at android.app.Activity.showDialog(Activity.java:2413)

전화해서 만들고 있습니다.showDialog디스플레이 아이디로. 더.onCreateDialog핸들러 로그는 정상적으로 기록되고 문제없이 처리할 수 있습니다만, 제가 뭔가를 놓치고 있는 것 같아서 첨부했습니다.

@Override
public Dialog onCreateDialog(int id)
{
    Dialog dialog;
    Context appContext = this.getApplicationContext();
    switch(id)
    {
        case RENAME_DIALOG_ID:
            Log.i("Edit", "Creating rename dialog...");
            dialog = new Dialog(appContext);
            dialog.setContentView(R.layout.rename);
            dialog.setTitle("Rename " + noteName);
            break;
        default:
            dialog = null;
            break;
    }
    return dialog;      
}

여기에 뭔가 빠진 게 있습니까?를들때이가는에해몇지이다지이다몇egmgamnest서gds화해를에는들가이때eonCreate하지만, 이고, , , , , , , , , , , , , , , , , , , .appContext변수가 디버거에 올바르게 입력된 것 같습니다.

: :Context appContext = this.getApplicationContext();현재 활동에 포인터를 사용해야 합니다(probablythis).

저도 오늘 이거 물렸는데 짜증나는 부분은.getApplicationContext() fromm m서온다는입니다 :(

활동이 아닌 컨텍스트를 통해 응용프로그램 창/대화상자를 표시할 수 없습니다.유효한 활동 참조를 전달해 봅니다.

getApplicationContext 항목에 대한 Ditto.

안드로이드 사이트에 있는 문서에 사용하라고 되어있는데 작동이 안되네요... grrrrrr :-P

그냥 하기:

dialog = new Dialog(this); 

"this"는 일반적으로 대화를 시작하는 작업입니다.

Android 문서에서는 getApplicationContext()를 사용할 것을 제안합니다.

그러나 AlertDialog를 인스턴스화하는 동안 현재 활동을 사용하는 대신에는 작동하지 않습니다.작성자 또는 알림 대화 상자 또는 대화 상자...

예:

AlertDialog.Builder builder = new  AlertDialog.Builder(this);

아니면

AlertDialog.Builder builder = new  AlertDialog.Builder((Your Activity).this);

getApplicationContext() 사용하기, ActivityName.this

저도 비슷한 문제가 있었는데 다른 수업이 있었습니다.

public class Something {
  MyActivity myActivity;

  public Something(MyActivity myActivity) {
    this.myActivity=myActivity;
  }

  public void someMethod() {
   .
   .
   AlertDialog.Builder builder = new AlertDialog.Builder(myActivity);
   .
   AlertDialog alert = builder.create();
   alert.show();
  }
}

대부분은 정상적으로 작동했지만 가끔 같은 오류와 함께 충돌하기도 했습니다.그 다음에 나는 그것을 깨닫습니다.MyActivity... 전

public class MyActivity extends Activity {
  public static Something something;

  public void someMethod() {
    if (something==null) {
      something=new Something(this);
    }
  }
}

왜냐하면 나는 그 물건을 들고 있었기 때문에static두, 의 의 은 의 를 하고 하고 를 하고 를 의 하고 .Activity하지 않았던 것입니다.

바보같은 바보같은 실수야, 특히 내가 물건을 들고 있을 필요가 없었기 때문에.static애초에...

그냥 바꿔주세요.

AlertDialog.Builder alert_Categoryitem = 
    new AlertDialog.Builder(YourActivity.this);

대신에

AlertDialog.Builder alert_Categoryitem = 
    new AlertDialog.Builder(getApplicationContext());

창 유형을 시스템 대화 상자로 설정하는 방법도 있습니다.

dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

이를 위해서는 다음과 같은 권한이 필요합니다.

<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />

문서에 따르면 다음과 같습니다.

이 권한을 사용하는 응용 프로그램은 거의 없습니다. 이 창은 사용자와의 시스템 수준 상호 작용을 위한 것입니다.

작업에 연결되지 않은 대화 상자가 필요한 경우에만 사용해야 하는 솔루션입니다.

사용하지않습니다.getApplicationContext()대화를 선언할 때

항상사용this아니면 당신의activity.this

중첩 대화 상자의 경우 이 문제는 매우 일반적이며, 다음과 같은 경우에 작동합니다.

AlertDialog.Builder mDialogBuilder = new AlertDialog.Builder(MyActivity.this);

대신에 사용됩니다.

mDialogBuilder = new AlertDialog.Builder(getApplicationContext);

이 대안.

이게 내겐 통했어요

new AlertDialog.Builder(MainActivity.this)
        .setMessage(Html.fromHtml("<b><i><u>Spread Knowledge Unto The Last</u></i></b>"))
        .setCancelable(false)
        .setPositiveButton("Dismiss",
                new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                    }
                }).show();

사용하다

ActivityName.this

이것도 할 수 있습니다.

public class Example extends Activity {
    final Context context = this;
    final Dialog dialog = new Dialog(context);
}

이거 나한테 통했어요!!

대화의 컨텍스트로 Activity가 필요하며, 정적 컨텍스트의 경우 "Your Activity.this"를 사용하거나 안전 모드에서 동적 컨텍스트를 사용하는 방법을 여기에서 확인합니다.

재설정 시도dialog에 대한 창 유형

WindowManager.LayoutParams.TYPE_SYSTEM_ALERT:
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);

사용 권한을 사용하는 것을 잊지 마십시오.android.permission.SYSTEM_ALERT_WINDOW

public class Splash extends Activity {

    Location location;
    LocationManager locationManager;
    LocationListener locationlistener;
    ImageView image_view;
    ublic static ProgressDialog progressdialog;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash);
        progressdialog = new ProgressDialog(Splash.this);
           image_view.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                        locationManager.requestLocationUpdates("gps", 100000, 1, locationlistener);
                        Toast.makeText(getApplicationContext(), "Getting Location plz wait...", Toast.LENGTH_SHORT).show();

                            progressdialog.setMessage("getting Location");
                            progressdialog.show();
                            Intent intent = new Intent(Splash.this,Show_LatLng.class);
//                          }
        });
    }

여기 텍스트:-
이것을 얻는 데 사용합니다.activity에 대한 정황progressdialog

 progressdialog = new ProgressDialog(Splash.this);

아니면progressdialog = new ProgressDialog(this);

응용프로그램 컨텍스트를 가져오는 데 사용합니다.BroadcastListener을 위한 것이 아닌progressdialog.

progressdialog = new ProgressDialog(getApplicationContext());
progressdialog = new ProgressDialog(getBaseContext());

비동기 작업에서 '진행 대화 상자'를 표시하는 가장 좋고 안전한 방법은 메모리 누출 문제를 방지하는 것입니다. Looper.main()과 함께 'Handler'를 사용하는 것입니다.

    private ProgressDialog tProgressDialog;

'onCreate'에서

    tProgressDialog = new ProgressDialog(this);
    tProgressDialog.setMessage(getString(R.string.loading));
    tProgressDialog.setIndeterminate(true);

이제 설정 부분을 끝냈습니다.이제 AsyncTask에서 'showProgress()' 및 'hideProgress()'를 호출합니다.

    private void showProgress(){
        new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                tProgressDialog.show();
            }
        }.sendEmptyMessage(1);
    }

    private void hideProgress(){
        new Handler(Looper.getMainLooper()){
            @Override
            public void handleMessage(Message msg) {
                tProgressDialog.dismiss();
            }
        }.sendEmptyMessage(1);
    }

언급URL : https://stackoverflow.com/questions/2634991/android-1-6-android-view-windowmanagerbadtokenexception-unable-to-add-window

반응형