QueryService.java revision 654888562d75fe4758cb0500f73aaa11385e6f63
1/* 2 * Copyright (C) 2011 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.contacts.tests; 18 19import android.app.IntentService; 20import android.content.Intent; 21import android.database.Cursor; 22import android.net.Uri; 23import android.util.Log; 24 25/** 26 * A service that executes a query specified by an intent and dump the result on logcat. Use the 27 * "am" command to launch it. 28 * 29 Usage: 30 adb shell am startservice -d URI \ 31 [-e s OPTIONAL SELECTION] [-e s OPTIONAL ORDER BY] \ 32 com.android.contacts.tests/.QueryService 33 34 Example: 35 36 adb shell am startservice -d content://com.android.contacts/directories \ 37 -e s 'accountName is null' -e o '_id' \ 38 com.android.contacts.tests/.QueryService 39 */ 40public class QueryService extends IntentService { 41 private static final String TAG = "contactsquery"; 42 43 private static final String EXTRA_SELECTION = "s"; 44 private static final String EXTRA_ORDER = "o"; 45 private static final String NULL_STRING = "*null*"; 46 private static final String SEPARATOR = "|"; 47 48 public QueryService() { 49 super("ContactsQueryService"); 50 } 51 52 @Override 53 protected void onHandleIntent(Intent intent) { 54 final Uri uri = intent.getData(); 55 final String selection = intent.getStringExtra(EXTRA_SELECTION); 56 final String order = intent.getStringExtra(EXTRA_ORDER); 57 58 Log.i(TAG, "URI: " + uri); 59 Log.i(TAG, "Selection: " + selection); 60 61 Cursor c = getContentResolver().query(uri, null, selection, null, order); 62 if (c == null) { 63 Log.i(TAG, "(no results)"); 64 return; 65 } 66 StringBuilder sb = new StringBuilder(); 67 try { 68 Log.i(TAG, "Result count: " + c.getCount()); 69 70 final int columnCount = c.getColumnCount(); 71 72 sb.setLength(0); 73 for (int i = 0; i < columnCount; i++) { 74 add(sb, c.getColumnName(i)); 75 } 76 Log.i(TAG, sb.toString()); 77 78 c.moveToPosition(-1); 79 while (c.moveToNext()) { 80 sb.setLength(0); 81 for (int i = 0; i < columnCount; i++) { 82 add(sb, c.getString(i)); 83 } 84 Log.i(TAG, sb.toString()); 85 } 86 } finally { 87 c.close(); 88 } 89 } 90 91 private StringBuilder add(StringBuilder sb, String s) { 92 if (sb.length() > 0) { 93 sb.append(SEPARATOR); 94 } 95 sb.append(s == null ? NULL_STRING : s); 96 return sb; 97 } 98} 99