我正在開發一個使用SQLite連接的簡單Android應用程序。當我運行它,它執行異步任務從SQLite的讀取所有記錄,並將其顯示在應用程序的列表:30秒後Android - SQLite,Alarm Receiver和異步任務之間的合作
public class ReadData extends AsyncTask< Void, Void, String >
{
@Override
protected String doInBackground(Void... arg0)
{
Database oDatabase = new Database();
SQLiteDatabase myDB = oDatabase.getWritableDatabase();
Cursor cursor = myDB.rawQuery("SELECT * FROM `items` ORDER BY `id`", null);
if(cursor != null)
{
while(cursor.moveToNext())
{
MainActivity.items.add(new DataItem(Database.getIntegerIndex(cursor, "test a"), Database.getIntegerIndex(cursor, "test b"), Database.getIntegerIndex(cursor, "test c"), Database.getIntegerIndex(cursor, "test d")));
}
}
}
}
如果我點擊按鈕「添加」報警接收器運行另一個異步任務它確實幾個數據庫插入:
public class InsertData extends AsyncTask< Void, Void, String >
{
@Override
protected String doInBackground(Void... arg0)
{
Database oDatabase = new Database();
SQLiteDatabase myDB = oDatabase.getWritableDatabase();
ContentValues newTodoValues = new ContentValues();
int iTestA = new Random().nextInt(100);
int iTestB = new Random().nextInt(100);
int iTestC = new Random().nextInt(100);
int iTestD = new Random().nextInt(100);
newTodoValues.put("test a", iTestA);
newTodoValues.put("test b", iTestB);
newTodoValues.put("test c", iTestC);
newTodoValues.put("test d", iTestD);
myDB.insert("items", null, newTodoValues);
boolean bIsRunning = false;
String[ ] tokens = Tools.getBase().getApplicationContext().getPackageName().split("\\.");
if(tokens.length >= 3 && tokens[ 0 ].equals("kibbo") && tokens[ 1 ].equals("soft") && tokens[ 2 ].equals("app"))
bIsRunning = Tools.getBase().getApplicationContext().getPackageName().equalsIgnoreCase(((ActivityManager)Tools.getBase().getApplicationContext().getSystemService(Context.ACTIVITY_SERVICE)).getRunningTasks(1).get(0).topActivity.getPackageName());
if(bIsRunning && Tools.base.getEngine() != null)
MainActivity.items.add(new DataItem(newTodoValues.getAsInteger("test a"), newTodoValues.getAsInteger("test b"), newTodoValues.getAsInteger("test c"), newTodoValues.getAsInteger("test d")));
}
}
當我點擊「添加」按鈕,然後離開應用程序,報警接收器將仍然執行異步任務,並在30秒後SQL插入。它安全嗎?我的意思是當我在Async Task的SQL插入過程中完美地運行我的應用程序時會發生什麼?是否有可能發生錯誤?