Android:由Handler引起的java.lang.RuntimeException

时间:2017-09-15 11:53:24

标签: java android handler runnable android-handler

早上好!

我在google play商店中有一个Android应用程序,其中有一个从服务器加载一些数据的小部件。 在我的Play-Console中,我得到以下异常:

java.lang.RuntimeException: 


  at android.os.AsyncTask$3.done (AsyncTask.java:318)

  at java.util.concurrent.FutureTask.finishCompletion (FutureTask.java:354)

  at java.util.concurrent.FutureTask.setException (FutureTask.java:223)

  at java.util.concurrent.FutureTask.run (FutureTask.java:242)

  at android.os.AsyncTask$SerialExecutor$1.run (AsyncTask.java:243)

  at java.util.concurrent.ThreadPoolExecutor.runWorker (ThreadPoolExecutor.java:1133)

  at java.util.concurrent.ThreadPoolExecutor$Worker.run (ThreadPoolExecutor.java:607)

  at java.lang.Thread.run (Thread.java:762)


Caused by: java.lang.RuntimeException: 

  at android.os.Handler.<init> (Handler.java:200)

  at android.os.Handler.<init> (Handler.java:114)

  at package.Widget.fehler (Widget.java:279)

  at package.Widget_Server.doInBackground (Widget_Server.java:73)

  at package.Widget_Server.doInBackground (Widget_Server.java:19)

  at android.os.AsyncTask$2.call (AsyncTask.java:304)

  at java.util.concurrent.FutureTask.run (FutureTask.java:237)

java类“Widget_Server.java”启动连接并从服务器获取数据。 “Widget.java”是Widget的Main_class。

Widget_Server.java,第73行:

finally {
     try {
        reader.close();
     } catch(Exception ex) {
               EXCEPTION (line 73) -> widget.fehler("Fehler! #2215", context);
     }
}

Widget.java,第279行:(在方法fehler(String, Context)内)

remoteViews.setTextViewText(R.id.label4, fehlerbeschreibung);

   EXCEPTION (line 279) -> Handler handler = new Handler();
   handler.postDelayed(new Runnable() {
      public void run() {
           remoteViews.setViewVisibility(R.id.loading, View. INVISIBLE);
           update(context);
      }
   }, 1000);

Handler初始化如何抛出runtime_exception?

我搜索了很长时间,但我没有找到相关的信息。

感谢所有答案!

1 个答案:

答案 0 :(得分:1)

Handler handler = new Handler()实际上会在下面的构造函数中调用。

public Handler(Callback callback, boolean async) {
    mLooper = Looper.myLooper();
    if (mLooper == null) {
        throw new RuntimeException(
            "Can't create handler inside thread that has not called Looper.prepare()");
    }
    mQueue = mLooper.mQueue;
    mCallback = callback;
    mAsynchronous = async;
}

如您所见,如果未调用Looper.prepare(),则会发送RuntimeException