在我的活动中不会调用处理程序

时间:2012-12-18 20:35:38

标签: android android-service android-handler

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

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 );


}

我的计划是在我的服务中设置setMmtpyMessage时将调用此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 );

我检查了日志,但是没有句柄消息,所以我的计划似乎不起作用。我想在每次服务完成工作时更新文本字段。

3 个答案:

答案 0 :(得分:0)

在你的情况下,你可以像这样使用BroadcastReceiver:

在Activity类中定义接收器:

public class DataUpdateReceiver extends BroadcastReceiver {

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

在onCreate或onStart方法中,您必须注册接收者:

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));

答案 1 :(得分: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)则会出错。

答案 2 :(得分:0)

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

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

您还尝试从服务访问此Handler。有些事情正在发生,但我不确定是什么。

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

相关问题