当前位置: 首页 > 面试题库 >

在某些设备上无法在未调用Looper.prepare()的线程内创建处理程序

顾高扬
2023-03-14
问题内容

我知道已经有很多这样的问题,但是我看不出我做错了什么。该应用程序崩溃,但未显示任何内容。另外,该错误不会在我的设备或仿真器上发生。仅在某些设备上(例如30-40%?)。

无法在未调用Looper.prepare()的线程内创建处理程序

MainActivity.java

public class MainActivity extends Activity implements Runnable {

Gebruiker gebruiker = new Gebruiker();
private DatabaseHelper db;
Context context;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    context = this;
    if(isOnline()){
        downloadData();
    } else {
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setMessage("Deze app vereist een actieve verbinding met het internet!")
               .setCancelable(false)
               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                       android.os.Process.killProcess(android.os.Process.myPid());
                   }
               });
        AlertDialog alert = builder.create();
        alert.show();
    }       
    db = new DatabaseHelper(this);
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

private ProgressDialog pDialog;

public void downloadData() {
    pDialog = ProgressDialog.show(this,
            "Controleren op bestaande gebruiker..", "Even geduld", true,
            false);
    Thread thread = new Thread(this);
    thread.start();
}

public void run() {
    // add downloading code here
    HttpReader httpReader = new HttpReader();
    String url = "*****";
    url += Secure.getString(getApplicationContext().getContentResolver(),
            Secure.ANDROID_ID);
    JsonHelper jsonHelper = new JsonHelper();

    gebruiker = jsonHelper.getGebruiker((httpReader.getTextFromUrl(url)
            .trim()));

    handler.sendEmptyMessage(0);
}

private Handler handler = new Handler() {
    @Override
    public void handleMessage(Message msg) {
        pDialog.dismiss();

        if (gebruiker == null) {
            // ga naar aanmaken gebruiker
            Intent intent = new Intent(MainActivity.this,
                    AanmakenUser.class);
            startActivity(intent);
        } else {
            // ga naar hoofdmenu
            db.droppen();
            db.insertGebruiker(gebruiker);
            Intent intent = new Intent(MainActivity.this, Hoofdmenu.class);
            startActivity(intent);
            // ga naar menu
        }
    }
};

public boolean isOnline() {
    ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}

LogCat

01-10 16:12:16.444: E/AndroidRuntime(6090): FATAL EXCEPTION: Thread-10
01-10 16:12:16.444: E/AndroidRuntime(6090): java.lang.ExceptionInInitializerError
01-10 16:12:16.444: E/AndroidRuntime(6090):     at db.jochen.quizapp.MainActivity.run(MainActivity.java:68)
01-10 16:12:16.444: E/AndroidRuntime(6090):     at java.lang.Thread.run(Thread.java:1019)
01-10 16:12:16.444: E/AndroidRuntime(6090): Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
01-10 16:12:16.444: E/AndroidRuntime(6090):     at android.os.Handler.<init>(Handler.java:121)
01-10 16:12:16.444: E/AndroidRuntime(6090):     at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
01-10 16:12:16.444: E/AndroidRuntime(6090):     at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:421)
01-10 16:12:16.444: E/AndroidRuntime(6090):     at android.os.AsyncTask.<clinit>(AsyncTask.java:152)
01-10 16:12:16.444: E/AndroidRuntime(6090):     ... 2 more
01-10 16:12:16.454: D/dalvikvm(6090): GC_CONCURRENT freed 79K, 48% free 2843K/5379K, external 3695K/4614K, paused 2ms+5ms
01-10 16:12:16.454: W/ActivityManager(278):   Force finishing activity db.jochen.quizapp/.MainActivity
01-10 16:12:16.544: E/SkLayout_wtle(6090): ellipsis failed line number does not match 1 0
01-10 16:12:16.624: D/fast-dormancy(165): [FDM]: finish the match exclude list procedure, but can not match any one
01-10 16:12:16.624: D/fast-dormancy(165): [FDM]: GoDormant? 0
01-10 16:12:16.624: D/fast-dormancy(165): [FDM]: Threads Status Mutex Locked in fdm_main_loop
01-10 16:12:16.624: D/fast-dormancy(165): [FDM]: Threads Status Mutex Unlocked in fdm_main_loop
01-10 16:12:16.624: D/fast-dormancy(165): [FDM]: finish the match exclude list procedure, but can not match any one
01-10 16:12:16.624: D/fast-dormancy(165): [FDM]: GoDormant? 0
01-10 16:12:16.624: D/fast-dormancy(165): [FDM]: Threads Status Mutex Locked in fdm_main_loop
01-10 16:12:16.624: D/fast-dormancy(165): [FDM]: Threads Status Mutex Unlocked in fdm_main_loop
01-10 16:12:16.624: I/ActivityManager(278): No longer want com.sonyericsson.tvlauncher (pid 4961): hidden #16
01-10 16:12:16.664: E/WindowManager(6090): Activity db.jochen.quizapp.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@2afd4aa0 that was originally added here
01-10 16:12:16.664: E/WindowManager(6090): android.view.WindowLeaked: Activity db.jochen.quizapp.MainActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView@2afd4aa0 that was originally added here
01-10 16:12:16.664: E/WindowManager(6090):      at android.view.ViewRoot.<init>(ViewRoot.java:269)
01-10 16:12:16.664: E/WindowManager(6090):      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:148)
01-10 16:12:16.664: E/WindowManager(6090):      at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:91)
01-10 16:12:16.664: E/WindowManager(6090):      at android.view.Window$LocalWindowManager.addView(Window.java:424)
01-10 16:12:16.664: E/WindowManager(6090):      at android.app.Dialog.show(Dialog.java:241)
01-10 16:12:16.664: E/WindowManager(6090):      at android.app.ProgressDialog.show(ProgressDialog.java:109)
01-10 16:12:16.664: E/WindowManager(6090):      at android.app.ProgressDialog.show(ProgressDialog.java:97)
01-10 16:12:16.664: E/WindowManager(6090):      at db.jochen.quizapp.MainActivity.downloadData(MainActivity.java:59)
01-10 16:12:16.664: E/WindowManager(6090):      at db.jochen.quizapp.MainActivity.onCreate(MainActivity.java:33)
01-10 16:12:16.664: E/WindowManager(6090):      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-10 16:12:16.664: E/WindowManager(6090):      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1623)
01-10 16:12:16.664: E/WindowManager(6090):      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1675)
01-10 16:12:16.664: E/WindowManager(6090):      at android.app.ActivityThread.access$1500(ActivityThread.java:121)
01-10 16:12:16.664: E/WindowManager(6090):      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:943)
01-10 16:12:16.664: E/WindowManager(6090):      at android.os.Handler.dispatchMessage(Handler.java:99)
01-10 16:12:16.664: E/WindowManager(6090):      at android.os.Looper.loop(Looper.java:138)
01-10 16:12:16.664: E/WindowManager(6090):      at android.app.ActivityThread.main(ActivityThread.java:3701)
01-10 16:12:16.664: E/WindowManager(6090):      at java.lang.reflect.Method.invokeNative(Native Method)
01-10 16:12:16.664: E/WindowManager(6090):      at java.lang.reflect.Method.invoke(Method.java:507)
01-10 16:12:16.664: E/WindowManager(6090):      at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:878)
01-10 16:12:16.664: E/WindowManager(6090):      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:636)
01-10 16:12:16.664: E/WindowManager(6090):      at dalvik.system.NativeStart.main(Native Method)

