我有一个小项目,我从内容提供商那里读取系统指标,如呼叫日志、短信日志等。
我创建了(Call/SMS)Logger类来从内容提供者读取信息并将信息保存在(Call/SMS)Metrics类的对象中。
MainActivity使用(Call/SMS)Metrics类的对象中的信息,并使用 databaseOpenHelper 类将数据保存在我自己的数据库中。
现在我打算使用 CursorLoader 从 contentproviders 加载数据。
我看到的例子表明 MainActivity 实现了 LoaderManager.LoaderCallbacks
当对非活动类进行实际查询时,如何在我的项目中使用它?
我可以在 Activity 中创建 I 1 loaderManger 并用于每个非 Activity 吗?
以下是一些示例代码片段:
从 Main Activity 我调用数据集合,我将上下文传递给 clssess 以便他们可以在管理器光标中使用它
private void CollectSystemMetrics() {
//passing the context in constructor so that it can be passed to
//the non activity classes which need it for quering
SystemMetricsCollector collector = new SystemMetricsCollector(this);
_callMetrics = collector.CollectCallMetrics();
_smsMetrics = collector.CollectSMSMetrics();
Toast toast = Toast.makeText(
MyActivity.this,
"Calls and SMS Data Collected",
Toast.LENGTH_SHORT);
toast.show();
}
SystemMetricsCollector 中用于获取 SMSData 的方法
public SMSMetrics CollectSMSMetrics() {
SMSLogger smsLogger = new SMSLogger(_context);
smsLogger.ReadSMSDataFromPhone();
return smsLogger.GetSMSMetrics();
}
SMSLogger 类中的变量。
Uri smsUri = Uri.parse("content://sms");
String[] selectColumns = null;
String where = null;
String whereArgs[] = null;
String sortBy = null;
SMSLogger 中使用游标读取数据的方法
public void ReadSMSDataFromPhone() {
int inCount = 0, outCountContacts = 0, outCountUnknown = 0;
Cursor managedCursor;
managedCursor = _context.getContentResolver().query(
smsUri,selectColumns,where,whereArgs,sortBy);
try {
if (managedCursor.moveToFirst()) {
int idxAddress = managedCursor.getColumnIndexOrThrow("address");
int idxType = managedCursor.getColumnIndex("type");
do {
int valType = managedCursor.getInt(idxType);
switch (valType) {
case 2://outgoing
String valAddress =
managedCursor.getString(idxAddress);
if (isContact(valAddress)) outCountContacts++;
else outCountUnknown++;
break;
default://incoming
inCount++;
break;
}
} while (managedCursor.moveToNext());
}
} finally {
managedCursor.close();
}//end finally
_smsMetrics.set_receivedSMS(inCount);
_smsMetrics.set_sentSMSContacts(outCountContacts);
_smsMetrics.set_sentSMSUnknown(outCountUnknown);
}