SQLite数据库的更新引发服务内容,通过观察来更新 [英] Sqlite Database updates triggers Service to update via Content Observer

查看:153
本文介绍了SQLite数据库的更新引发服务内容,通过观察来更新的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用一个内容观察员更新服务时的任何变化发生在我的应用程序的SQLite数据库。

我很困惑,怎么做,所以我放在一起下面的一些code。通常情况下,内容观察家们使用的接触或与媒体播放器的后台服务。在我的研究,我读了它可以用在手机上的SQLite数据库中。

问题: 1.由于SQLite数据库没有一个URI,我更换了什么信息 People.CONTENT_URI

  this.getContentResolver()registerContentObserver(People.CONTENT_URI,真实,contentObserver)。
 

2。在我的研究,我没有找到任何code,将进入将提醒ContentObserver数据库类。是否所有的code为服务类中的内容观察员的工作?

请注意,这个问题类似于的Andr​​oid的SQLite数据库通知怎么听的变化联系数据库 这两个问题都没有明确回答我的问题。如果你有code,解释这一点,那将是非常有益的。

下面是我的半pusedo code以下。这不可行。我用它来学习如何当数据库信息的变化更新服务。

 包com.example.com.test.content.observer;

进口java.sql.Date;
进口的java.util.Calendar;
进口的java.util.List;

进口com.google.android.gcm.demo.app.Alerts.AlarmsService;
进口com.google.android.gcm.demo.app.Alerts.Alerts;
进口com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;

进口android.os.Bundle;
进口android.os.Handler;
进口android.os.IBinder;
进口android.provider.Contacts.People;
进口android.annotation.Sup pressLint;
进口android.app.Activity;
进口android.app.AlarmManager;
进口android.app.PendingIntent;
进口android.content.Intent;
进口android.database.ContentObserver;
进口android.util.Log;
进口android.view.Menu;
进口android.view.MenuItem;
进口android.widget.Toast;
进口android.support.v4.app.NavUtils;

公共类AlarmService扩展服务
{

    处理器mHandler =新的处理程序();
    DatabaseSqlite DB =新DatabaseSqlite(本);
    名单<通知> listAlerts;
    PendingIntent pendingIntent;


    @覆盖
    公共无效的onCreate(包savedInstanceState){
        super.onCreate(savedInstanceState);
        的setContentView(R.layout.activity_main);
        this.getApplicationContext()
                .getContentResolver()
                .registerContentObserver(?????,真实,
                        contentObserver);
    }


    公众诠释onStartCommand(意向意图,诠释标志,诠释startId){
        Log.d(TAG,开始从创建警报服务的OnStart命令。);
        返回super.onStartCommand(意向,标志,startId); // START_STICKY;
    }

    @覆盖
    公共无效ONSTART(最终意图的意图,诠释startId){
        super.onStart(意向,startId);

         runThread();
    }

    @覆盖
    公共无效的onDestroy(){
        super.onDestroy();
        Toast.makeText(本,服务破坏......,Toast.LENGTH_LONG).show();
    }

    @覆盖
    公众的IBinder onBind(意向意图){
        返回null;
    }

    私有类MyContentObserver扩展ContentObserver {

        @燮pressLint(ParserError)
        公共MyContentObserver(处理器mHandler){
            超(mHandler);
        }

        @覆盖
        公共无效的onChange(布尔selfChange){

             runThread();

            super.onChange(selfChange);
        }



        公共无效runThread(){

            线程线程=新的Thread(){
                @覆盖
                公共无效的run(){

                    布尔X =真;
                    而(X){

                        db.open();
                        listAlerts = db.getAlarmsForService();
                        db.close();
                        诠释警报= listAlerts.size();
                        的for(int i = 0; I<警报;我++){
                            快讯项目= listAlerts.get(我);
                            item.getRowId();
                            item.getRemoteServerId();
                        串alertInMills = item.getAlertDateInMills();
                        串alertDuration = item.getAlertDurationInMinutes();
                        串eventName的= item.getEventName();


                        长longAlertInMills =的Long.parseLong(alertInMills);



                         pendingIntent = PendingIntent.getService(AlarmsService.this,0,意向,0);

                         AlarmManager alarmManager =(AlarmManager)getSystemService(ALARM_SERVICE);

                         台历挂历= Calendar.getInstance();

                        //到数据库的时间在造纸厂

                         calendar.setTimeInMillis(longAlertInMills);

                         alarmManager.set(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),
                         pendingIntent);
                        //
                         的System.out.println(calendar.toString());

                        }

                        //
                        的System.out.println(线);
                        X = FALSE;

                    }

                }
            };

            thread.start();
        }

        }


    MyContentObserver contentObserver =新MyContentObserver(mHandler);

    。this.getContentResolver()registerContentObserver(People.CONTENT_URI,真实,contentObserver);



}
 

