Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Lệnh gọi service trong service của firebase
- // Thực hiện gọi service polling
- if (!Help.isServiceRunning(JobService0TSleep.class, this)) {
- Log.d(TAG, "Chạy service polling vị trí");
- Intent intent = new Intent(this, JobService0TSleep.class);
- this.startService(intent);
- Log.d(TAG, "Đã chạy service polling vị trí thành công");
- } else {
- Log.d(TAG, "Service polling vị trí đang chạy");
- }
- // File service
- package vn.net.lad.taxi.driver.service;
- import android.app.IntentService;
- import android.content.Intent;
- import android.location.Location;
- import android.location.LocationListener;
- import android.location.LocationManager;
- import android.os.Bundle;
- import android.os.IBinder;
- import android.util.Log;
- import android.widget.Toast;
- import com.google.gson.Gson;
- import java.io.IOException;
- import java.util.ArrayList;
- import vn.net.lad.taxi.driver.CurrentUserSession;
- import vn.net.lad.taxi.driver.SettingGlobal;
- import vn.net.lad.taxi.driver.SharedPref;
- import vn.net.lad.taxi.driver.lib_app.jsonPositionGps;
- import vn.net.lad.taxi.driver.lib_base.Help;
- import vn.net.lad.taxi.driver.lib_base.ReturnApi;
- import vn.net.lad.taxi.driver.lib_base.UploadFileAsync;
- import vn.net.lad.taxi.driver.lib_base.Utils;
- import vn.net.lad.taxi.driver.lib_base.cDateTime;
- import vn.net.lad.taxi.driver.lib_base.cfile;
- import vn.net.lad.taxi.driver.lib_base.ctool;
- import vn.net.lad.taxi.driver.service.JobSetting;
- public class JobService0TSleep extends IntentService implements LocationListener {
- private final String TAG = "JobService0TSleep";
- public static final String RESPONSE_DATA = "data";
- // khai báo vị trí
- private Location myLocation;
- // flag for GPS status
- boolean isGPSEnabled = false;
- // flag for network status
- boolean isNetworkEnabled = false;
- // flag for GPS status
- boolean canGetLocation = false;
- // double latitude; // latitude
- // double longitude; // longitude
- // The minimum distance to change Updates in meters
- private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
- // The minimum time between updates in milliseconds
- private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
- // Declare time pooling
- static int countLoop = 0;
- static String folderSendPos, folderLogPos, file_tmp_upload;
- ArrayList<String> arrayList_file_send_pos;
- // Declaring a Location Manager
- protected LocationManager locationManager;
- public JobService0TSleep() {
- super("PositionUpdateService");
- folderSendPos = SettingGlobal.getSendPositionPath();
- folderLogPos = SettingGlobal.getLogPositionPath();
- if (!cfile.fileExist(folderSendPos))
- cfile.mkdir(folderSendPos);
- if (!cfile.fileExist(folderLogPos))
- cfile.mkdir(folderLogPos);
- }
- private jsonPositionGps getPos() {
- jsonPositionGps jsonPositionGps = new jsonPositionGps();
- try {
- locationManager = (LocationManager) getApplicationContext()
- .getSystemService(LOCATION_SERVICE);
- // getting GPS status
- isGPSEnabled = locationManager
- .isProviderEnabled(LocationManager.GPS_PROVIDER);
- // getting network status
- isNetworkEnabled = locationManager
- .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
- if (!isGPSEnabled && !isNetworkEnabled) {
- Log.d(TAG, "Chưa xác định được vị trí hiện tại");
- } else {
- this.canGetLocation = true;
- // if GPS Enabled get lat/long using GPS Services
- if (isGPSEnabled) {
- locationManager.requestLocationUpdates(
- LocationManager.GPS_PROVIDER,
- MIN_TIME_BW_UPDATES,
- MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
- Log.d(TAG, "GPS Enabled");
- if (locationManager != null) {
- myLocation = locationManager
- .getLastKnownLocation(LocationManager.GPS_PROVIDER);
- }
- }
- //
- // get location from Network Provider
- if (isNetworkEnabled) {
- if (myLocation == null) {
- locationManager.requestLocationUpdates(
- LocationManager.NETWORK_PROVIDER,
- MIN_TIME_BW_UPDATES,
- MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
- Log.d(TAG, "Network");
- if (locationManager != null) {
- myLocation = locationManager
- .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
- }
- }
- }
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- if (myLocation == null) {
- //showDialogInfo("Thông báo", "Bạn chưa bật vị trí");
- Toast.makeText(getApplicationContext(), "Chưa lấy được vị trí hiện tại", Toast.LENGTH_SHORT).show();
- return null;
- } else {
- // ctool.ol1(myLocation.getLatitude() + " - " + myLocation.getLongitude());
- Log.d(TAG, myLocation.getLatitude() + " - " + myLocation.getLongitude());
- jsonPositionGps.lat_position = myLocation.getLatitude() + "";
- jsonPositionGps.lng_position = myLocation.getLongitude() + "";
- jsonPositionGps.radius = SettingGlobal.RADIUS + "";
- // jsonPositionGps.get_near = 1;
- jsonPositionGps.option_get_status = "1";
- jsonPositionGps.userid_number = CurrentUserSession.getUserId();
- return jsonPositionGps;
- }
- }
- @Override
- public IBinder onBind(Intent intent) {
- // TODO: Return the communication channel to the service.
- throw new UnsupportedOperationException("Not yet implemented");
- }
- @Override
- protected void onHandleIntent(Intent intent) {
- cfile.ol1("JobService0TSleep: onHandleIntent ");
- long lastTimePooling = 0, dTime;
- if (intent != null) {
- // while (true) {
- // Log.d(TAG, "countLoop: " + countLoop);
- // if (countLoop > 0) {
- // try {
- // Thread.sleep(60000);
- // } catch (InterruptedException e) {
- // e.printStackTrace();
- // }
- //
- // }
- // try {
- // Thread.sleep(1000);
- // } catch (InterruptedException e) {
- // e.printStackTrace();
- // }
- if (!Utils.isOnline(this)) {
- Log.d(TAG, "Không có mạng?");
- // ctool.logError("Không có mạng ? ");
- return;
- } else {
- try {
- //Kiểm tra login, trường hợp này giải quyết vấn đề khi app killed, chúng ta bị mất giá trị CurrentUserSession
- if (!CurrentUserSession.isLogined()) {
- // CurrentUserSession.currentUserSession = SharedPref.getUserInfoInSharePref(getSharedPreferences(SharedPref.name, MODE_PRIVATE));
- CurrentUserSession.initInstance(SharedPref.getUserInfoInSharePref(getSharedPreferences(SharedPref.name, MODE_PRIVATE)));
- if (CurrentUserSession.getSessionToken() != null && CurrentUserSession.getSessionToken().length() > 0)
- CurrentUserSession.checkLoginOnline = 1;
- }
- // Thực hiện kết thúc chuyến đi
- String id_item = SharedPref.getIdItem(getSharedPreferences(SharedPref.s_id_item, MODE_PRIVATE));
- if (!SettingGlobal.isStopWithInternet && id_item != null) {
- Log.d(TAG, "Thực hiện kết thúc chuyến đi.");
- Log.d(TAG, "id_item: " + id_item);
- Help.replyDriverFinish(getApplicationContext(), id_item, "", "", "", "1");
- }
- // khởi tạo giá trị cho lớp jsonPositionGps để gán giá trị đầu vào
- jsonPositionGps jsonObj = new jsonPositionGps();
- jsonObj = getPos();
- if (jsonObj != null) {
- ctool.ol1("=== TSleep: count = " + countLoop++);
- dTime = (System.currentTimeMillis() - lastTimePooling) / 1000;
- if (lastTimePooling > 0)
- if (dTime > 10 * JobSetting.delayTime) {
- ctool.ol1(" *********************");
- ctool.ol1(" ***** JobService0TSleep: ERROR DTIME = " + dTime);
- ctool.ol1(" *********************");
- } else
- ctool.ol1("JobService0TSleep: OK DTIME = " + dTime);
- lastTimePooling = System.currentTimeMillis();
- String jobType = "tsleep";
- // if (CurrentUserSession.getGID() != null) {
- // if (CurrentUserSession.getGID().equals("1")) {
- //
- //
- // Log.d(TAG, "Đã vào lấy file");
- //
- //
- // String list_file_send_pos[] = null;
- // //*Bước 5: Đọc danh sách file và Gửi server
- // //đến bước này trong thư mục send có ít nhất 1 file là position hiện tại
- //
- // if (folderSendPos != null) {
- // if (cfile.fileExist(folderSendPos))
- // list_file_send_pos = cfile.ls(folderSendPos);
- // else
- // Log.d(TAG, "Đường dẫn file không tồn tại");
- // } else {
- // if (cfile.fileExist("/send_position"))
- // list_file_send_pos = cfile.ls("/send_position");
- // else
- // Log.d(TAG, "Đường dẫn file không tồn tại");
- // }
- // arrayList_file_send_pos = new ArrayList<String>(); // trong ds có nhiều file, file nào cần gửi thì sẽ cho vào đây để sau xóa
- //
- // if (folderLogPos != null)
- // file_tmp_upload = folderLogPos + "/tmp_send_data.txt";
- // else
- // file_tmp_upload = "/log_position" + "/tmp_send_data.txt";
- // // lấy được ds file cho vào biến,
- //
- // int total_files = 0;
- // if (list_file_send_pos != null) {
- // total_files = list_file_send_pos.length;
- // Log.d(TAG, "total files: " + total_files);
- // }
- // if (list_file_send_pos != null && total_files > 0) {
- // Log.d(TAG, "Có " + total_files + " vị trí chưa gửi lên server.");
- // cfile.ol1("Có " + total_files + " vị trí chưa gửi lên server.");
- //
- // if (cfile.fileExist(file_tmp_upload))
- // cfile.deleteFile(file_tmp_upload); //xóa nội dung file tạm để tạo dữ liệu cho lần upload mới.
- //
- // for (int j = 0; j < total_files; j++) {
- // if (j >= 10000) {//cho giới hạn 10k file, tổng size khoảng 400kb, tương ứng lưu trữ 24h với 10s ghi 1 file (VD app taxi).
- // ctool.ol1("Có nhiều hơn 10,000 file chưa gửi, gửi trước 10,000 file.");
- // break;
- // }
- //
- // if (list_file_send_pos[j].contains(CurrentUserSession.getUserId() + "_")) {
- // // đúng file của user này thì mới lấy nội dung
- // String c = cfile.file_get_content(list_file_send_pos[j]);
- // if (c.length() > 0) {
- // c = c.replace("\n", "");
- // if (!cfile.output(c, file_tmp_upload)) {
- // break;
- // }
- // arrayList_file_send_pos.add(list_file_send_pos[j]);
- // }
- // }
- // }
- // } else {
- // Log.d(TAG, "Chưa lấy được file...!");
- // }
- // }
- //
- // }
- try {
- //Lấy thông tin xác thực cho giao dịch từ Session User hiện tại
- if (!jsonObj.getSessionAuth(null)) {
- Log.d(TAG, " Chua login nen ko gui position");
- return;
- }
- } catch (Exception e) {
- ctool.logError(e);
- }
- //Tạo đối tượng json cho giao dịch, và encode đối tượng ra chuỗi json:
- Gson gSon = new Gson();
- String strGson = gSon.toJson(jsonObj);
- //Mã hóa thành chuỗi hexa
- Log.d(TAG, "gsonJobService0TSleep" + strGson);
- String strGsonHex = ctool.STH(strGson.getBytes());
- //URL giao tiếp Webserver:
- final String url = SettingGlobal.API_URL + "&update_position=" + strGsonHex;
- Log.d(TAG, "url: " + url);
- // String url = "http://" + SettingGlobal.APP_DOMAIN + "/tool/api_app/check_alarm_call.html?time=" + System.currentTimeMillis() + "&serial_device=" + serialDevice + "&dtime=" + dTime + "&jobType=" + jobType;
- String response = "";
- /////////////////
- //Thực hiện task:
- long deltaTime = JobSetting.checkDoTask(vn.net.lad.taxi.driver.service.JobService0TSleep.this);
- if (deltaTime > 0) {
- ctool.ol1("Do task - " + jobType + " / deltaTime = " + deltaTime);
- try {
- // if (CurrentUserSession.getGID().equals("1") && cfile.fileExist(file_tmp_upload)) {
- // response = new UploadFileAsync().execute(file_tmp_upload, url).get();
- // } else
- response = cfile.DownloadHtml(url, 0, 0);
- // login background để đồng bộ lại dữ liệu
- Help.tryLoginBackground(getApplicationContext(), true);
- if (response != null) {
- Log.d(TAG, "response=" + response);
- ReturnApi returnApi = null;
- try {
- returnApi = new ReturnApi(response);
- if (returnApi != null) {
- if (returnApi.value != null) {
- if (returnApi.value.equals("-1")) {
- ctool.logError(" Het han phien lam viec ! ");
- CurrentUserSession.deleteSessionTokenExpired(getSharedPreferences(SharedPref.name, MODE_PRIVATE));
- CurrentUserSession.setCheckLoginOnline(-1);
- } else if (returnApi.value.equals("1")) {
- // if (CurrentUserSession.getGID() != null) {
- // if (CurrentUserSession.getGID().equals("1")) {
- //
- // Log.d(TAG, "Đã truyền được file đi ...!");
- //
- // //ghi nội dung hiện tại vào log trước vì nó vẫn còn trên biến
- // String file_log = CurrentUserSession.getUserId() + "_" + cDateTime.nowy(0);
- //// // làm việc với các file cũ
- //// ctool.ol1("RunGet_UploadPosition: Upload Position OK, " + arrayList_file_send_pos.size() + " local files.");
- //
- // if (arrayList_file_send_pos.size() > 0) {
- //
- // // xử lý ghi log & xóa file đã send
- // for (int k = 0; k < arrayList_file_send_pos.size(); k++) {
- // String pFile = arrayList_file_send_pos.get(k);
- // String c = cfile.file_get_content(pFile);
- // if (c != null && c.length() > 0) {
- // c = c.replace("\n", "");
- //
- // if (folderLogPos != null) {
- // if (cfile.output(c, folderLogPos + "/" + file_log))// ghi file log
- // {
- // cfile.deleteFile(pFile);
- // } else
- // ctool.ol1("RunGet_UploadPosition:: Ghi log FAIL: " + pFile);
- // } else {
- // if (cfile.output(c, "/log_position" + "/" + file_log))// ghi file log
- // {
- // cfile.deleteFile(pFile);
- // } else
- // ctool.ol1("RunGet_UploadPosition:: Ghi log FAIL: " + pFile);
- // }
- // }
- // }
- //
- //
- // } // không có file thì ko làm gì
- // //xóa file tạm
- // if (cfile.fileExist(file_tmp_upload))
- // cfile.deleteFile(file_tmp_upload);
- // }
- // }
- Log.d(TAG, returnApi.info);
- Log.d(TAG, returnApi.info.replace("\"", ""));
- // Gán giá trị status cho current Session
- CurrentUserSession.setStatus(returnApi.info.replace("\"", ""));
- } else if (returnApi.value.equals("0")) {
- ctool.logError(" Co loi lay vi tri xay ra: " + returnApi.info);
- } else {
- ctool.logError(" Gia tri tra lai khong xac dinh: " + response);
- }
- Intent broadcastIntent = new Intent();
- broadcastIntent.setAction(SettingGlobal.PROCESS_POSITION_SERVICE);
- broadcastIntent.addCategory(Intent.CATEGORY_APP_MAPS);
- sendBroadcast(broadcastIntent);
- } else {
- Log.d(TAG, "Server chưa trả về đúng kiểu giá trị (-1, 0, 1, 2)");
- ctool.logError(TAG + ": Server chưa trả về đúng kiểu giá trị (-1, 0, 1, 2)");
- }
- } else {
- Log.d(TAG, "Chưa nhận được dữ liệu khi request tới server");
- ctool.logError(TAG + ": Chưa nhận được dữ liệu khi request tới server");
- }
- } catch (Exception e) {
- //Đưa ra log lỗi
- ctool.logError(e.getMessage());
- }
- } else {
- Log.e(TAG, "Có lỗi chưa nhận được phản hồi từ server(Polling 1 phút / 1 lần)");
- ctool.logError(TAG + ": Có lỗi chưa nhận được phản hồi từ server(Polling 1 phút / 1 lần)");
- }
- } catch (IOException e) {
- ctool.logError(e);
- }
- // ctool.ol1("JobService0TSleep, ret = " + response);
- } else
- ctool.ol1("Not need do task - " + jobType);
- } else {
- Log.d(TAG, "Không polling được tới server, do chưa lấy được vị trí hiện tại");
- }
- } catch (Exception e) {
- e.printStackTrace();
- ctool.logError(e);
- }
- }
- // try {
- // Thread.sleep(60000);
- // } catch (InterruptedException e) {
- // e.printStackTrace();
- // ctool.logError(e);
- // }
- // }
- }
- }
- @Override
- public void onLocationChanged(Location location) {
- }
- @Override
- public void onStatusChanged(String provider, int status, Bundle extras) {
- }
- @Override
- public void onProviderEnabled(String provider) {
- }
- @Override
- public void onProviderDisabled(String provider) {
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement