What happens to an Android thread after the Activity that created it is destroyed?

前端 未结 4 1886
一向
一向 2021-02-07 04:25

In my Android app, the main Activity will sometimes start a Thread to load data from a server. This thread modifies the app\'s database and edits some important files. AFAIK,

4条回答
  •  梦毁少年i
    2021-02-07 05:10

    I might be digging out an old thread, but nobody mentioned one important thing.

    Every time you use a database and modify multiple rows, you should make use of transactions to ensure that data stays valid in case of any kind of failure (which might be for example a termination of a thread, a socket exception etc.).

        try{
            db.beginTransaction(); 
    
            //Do whatever you need to do...    
    
            db.setTransactionSuccessful();
        }catch(SQLiteException e){
            Log.e("SQLite","Error while updating rows: " + e.getMessage());
        }finally{
            db.endTransaction(); //Commit (if everything ok) or rollback (if any error occured). 
            db.close(); //Close databse;
        }
    

提交回复
热议问题