如何在服务中访问数据库?

时间:2017-11-06 16:17:31

标签: android database sqlite service android-sqlite

public class BackServices  extends BroadcastReceiver {

    private boolean screenOff;

    @Override
    public void onReceive(Context context, Intent intent) {

        context.startService(new Intent(context, UpdateService.class));
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
            screenOff = true;
        } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
            screenOff = false;
        }

                Intent i = new Intent(context, UpdateService.class);
                i.putExtra("screen_state", screenOff);
                context.startService(i);
            }

}

我需要访问数据库并从中收集电话号码我该怎么做。

1 个答案:

答案 0 :(得分:0)

我做了这个,如下所示。它现在正在运作。

private boolean screenOff;
String str1,str2,str3,str4,str5;
@Override
public void onReceive(Context context, Intent intent) {

    context.startService(new Intent(context, UpdateService.class));
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
        screenOff = true;
    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
        screenOff = false;
    }
    DB db = new DB(context);
    Cursor c = db.getdata1();
    while (c.moveToNext()) {

        str1 = c.getString(c.getColumnIndex(DB.col1));
        str2 = c.getString(c.getColumnIndex(DB.col2));
        str3 = c.getString(c.getColumnIndex(DB.col3));
        str4 = c.getString(c.getColumnIndex(DB.col4));
        str5 = c.getString(c.getColumnIndex(DB.col5));
    }

            Intent i = new Intent(context, UpdateService.class);
            i.putExtra("screen_state", screenOff);
            i.putExtra("str1",str1);
            i.putExtra("str2",str2);
            i.putExtra("str3",str3);
            i.putExtra("str4",str4);
            i.putExtra("str5",str5);
            context.startService(i);
        }