2012-12-18 48 views
0

我在我的活动中创建了一个处理程序。处理程序将被存储在应用程序对象中。处理程序不会在我的活动中被调用

protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.action_activity); 
    appData = (AttachApplication) getApplication(); 

    Handler updateHandler = new Handler() { 
     public void handlerMessage(Message msg) { 
      Log.d(TAG, "handle message "); 
     } 
    }; 
    appData.setUpdateHandler(updateHandler); 


} 

我的计划是,当我在我的服务setEmtpyMessage时,将调用此handleMessage。该服务从应用程序对象中检索处理程序。

public int onStartCommand(Intent intent, int flags, int startId) { 
    Log.d(TAG, "onStartCommand of attachService"); 
    List<Job> jobList = DBManager.getInstance().getAllOpenJobs(); 
    appData = (AttachApplication) getApplication(); 
    updateHandler = appData.getUpdateHandler(); 
      updateHandler.sendEmptyMessage(101); 

我检查了日志,但没有处理消息,因此看起来我的计划不起作用。每次我的服务完成其工作时,我都想更新文本字段。

回答

0

在你的情况shoild使用广播接收器是这样的:

在你的Activity类定义接收器:在您的onCreate或OnStart方法

public class DataUpdateReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     if (intent.getAction().equals(MainService.REFRESH_DATA_INTENT)) { 
         //do something 
     } 
    } 
} 

你必须注册接收器:

DataUpdateReceiver dataUpdateReceiver = new DataUpdateReceiver(); 
IntentFilter intentFilter = new IntentFilter(MainService.REFRESH_DATA_INTENT); 
registerReceiver(dataUpdateReceiver, intentFilter); 

在您的服务上加上:

public static final String REFRESH_DATA_INTENT = "done"; 

,当你完成了所有的工作人员必须发送brocast这样的:

sendBroadcast(new Intent(MainService.REFRESH_DATA_INTENT)); 
+0

感谢这真的帮助,我可以再次在视图中做一些东西,并更新我的文本字段 –

0

您的代码段说public void handlerMessage(Message msg),但我想你的意思public void handleMessage(Message msg),没有r。当您打算覆盖超类的方法时,可以通过使用@Override标记来避免这些问题;所以你的代码片段将呈现@Override public void handleMessage(Message msg),而@Override public void handlerMessage(Message msg)将是一个错误。

0

你想要做什么?我真的没有看到在活动中实例化Handler的意义,因为你所做的只是从MessageQueue获取消息。你当然不想与Android发布的任何消息混在一起,并且有更好的方式发送消息给Activity。

当然,您不包含AttachApplication的代码,所以我只能推测。

您还试图从服务访问此处理程序。事情正在发生,但我不知道是什么。

如果您想在每次服务完成其工作时更新TextView,请将广播Intent从服务发送到活动,并在活动中使用广播接收器。您还应该考虑使用IntentService而不是服务。

相关问题