将上下文传递给内部类会返回nullpointerexception

时间:2014-03-12 17:28:10

标签: android multithreading handler android-toast

我在Service中有HandlerService,如下所示。

public class AdhocFinderService extends Service{
 Handler someHandler = new Handler(){

     //this method will handle the calls from other threads.       
     public void handleMessage(Message msg) {

          Toast.makeText(AdhocFinderService.this,"display", Toast.LENGTH_SHORT).show();
     }
};

在线程类

Message status = adhocFinderService.someHandler.obtainMessage();
Bundle data = new Bundle();
        data.putString("SOMETHING", "dist");
        Log.d(TAG,data.toString());
        status.setData(data);
        adhocFinderService.someHandler.sendMessage(status);

当我跑步时,我得到NullpointerException

03-12 13:13:14.542: E/AndroidRuntime(2862): FATAL EXCEPTION: main
03-12 13:13:14.542: E/AndroidRuntime(2862): java.lang.NullPointerException
03-12 13:13:14.542: E/AndroidRuntime(2862):     at android.content.ContextWrapper.getResources(ContextWrapper.java:80)
03-12 13:13:14.542: E/AndroidRuntime(2862):     at android.widget.Toast.<init>(Toast.java:89)
03-12 13:13:14.542: E/AndroidRuntime(2862):     at android.widget.Toast.makeText(Toast.java:231)
03-12 13:13:14.542: E/AndroidRuntime(2862):     at com.example.v2papp.AdhocFinderService$1.handleMessage(AdhocFinderService.java:43)
03-12 13:13:14.542: E/AndroidRuntime(2862):     at android.os.Handler.dispatchMessage(Handler.java:99)
03-12 13:13:14.542: E/AndroidRuntime(2862):     at android.os.Looper.loop(Looper.java:143)
03-12 13:13:14.542: E/AndroidRuntime(2862):     at android.app.ActivityThread.main(ActivityThread.java:4196)
03-12 13:13:14.542: E/AndroidRuntime(2862):     at java.lang.reflect.Method.invokeNative(Native Method)
03-12 13:13:14.542: E/AndroidRuntime(2862):     at java.lang.reflect.Method.invoke(Method.java:507)
03-12 13:13:14.542: E/AndroidRuntime(2862):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
03-12 13:13:14.542: E/AndroidRuntime(2862):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
03-12 13:13:14.542: E/AndroidRuntime(2862):     at dalvik.system.NativeStart.main(Native Method)

我认为我所做的是正确的。有人可以纠正我。谢谢

2 个答案:

答案 0 :(得分:0)

您可能希望使用getApplicationContext()而不是AdhocFinderService.this

请注意,我不是专家,但我认为这个答案会满足您的需求:Android Toast started from Service only displays once

答案 1 :(得分:0)

最后,我想出了从线程向服务发布消息的解决方案。如果没有正确实施Thread课程,您将无法发布消息。下面的代码工作正常。

Message status = adhocFinderService.someHandler.obtainMessage();

除非您将服务实例传递给线程,否则它会传递null值。