问题答案:

如果您的线程不在监听循环程序,您如何管理发送给处理程序的请求?

Doc说:public Handler()

API级别1中添加的默认构造函数将此处理程序与当前线程的Looper关联。如果此线程没有循环程序,则此处理程序将无法接收消息,因此将引发异常。

如果您希望辅助线程能够管理Handler,则必须调用Looper.prepare()

例:

public class MyThread extends Thread {
    private Handler mHandler;

    public void run() {
        Looper.prepare();
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                switch (msg.what) {
                    // manage the message
                }
            }
        };
        Looper.loop();
    }

    public void stopLooper() {
        if (Looper.myLooper()!=null)
            Looper.myLooper().quitSafely();
    }
}


 类似资料:
  • 问题内容: 我收到此错误“无法在未调用Looper.prepare()的线程内创建处理程序” 你能告诉我如何解决吗? StartPayment方法: 问题答案: 您应该知道,当您尝试修改UI时, 唯一 可以执行此操作的线程是。 因此,如果要在另一个线程中修改UI,请尝试使用以下方法: 您的代码应如下所示:

  • 问题内容: 我正在使用AsyncTask调用yahooweather API。以下是代码: } 调试代码后,我发现yahooAPI调用成功,并且可以在函数中看到XML响应。但是,一旦执行完此功能,就会引发异常: 请帮帮我。 问题答案: 从方法中删除所有Toast的from,因为此方法是从of 调用的,并且您无法从后台线程访问Toast等Ui元素(也是Ui元素)。 注意: 如果您想知道后台发生了什么

  • 我在android中点击添加学生时出错了

  • 问题内容: 我不明白为什么会收到此错误。我正在使用AsyncTask在后台运行一些进程。 我有: 当我根据情况进入时: 每当我尝试我都会收到错误消息。 有想法吗? 问题答案: 该方法必须从被调用用户界面(UI)螺纹,而在不同的螺纹,其是主要的原因,运行被设计。 你必须调用无论是在或。 例如:

  • 我正在使用Google Maps V2 API开发一个简单的应用程序,只是为了获得基本知识,我面临着这个错误: 奇怪的是,我可以在我的模拟器(API16)上运行这个应用程序,它运行得很好,但当我试图在物理设备(API15)上运行它时,它得到了这个错误。AsyncTask在单独的类中运行,因此可能会导致此问题。如果有任何建议,我将不胜感激。提前谢了。

  • 问题内容: 我正在尝试使用其他EditText上传照片。我从一个在线示例中获取了示例代码,并对其进行了少量编辑,但我收到此错误: 我的Android代码: 请告诉我这里是什么问题,我该如何解决呢?预先感谢我知道,常见的答案是我需要从UI线程调用Toast.makeText(…):很抱歉,因为我很新任何人都介意对此进行更详细的解释 问题答案: 可能由于此行而出现错误 里面。必须显示在UIThread