解决方案

在一般情况下,有两个部分来处理这样的:你有的 ContentObserver 这需要注册接收的变化,因为你已经指出的那样,和的 SQLiteDatabase 有通知任何更改注册的观察者。如果这是你自己的数据库,你可以创建URI,你可以用它来听。

(1)首先定义的URI,通常是在你的数据库定义文件。

 公共静态最终乌里CONTENT_URI = Uri.parse(为myContent://软件包名/某事);
 

(2)为你的数据库内容供应商:

每个数据库功能(插入,更新,删除)应调用通过对有NotifyChange()完成操作,以通知观察者的变化发生后。

  ROWID = db.insert(tableName值,空,CV);
    ...
    。的getContext()getContentResolver()有NotifyChange(newUri,空)。
 

(3)创建并注册自己的 ContentObserver 的服务,如您在上面提供href="http://stackoverflow.com/questions/1401280/how-to-listen-for-changes-in-contact-database">同一链路上的 deliverSelfNotifications()返回true)

 公共类的MyService延伸服务{
    私人MyContentObserver mObserver;

    @覆盖
    公共无效onStartCommand(意向意图,诠释标志,诠释startId){
        ...
        mObserver =新MyContentObserver();
        。getContentResolver()registerContentObserver(Dbfile.CONTENT_URI,空,mObserver);
    }

    @覆盖
    公共无效的onDestroy(){
        ...
        如果(mObserver!= NULL){
            。getContentResolver()unregisterContentObserver(mObserver);
            mObserver = NULL;
        }
    }

    //在这里定义MyContentObserver
}
 

(4)在你的 ContentObserver.onChange(),你可以发布的东西服务或办理变更权有可能的话。

此外,如果它可以帮助你的事业,你可以自定义的URI定义来处理不同类型的数据,你的观察,注册您的观察员每个URI,然后重写<一个href="http://developer.android.com/reference/android/database/ContentObserver.html#onChange%28boolean,%20android.net.Uri%29"相对=nofollow> ContentObserver.onChange(布尔,URI)代替。

希望这有助于!

I'm trying to use a Content Observer to update a Service when any changes happen to the sqlite database in my app.

I'm confused as to what to do, so I put together some code below. Usually, Content Observers are used with contacts or mediaplayer with a background service. In my research I read that it can be used with the sqlite database on the phone.

Questions: 1. Since Sqlite database does not have a uri, what info do I replace People.CONTENT_URI in

this.getContentResolver().registerContentObserver (People.CONTENT_URI, true, contentObserver);

2. In my research I didn't find any code that would go into the database class that would alert the ContentObserver. Does all the code for the Content Observer work within the service class?

Note that this question is similar to Android SQLite DB notifications and how to listen for changes in Contact Database Both questions do not explicitly answer my question. If you have code that explains this, that would be very helpful.

Here is my semi-pusedo code below. It does not work. I'm using it to learn about how to update a service when the database info changes.

package com.example.com.test.content.observer;

import java.sql.Date;
import java.util.Calendar;
import java.util.List;

import com.google.android.gcm.demo.app.Alerts.AlarmsService;
import com.google.android.gcm.demo.app.Alerts.Alerts;
import com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;

