使用Intent服务在Android中进行后台处理

时间:2018-07-18 06:19:08

标签: android sqlite intentservice

我正在尝试使用Intent-service在android中进行后台处理,在我的项目中,用户可以在SQLite中存储许多记录(当用户处于离线模式时),每当用户连接WiFi或移动数据用户尝试同步离线数据,同时他正在SQLite中输入新数据。

当用户在同步记录时输入新记录时,数据设备的性能非常缓慢,UI也冻结了,如果我处理过程中的任何错误都可以有人帮助我,请

代码:-

public class NetworkIntentServiceForOfflineDetails extends IntentService {

    // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
    private static final String ACTION = ConnectivityManager.CONNECTIVITY_ACTION;
    //private NetworkChangeReceiver networkChangeReceiver;
    public NetworkIntentServiceForOfflineDetails() {
        super("NetworkIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {

            DatabaseAccess databaseAccess = new DatabaseAccess(this);
            databaseAccess.open();
            List<OfflineDataObj> offlineInfo = databaseAccess.getDetailsInfo();
            databaseAccess.close();
            UserPreferences.setPreferenceBoolean(Constants.IS_ALARM_ON, false);
            if (offlineInfo.size() == 0) {
           Toast.LENGTH_SHORT).show();
            } else if (NetWorkConnection.isConnected()) {

                try {
                    for(int i = 0 ; i < offlineInfo.size(); i++) {

                            OfflineDataObj offlineDataObj = offlineInfo.get(i);
                            String userId = UserPreferences.getPreferenceString(Constants.USER_ID,
                                    null);
                            String url = ServerUrls.SUBMIT_PROJECT_DETAILS_TO_SERVER + userId + "/" + "project_submissions";

VolleyHelperPostForOffline().callVolleyHelperPost(url, offlineDataObj.getJson(),
                                  Constants.NOTIFICATION_SUBMIT_PROJECT_DETAILS_TO_SERVER, this, null,
                                    offlineDataObj);

                    }
                } catch (Throwable throwable) {
                    throwable.printStackTrace();
                }
            } else {
                setAlarm();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

    private void setAlarm() {
        UserPreferences.setPreferenceBoolean(Constants.IS_ALARM_ON, true);
        PendingIntent pendingIntent;
        Intent myIntent = new Intent(NetworkIntentServiceForOfflineDetails.this, NetworkIntentServiceForOfflineDetails.class);
        pendingIntent = PendingIntent.getService(NetworkIntentServiceForOfflineDetails.this, 0, myIntent, 0);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + Constants.ALARM_TIME_FOR_OFFLINEDATA, pendingIntent);
    }
}

0 个答案:

没有答案