我的应用程序中有Realm数据库。当我的应用程序处于活动状态时,我没有写入数据的问题,但如果我启动IntentService然后关闭应用程序,我在Realm数据库中什么都没有。
我的IntentService:
@Override
protected void onHandleIntent(Intent intent) {
RealmResults<HashtagObject> hashtags;
SubscriberObject subscriber = new SubscriberObject();
Realm realmForThisThread = Realm.getDefaultInstance();
hashtags = realmForThisThread.where(HashtagObject.class).findAll();
for(int i=0;i<hashtags.size();i++){
getRecentlyTag(Constants.API_URL);
}
realmForThisThread.beginTransaction();
for (Map.Entry entry : hm.entrySet()) {
if(realmForThisThread.where(SubscriberObject.class)
.equalTo(SubscriberObject.ID,entry.getKey().toString()).findAll().isEmpty()) {
subscriber.setId(entry.getKey().toString());
subscriber.setUsername(entry.getValue().toString());
subscriber.setDate(mDate.getTime());
realmForThisThread.insert(subscriber);
}
}
realmForThisThread.commitTransaction();
realmForThisThread.close();
}
private void getRecentlyTag(String path,final String tagName){
HttpURLConnection urlConnection = null;
try {
Thread.sleep(10000);
URL url = new URL(path);
urlConnection = (HttpURLConnection) url
.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
String response = Tools.streamToString(urlConnection
.getInputStream());
JSONObject jsonObj = (JSONObject) new JSONTokener(response)
.nextValue();
for(int i=0;i<jsonObj.getJSONArray("data").length();i++) {
JSONObject json = (JSONObject) jsonObj.getJSONArray("data").get(i);
hm.put(json.getJSONObject("user").getString("id"),json.getJSONObject("user").getString("username"));
}
}catch(Exception exc){
exc.printStackTrace();
}finally {
if(urlConnection!=null){
try{
urlConnection.disconnect();
}catch(Exception e){
e.printStackTrace();
}
}
}
}
我正在使用:
classpath "io.realm:realm-gradle-plugin:2.0.2" // Top-level build file
compile 'io.realm:android-adapters:1.3.0' //app gradle
在片段中启动IntentService,如:
@OnClick(R.id.find_users)
public void startClick(){
Intent intent = new Intent(getActivity(), SubscribersGathering.class);
getActivity().startService(intent);
}
Application类中的Realm cofigs:
Realm.init(this);
RealmConfiguration realmConfiguration = new RealmConfiguration.Builder()
.deleteRealmIfMigrationNeeded()
.build();
Realm.setDefaultConfiguration(realmConfiguration);