import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.provider.Contacts.People;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.database.ContentObserver;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.Toast;
import android.support.v4.app.NavUtils;

public class AlarmService extends Service
{

    Handler mHandler = new Handler();
    DatabaseSqlite db = new DatabaseSqlite(this);
    List<Alerts> listAlerts;
    PendingIntent pendingIntent;


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        this.getApplicationContext()
                .getContentResolver()
                .registerContentObserver(?????, true,
                        contentObserver);
    }


    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "started onstart command Created from Alerts service .");
        return super.onStartCommand(intent, flags, startId);// START_STICKY;
    }

    @Override
    public void onStart(final Intent intent, int startId) {
        super.onStart(intent, startId);

         runThread();
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    private class MyContentObserver extends ContentObserver {

        @SuppressLint("ParserError")
        public MyContentObserver(Handler mHandler) {
            super(mHandler);
        }

        @Override
        public void onChange(boolean selfChange) {

             runThread();

            super.onChange(selfChange);
        }



        public void runThread(){

            Thread thread = new Thread() {
                @Override
                public void run() {

                    Boolean x = true;
                    while (x) {

                        db.open();
                        listAlerts = db.getAlarmsForService();
                        db.close();
                        int alerts=listAlerts.size();
                        for (int i = 0; i < alerts; i++) {
                            Alerts item = listAlerts.get(i);
                            item.getRowId();
                            item.getRemoteServerId();
                        String alertInMills = item.getAlertDateInMills();
                        String alertDuration = item.getAlertDurationInMinutes();
                        String eventName = item.getEventName();


                        long longAlertInMills = Long.parseLong(alertInMills);



                         pendingIntent = PendingIntent.getService(AlarmsService.this, 0,intent, 0);

                         AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);

                         Calendar calendar = Calendar.getInstance();

                        // go to data base for time in mills

                         calendar.setTimeInMillis(longAlertInMills);

                         alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                         pendingIntent);
                        //
                         System.out.println(calendar.toString());

                        }

                        //
                        System.out.println("thread");
                        x = false;

                    }

                }
            };

            thread.start();
        }

        }


    MyContentObserver contentObserver = new MyContentObserver(mHandler);

    this.getContentResolver().registerContentObserver (People.CONTENT_URI, true, contentObserver);



}

解决方案

In general, there are two parts to handling this: you have the ContentObserver which needs to register to receive changes, as you've pointed out, and the SQLiteDatabase which has to notify the registered observers of any changes. If this is a database you own, you can create the URI that you can use to listen for.

(1) First define your URI, typically in your Database definition file.

public static final Uri CONTENT_URI = Uri.parse("mycontent://packagename/something");

(2) for your database Content Provider:

Each db function (insert, update, delete) should call through to notifyChange() after completing the operation in order to inform the observers that changes have happened.

    rowId = db.insert(tableName, null, cv);
    ...
    getContext().getContentResolver().notifyChange(newUri, null);

(3) Create and register your ContentObserver in the Service, as described in the same link you provided above (remember to override the deliverSelfNotifications() to return true)

public class MyService extends Service {
    private MyContentObserver mObserver;

    @Override
    public void onStartCommand(Intent intent, int flags, int startId) {
        ...
        mObserver = new MyContentObserver();
        getContentResolver().registerContentObserver(Dbfile.CONTENT_URI, null, mObserver);
    }

    @Override
    public void onDestroy() {
        ...
        if (mObserver != null) {
            getContentResolver().unregisterContentObserver(mObserver);
            mObserver = null;
        }
    }

    // define MyContentObserver here
}

(4) In your ContentObserver.onChange(), you can post something to the Service or handle the change right there if possible.

Also, if it helps your cause, you can customize the URI definition to handle different types of data that you are observing, register your observer for each URI, and then override ContentObserver.onChange(boolean, Uri) instead.

Hope this helps!

这篇关于SQLite数据库的更新引发服务内容,通过观察来更新的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