[英]Android: Run a thread in the background without delaying activity
我有一個提取聯系人信息的過程,這需要很長時間-4秒。 我不希望它干擾我的應用程序中的用戶體驗。 我有兩個問題:
我嘗試過從onCreate,onStart和onResume調用下面的getContacts()方法,但是在所有情況下,直到方法完全運行之后,屏幕才會出現。
這是代碼:
private void getContacts() {
Thread thread = new Thread() {
@Override
public void run() {
try {
Log.d("ManageFriends","getContacts Start");
ContentResolver cr = getContentResolver();
String[] PROJECTION = new String[] {
ContactsContract.CommonDataKinds.Email.CONTACT_ID,
ContactsContract.Contacts.DISPLAY_NAME,
ContactsContract.CommonDataKinds.Email.ADDRESS,
ContactsContract.CommonDataKinds.Email.IS_PRIMARY,
};
String filter = ContactsContract.CommonDataKinds.Email.ADDRESS + " NOT LIKE '' AND 1 == " +
ContactsContract.Contacts.IN_VISIBLE_GROUP + " AND " +
ContactsContract.Contacts.DISPLAY_NAME + " NOT LIKE '%@%'";
Cursor cur = cr.query(ContactsContract.CommonDataKinds.Email.CONTENT_URI, PROJECTION, filter, null, null);
DBHelper.insertArrayList(db,"Contacts",DBHelper.cursorToArrayList(cur));
Log.d("ManageFriends","getContacts End");
}
catch (Exception e) {
e.printStackTrace();
}
}
};
thread.run();
}
注意:我知道這個過程很慢的主要原因-我將光標結果轉換為ArrayList <ArrayList <String >>,然后將其插入到SQLite數據庫中。 但是,如果我能在后台運行它,我會很高興的。
考慮使用daemon
線程。
Daemon
線程通常用於為您的應用程序/小程序執行服務(例如加載“小提琴位”)。 用戶線程和守護程序線程之間的核心區別在於,JVM將僅在所有用戶線程終止后才關閉程序。 當不再運行任何用戶線程(包括執行的主線程)時,JVM將終止守護程序線程。
PS這是低優先級線程
資料來源:
例
Thread thread = new Thread();
thread.setDaemon(true);
thread.start();
編輯!
AsyncTask
出AsyncTask
此鏈接 ,它是UI后台任務的線程。
考慮使用CursorLoader在后台線程中從ContentProvider加載數據: 檢索聯系人列表
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.