我有一个BroadcastReceiver
可以监控我与 Wifi 或移动网络的连接状态。这样做的重点是在手机建立连接时BroadcastReceiver
访问 a 。SQLite Database
所以在我的onPause
方法中,我注册了接收者:
networkMonitor = new CaseQueueReceiver();
IntentFilter filter = new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(networkMonitor, filter);
在我的onDestory
方法中,我取消注册它
unregisterReceiver(networkMonitor);
到这个 networkMonitor 接收器
public class CaseQueueReceiver extends BroadcastReceiver {
public boolean available;
DatabaseHandler db;
QueueDB queueDB;
HashMap<String, String> queueHashMap;
public CaseQueueReceiver() {
db = new DatabaseHandler(ContextHelper.context());
queueDB = new QueueDB(ContextHelper.context());
queueHashMap = new HashMap<String, String>();
}
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
String typeName = info.getTypeName();
String subtypeName = info.getSubtypeName();
available = info.isAvailable();
Log.i("Network Monitor", "Network Type: " + typeName
+ ", subtype: " + subtypeName
+ ", available: " + available);
//call a method which will get all the unsent cases from the database, and update their field of sent status
//in order to do so, add an extra column in the database, also remember to delete the cases.
if(available) {
int count = queueDB.countUnsentCases();
Log.i("Count unsentCases: ", Integer.toString(count));
queueDB.getUnsetCases();
// Iterator<Entry<String, String>> it = queueHashMap.entrySet().iterator();
// while (it.hasNext()) {
// Map.Entry pairs = (Map.Entry)it.next();
// Log.i("In the Queue: ", "PCN: " + pairs.getKey() + " Nist-File: " + pairs.getValue());
// }
}
}
}
还有我来自 QueueDB 的两种方法
public int countUnsentCases() {
String SQLQuery = "SELECT COUNT(" + PCN + ") FROM "
+ TABLE_CASES_IN_QUEUE + ";";
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(SQLQuery, null);
cursor.moveToFirst();
int count = cursor.getInt(0);
cursor.close();
db.close();
return count;
}
public HashMap<String, String> getUnsetCases() {
HashMap<String, String> queueHashMap = new HashMap<String, String>();
SQLiteDatabase db = this.getWritableDatabase();
String query = "SELECT * FROM " + TABLE_CASES_IN_QUEUE + ";";
Cursor cursor = db.rawQuery(query, null);
if (cursor.moveToFirst()) {
do {
Log.i("CURSOR(0)", cursor.getString(0));
// queueHashMap.put(cursor.getString(0), cursor.getString(1));
} while (cursor.moveToNext());
}
cursor.close();
db.close();
return queueHashMap;
}
我遇到的问题是,onReceive
当我打开 Wifi 时,该方法将被称为无限。这不会导致任何异常,我的应用程序只会挂起,并占用堆的内存。我知道我应该在线程中读取/写入数据库。谁能解释为什么这个onReceive
方法会被调用这么多次?解决此问题的最佳方法是什么?
提前致谢!