嘿,一个新手来android编程和我正在这个项目上工作。 这个问题很长,所以这里就是交易。在其他线程上执行方法的同步
我有延长GCMBaseIntentService
这个GCMIntentService类和当消息从服务器到达时,GCMBroadcastReceiver
可自动识别并调用GCMIntentService类重写onMessage()
方法。现在在onMessage
正文中,我正在对SQLiteDatabase
执行一些操作,并且我正在通过在onMessage主体内的ui线程中调用adapter.notifyDataSetChanged()
来通知我的适配器进行列表视图。
现在,如果超过2或3 gcm的消息同时传到设备,应用程序会崩溃,因为多个线程正在调用相同的onMessage()
方法,并且正在搞乱我的数据库和适配器。我想我需要在一次只能由一个线程使用的方法上使用synchronized关键字。
但自从我onMessage
方法是一种覆盖方法,我决定做的另一种方法,把同步的修改就可以了,但我再次需要从里面调用runOnUiThread()
方法,因为我需要更改通知到我的列表视图的适配器。
我只是想问,如果这样做是正确的方式还是可以使用更简单的解决方案来解决我的问题?
下面是示例代码,什么M做:
@Override
protected void onMessage(Context arg0, Intent intent) {
// called when a new cloud message has been received
Log.w("Service ", "Started");
dbh = new DatabaseHandler(this);
sld = dbh.getWritableDatabase();
who = this;
// processing json object
putDataFromJSON();
//other stuff
}
synchronized private void putDataFromJSON(){
//do some work on JSON Object
//complete work on JSON by putting in database
dbh.saveInDB();
//notify the adapter
((MainActivity) MainActivity.con).runOnUiThread(new Runnable() {
@Override
public void run() {
adapter.notifyDataSetChanged();
//do other stuffs as well
}
}
}
我不明白你所谓的“线程”与bucle .. – delive