Android - 使用Service连接ContentObserver

时间:2014-05-04 21:04:14

标签: android service intentfilter contentobserver

我有一个简单的应用程序,我正在努力学习如何:

1)调用Web服务

2)解析数据

3)将其保存到SQLiteDatabase

4)设置ContentObserver / Broadcaster以检测活动中的更改并更改UI

到目前为止,我已经完成了所有工作,但遇到了第4步的问题。

代码:

LaunchActivity显示包含我最终想要更改的UI的布局,启动Service类:

Intent intent = new Intent(this, DataService.class);
intent.putExtra("restMethodType", 0);
startService(intent);

然后DataService类运行所需的AsyncTask Rest方法:

public class DataService extends IntentService {

    public DataService() {
        super("DataService");
    }

    public DataService(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        RestMethodType restMethodType = RestMethodType.values()[intent.getIntExtra("restMethodType", 0)];

        switch (restMethodType) {
            case UPCOMING_MATCH:
                UpcomingMatchRestMethod restMethod = new UpcomingMatchRestMethod(getApplicationContext(), intent);
                restMethod.execute();
                break;
        }
    }
}

AsyncTask的onPostExecute方法中,我将检索到的数据保存到数据库中,然后广播事件:

long newRowId = database.insert(MatchContract.MatchEntry.TABLE_NAME, MatchContract.MatchEntry.COLUMN_NAME_LOCATION, values);

if(newRowId != -1){
    mIntent.putExtra("matchId", newRowId);
    LocalBroadcastManager.getInstance(mContext).sendBroadcast(mIntent);
}

回到LaunchActivity,我设置了一个接收器对象:

DataReceiver mDataReceiver;

@Override
protected void onResume() {
    super.onResume();
    IntentFilter intentFilter = new IntentFilter("What Goes In Here?");
    registerReceiver(mDataReceiver, intentFilter);
}

这就是接收器的样子:

private class DataReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // Do Stuff like update the UI
        // Make sure to wrap any View objects in runOnUIThread
    }
}

那么IntentFilter会发生什么?还有什么我想念的?我跟着谷歌文档,但有点困惑。

提前谢谢。

0 个答案:

没有答案