Advertisement
Guest User

Untitled

a guest
Mar 22nd, 2017
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 24.50 KB | None | 0 0
  1. // Lệnh gọi service trong service của firebase
  2.  
  3. // Thực hiện gọi service polling
  4.                     if (!Help.isServiceRunning(JobService0TSleep.class, this)) {
  5.                         Log.d(TAG, "Chạy service polling vị trí");
  6.                         Intent intent = new Intent(this, JobService0TSleep.class);
  7.                         this.startService(intent);
  8.                         Log.d(TAG, "Đã chạy service polling vị trí thành công");
  9.                     } else {
  10.                         Log.d(TAG, "Service polling vị trí đang chạy");
  11.                     }
  12.  
  13.  
  14. // File service
  15.  
  16. package vn.net.lad.taxi.driver.service;
  17.  
  18. import android.app.IntentService;
  19. import android.content.Intent;
  20. import android.location.Location;
  21. import android.location.LocationListener;
  22. import android.location.LocationManager;
  23. import android.os.Bundle;
  24. import android.os.IBinder;
  25. import android.util.Log;
  26. import android.widget.Toast;
  27.  
  28. import com.google.gson.Gson;
  29.  
  30. import java.io.IOException;
  31. import java.util.ArrayList;
  32.  
  33. import vn.net.lad.taxi.driver.CurrentUserSession;
  34. import vn.net.lad.taxi.driver.SettingGlobal;
  35. import vn.net.lad.taxi.driver.SharedPref;
  36. import vn.net.lad.taxi.driver.lib_app.jsonPositionGps;
  37. import vn.net.lad.taxi.driver.lib_base.Help;
  38. import vn.net.lad.taxi.driver.lib_base.ReturnApi;
  39. import vn.net.lad.taxi.driver.lib_base.UploadFileAsync;
  40. import vn.net.lad.taxi.driver.lib_base.Utils;
  41. import vn.net.lad.taxi.driver.lib_base.cDateTime;
  42. import vn.net.lad.taxi.driver.lib_base.cfile;
  43. import vn.net.lad.taxi.driver.lib_base.ctool;
  44. import vn.net.lad.taxi.driver.service.JobSetting;
  45.  
  46. public class JobService0TSleep extends IntentService implements LocationListener {
  47.  
  48.     private final String TAG = "JobService0TSleep";
  49.  
  50.     public static final String RESPONSE_DATA = "data";
  51.  
  52.     //    khai báo vị trí
  53.     private Location myLocation;
  54.  
  55.     // flag for GPS status
  56.     boolean isGPSEnabled = false;
  57.  
  58.     // flag for network status
  59.     boolean isNetworkEnabled = false;
  60.  
  61.     // flag for GPS status
  62.     boolean canGetLocation = false;
  63.  
  64. //    double latitude; // latitude
  65. //    double longitude; // longitude
  66.  
  67.     // The minimum distance to change Updates in meters
  68.     private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
  69.  
  70.     // The minimum time between updates in milliseconds
  71.     private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
  72.  
  73.     //    Declare time pooling
  74.  
  75.     static int countLoop = 0;
  76.  
  77.     static String folderSendPos, folderLogPos, file_tmp_upload;
  78.     ArrayList<String> arrayList_file_send_pos;
  79.  
  80.  
  81.     // Declaring a Location Manager
  82.     protected LocationManager locationManager;
  83.  
  84.     public JobService0TSleep() {
  85.         super("PositionUpdateService");
  86.  
  87.         folderSendPos = SettingGlobal.getSendPositionPath();
  88.         folderLogPos = SettingGlobal.getLogPositionPath();
  89.         if (!cfile.fileExist(folderSendPos))
  90.             cfile.mkdir(folderSendPos);
  91.  
  92.         if (!cfile.fileExist(folderLogPos))
  93.             cfile.mkdir(folderLogPos);
  94.     }
  95.  
  96.     private jsonPositionGps getPos() {
  97.  
  98.         jsonPositionGps jsonPositionGps = new jsonPositionGps();
  99.  
  100.         try {
  101.             locationManager = (LocationManager) getApplicationContext()
  102.                     .getSystemService(LOCATION_SERVICE);
  103.  
  104.             // getting GPS status
  105.             isGPSEnabled = locationManager
  106.                     .isProviderEnabled(LocationManager.GPS_PROVIDER);
  107.  
  108.             // getting network status
  109.             isNetworkEnabled = locationManager
  110.                     .isProviderEnabled(LocationManager.NETWORK_PROVIDER);
  111.  
  112.             if (!isGPSEnabled && !isNetworkEnabled) {
  113.                 Log.d(TAG, "Chưa xác định được vị trí hiện tại");
  114.             } else {
  115.                 this.canGetLocation = true;
  116.                 // if GPS Enabled get lat/long using GPS Services
  117.                 if (isGPSEnabled) {
  118.                     locationManager.requestLocationUpdates(
  119.                             LocationManager.GPS_PROVIDER,
  120.                             MIN_TIME_BW_UPDATES,
  121.                             MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
  122.                     Log.d(TAG, "GPS Enabled");
  123.                     if (locationManager != null) {
  124.                         myLocation = locationManager
  125.                                 .getLastKnownLocation(LocationManager.GPS_PROVIDER);
  126.                     }
  127.                 }
  128. //
  129.                 // get location from Network Provider
  130.                 if (isNetworkEnabled) {
  131.                     if (myLocation == null) {
  132.                         locationManager.requestLocationUpdates(
  133.                                 LocationManager.NETWORK_PROVIDER,
  134.                                 MIN_TIME_BW_UPDATES,
  135.                                 MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
  136.                         Log.d(TAG, "Network");
  137.                         if (locationManager != null) {
  138.                             myLocation = locationManager
  139.                                     .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
  140.                         }
  141.                     }
  142.                 }
  143.  
  144.             }
  145.  
  146.         } catch (Exception e) {
  147.             e.printStackTrace();
  148.         }
  149.  
  150.  
  151.         if (myLocation == null) {
  152.             //showDialogInfo("Thông báo", "Bạn chưa bật vị trí");
  153.             Toast.makeText(getApplicationContext(), "Chưa lấy được vị trí hiện tại", Toast.LENGTH_SHORT).show();
  154.             return null;
  155.         } else {
  156.  
  157.  
  158. //            ctool.ol1(myLocation.getLatitude() + " - " + myLocation.getLongitude());
  159.  
  160.             Log.d(TAG, myLocation.getLatitude() + " - " + myLocation.getLongitude());
  161.  
  162.             jsonPositionGps.lat_position = myLocation.getLatitude() + "";
  163.             jsonPositionGps.lng_position = myLocation.getLongitude() + "";
  164.             jsonPositionGps.radius = SettingGlobal.RADIUS + "";
  165. //            jsonPositionGps.get_near = 1;
  166.             jsonPositionGps.option_get_status = "1";
  167.             jsonPositionGps.userid_number = CurrentUserSession.getUserId();
  168.             return jsonPositionGps;
  169.         }
  170.     }
  171.  
  172.  
  173.     @Override
  174.     public IBinder onBind(Intent intent) {
  175.         // TODO: Return the communication channel to the service.
  176.         throw new UnsupportedOperationException("Not yet implemented");
  177.     }
  178.  
  179.     @Override
  180.     protected void onHandleIntent(Intent intent) {
  181.  
  182.         cfile.ol1("JobService0TSleep: onHandleIntent ");
  183.  
  184.         long lastTimePooling = 0, dTime;
  185.         if (intent != null) {
  186. //            while (true) {
  187.  
  188. //                Log.d(TAG, "countLoop: " + countLoop);
  189. //                if (countLoop > 0) {
  190. //                    try {
  191. //                        Thread.sleep(60000);
  192. //                    } catch (InterruptedException e) {
  193. //                        e.printStackTrace();
  194. //                    }
  195. //
  196. //                }
  197.  
  198. //                try {
  199. //                    Thread.sleep(1000);
  200. //                } catch (InterruptedException e) {
  201. //                    e.printStackTrace();
  202. //                }
  203.  
  204.  
  205.             if (!Utils.isOnline(this)) {
  206.                 Log.d(TAG, "Không có mạng?");
  207. //                    ctool.logError("Không có mạng ? ");
  208.                 return;
  209.             } else {
  210.  
  211.                 try {
  212.  
  213.                     //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
  214.                     if (!CurrentUserSession.isLogined()) {
  215. //                            CurrentUserSession.currentUserSession = SharedPref.getUserInfoInSharePref(getSharedPreferences(SharedPref.name, MODE_PRIVATE));
  216.                         CurrentUserSession.initInstance(SharedPref.getUserInfoInSharePref(getSharedPreferences(SharedPref.name, MODE_PRIVATE)));
  217.                         if (CurrentUserSession.getSessionToken() != null && CurrentUserSession.getSessionToken().length() > 0)
  218.                             CurrentUserSession.checkLoginOnline = 1;
  219.  
  220.                     }
  221.  
  222.                     // Thực hiện kết thúc chuyến đi
  223.                     String id_item = SharedPref.getIdItem(getSharedPreferences(SharedPref.s_id_item, MODE_PRIVATE));
  224.                     if (!SettingGlobal.isStopWithInternet && id_item != null) {
  225.                         Log.d(TAG, "Thực hiện kết thúc chuyến đi.");
  226.                         Log.d(TAG, "id_item: " + id_item);
  227.                         Help.replyDriverFinish(getApplicationContext(), id_item, "", "", "", "1");
  228.                     }
  229.  
  230. //      khởi tạo giá trị cho lớp jsonPositionGps để gán giá trị đầu vào
  231.                     jsonPositionGps jsonObj = new jsonPositionGps();
  232.                     jsonObj = getPos();
  233.  
  234.                     if (jsonObj != null) {
  235.  
  236.  
  237.                         ctool.ol1("=== TSleep: count = " + countLoop++);
  238.  
  239.                         dTime = (System.currentTimeMillis() - lastTimePooling) / 1000;
  240.  
  241.                         if (lastTimePooling > 0)
  242.                             if (dTime > 10 * JobSetting.delayTime) {
  243.                                 ctool.ol1(" *********************");
  244.                                 ctool.ol1(" ***** JobService0TSleep: ERROR DTIME = " + dTime);
  245.                                 ctool.ol1(" *********************");
  246.                             } else
  247.                                 ctool.ol1("JobService0TSleep: OK DTIME = " + dTime);
  248.  
  249.                         lastTimePooling = System.currentTimeMillis();
  250.  
  251.                         String jobType = "tsleep";
  252.  
  253.  
  254. //                            if (CurrentUserSession.getGID() != null) {
  255. //                                if (CurrentUserSession.getGID().equals("1")) {
  256. //
  257. //
  258. //                                    Log.d(TAG, "Đã vào lấy file");
  259. //
  260. //
  261. //                                    String list_file_send_pos[] = null;
  262. //                                    //*Bước 5: Đọc danh sách file và Gửi server
  263. //                                    //đến bước này trong thư mục send có ít nhất 1 file là position hiện tại
  264. //
  265. //                                    if (folderSendPos != null) {
  266. //                                        if (cfile.fileExist(folderSendPos))
  267. //                                            list_file_send_pos = cfile.ls(folderSendPos);
  268. //                                        else
  269. //                                            Log.d(TAG, "Đường dẫn file không tồn tại");
  270. //                                    } else {
  271. //                                        if (cfile.fileExist("/send_position"))
  272. //                                            list_file_send_pos = cfile.ls("/send_position");
  273. //                                        else
  274. //                                            Log.d(TAG, "Đường dẫn file không tồn tại");
  275. //                                    }
  276. //                                    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
  277. //
  278. //                                    if (folderLogPos != null)
  279. //                                        file_tmp_upload = folderLogPos + "/tmp_send_data.txt";
  280. //                                    else
  281. //                                        file_tmp_upload = "/log_position" + "/tmp_send_data.txt";
  282. //                                    // lấy được ds file cho vào biến,
  283. //
  284. //                                    int total_files = 0;
  285. //                                    if (list_file_send_pos != null) {
  286. //                                        total_files = list_file_send_pos.length;
  287. //                                        Log.d(TAG, "total files: " + total_files);
  288. //                                    }
  289. //                                    if (list_file_send_pos != null && total_files > 0) {
  290. //                                        Log.d(TAG, "Có " + total_files + " vị trí chưa gửi lên server.");
  291. //                                        cfile.ol1("Có " + total_files + " vị trí chưa gửi lên server.");
  292. //
  293. //                                        if (cfile.fileExist(file_tmp_upload))
  294. //                                            cfile.deleteFile(file_tmp_upload); //xóa nội dung file tạm để tạo dữ liệu cho lần upload mới.
  295. //
  296. //                                        for (int j = 0; j < total_files; j++) {
  297. //                                            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).
  298. //                                                ctool.ol1("Có nhiều hơn 10,000 file chưa gửi, gửi trước 10,000 file.");
  299. //                                                break;
  300. //                                            }
  301. //
  302. //                                            if (list_file_send_pos[j].contains(CurrentUserSession.getUserId() + "_")) {
  303. //                                                // đúng file của user này thì mới lấy nội dung
  304. //                                                String c = cfile.file_get_content(list_file_send_pos[j]);
  305. //                                                if (c.length() > 0) {
  306. //                                                    c = c.replace("\n", "");
  307. //                                                    if (!cfile.output(c, file_tmp_upload)) {
  308. //                                                        break;
  309. //                                                    }
  310. //                                                    arrayList_file_send_pos.add(list_file_send_pos[j]);
  311. //                                                }
  312. //                                            }
  313. //                                        }
  314. //                                    } else {
  315. //                                        Log.d(TAG, "Chưa lấy được file...!");
  316. //                                    }
  317. //                                }
  318. //
  319. //                            }
  320.  
  321.                         try {
  322.                             //Lấy thông tin xác thực cho giao dịch từ Session User hiện tại
  323.                             if (!jsonObj.getSessionAuth(null)) {
  324.                                 Log.d(TAG, " Chua login nen ko gui position");
  325.                                 return;
  326.                             }
  327.                         } catch (Exception e) {
  328.                             ctool.logError(e);
  329.                         }
  330.  
  331.                         //Tạo đối tượng json cho giao dịch, và encode đối tượng ra chuỗi json:
  332.                         Gson gSon = new Gson();
  333.                         String strGson = gSon.toJson(jsonObj);
  334.                         //Mã hóa thành chuỗi hexa
  335.                         Log.d(TAG, "gsonJobService0TSleep" + strGson);
  336.                         String strGsonHex = ctool.STH(strGson.getBytes());
  337.  
  338.                         //URL giao tiếp Webserver:
  339.                         final String url = SettingGlobal.API_URL + "&update_position=" + strGsonHex;
  340.  
  341.                         Log.d(TAG, "url: " + url);
  342.  
  343.  
  344. //                                String url = "http://" + SettingGlobal.APP_DOMAIN + "/tool/api_app/check_alarm_call.html?time=" + System.currentTimeMillis() + "&serial_device=" + serialDevice + "&dtime=" + dTime + "&jobType=" + jobType;
  345.                         String response = "";
  346.  
  347.                         /////////////////
  348.                         //Thực hiện task:
  349.                         long deltaTime = JobSetting.checkDoTask(vn.net.lad.taxi.driver.service.JobService0TSleep.this);
  350.                         if (deltaTime > 0) {
  351.                             ctool.ol1("Do task - " + jobType + " / deltaTime = " + deltaTime);
  352.                             try {
  353.  
  354. //                                    if (CurrentUserSession.getGID().equals("1") && cfile.fileExist(file_tmp_upload)) {
  355. //                                        response = new UploadFileAsync().execute(file_tmp_upload, url).get();
  356. //                                    } else
  357.  
  358.                                 response = cfile.DownloadHtml(url, 0, 0);
  359.                                 // login background để đồng bộ lại dữ liệu
  360.                                 Help.tryLoginBackground(getApplicationContext(), true);
  361.  
  362.  
  363.                                 if (response != null) {
  364.                                     Log.d(TAG, "response=" + response);
  365.  
  366.                                     ReturnApi returnApi = null;
  367.                                     try {
  368.                                         returnApi = new ReturnApi(response);
  369.                                         if (returnApi != null) {
  370.                                             if (returnApi.value != null) {
  371.                                                 if (returnApi.value.equals("-1")) {
  372.                                                     ctool.logError(" Het han phien lam viec ! ");
  373.                                                     CurrentUserSession.deleteSessionTokenExpired(getSharedPreferences(SharedPref.name, MODE_PRIVATE));
  374.                                                     CurrentUserSession.setCheckLoginOnline(-1);
  375.  
  376.                                                 } else if (returnApi.value.equals("1")) {
  377. //                                                if (CurrentUserSession.getGID() != null) {
  378. //                                                    if (CurrentUserSession.getGID().equals("1")) {
  379. //
  380. //                                                        Log.d(TAG, "Đã truyền được file đi ...!");
  381. //
  382. //                                                        //ghi nội dung hiện tại vào log trước vì nó vẫn còn trên biến
  383. //                                                        String file_log = CurrentUserSession.getUserId() + "_" + cDateTime.nowy(0);
  384. ////                                            // làm việc với các file cũ
  385. ////                                            ctool.ol1("RunGet_UploadPosition: Upload Position OK, " + arrayList_file_send_pos.size() + " local files.");
  386. //
  387. //                                                        if (arrayList_file_send_pos.size() > 0) {
  388. //
  389. //                                                            // xử lý ghi log & xóa file đã send
  390. //                                                            for (int k = 0; k < arrayList_file_send_pos.size(); k++) {
  391. //                                                                String pFile = arrayList_file_send_pos.get(k);
  392. //                                                                String c = cfile.file_get_content(pFile);
  393. //                                                                if (c != null && c.length() > 0) {
  394. //                                                                    c = c.replace("\n", "");
  395. //
  396. //                                                                    if (folderLogPos != null) {
  397. //                                                                        if (cfile.output(c, folderLogPos + "/" + file_log))// ghi file log
  398. //                                                                        {
  399. //                                                                            cfile.deleteFile(pFile);
  400. //                                                                        } else
  401. //                                                                            ctool.ol1("RunGet_UploadPosition:: Ghi log FAIL: " + pFile);
  402. //                                                                    } else {
  403. //                                                                        if (cfile.output(c, "/log_position" + "/" + file_log))// ghi file log
  404. //                                                                        {
  405. //                                                                            cfile.deleteFile(pFile);
  406. //                                                                        } else
  407. //                                                                            ctool.ol1("RunGet_UploadPosition:: Ghi log FAIL: " + pFile);
  408. //                                                                    }
  409. //                                                                }
  410. //                                                            }
  411. //
  412. //
  413. //                                                        } // không có file thì ko làm gì
  414. //                                                        //xóa file tạm
  415. //                                                        if (cfile.fileExist(file_tmp_upload))
  416. //                                                            cfile.deleteFile(file_tmp_upload);
  417. //                                                    }
  418. //                                                }
  419.  
  420.                                                     Log.d(TAG, returnApi.info);
  421.                                                     Log.d(TAG, returnApi.info.replace("\"", ""));
  422.  
  423. //                            Gán giá trị status cho current Session
  424.                                                     CurrentUserSession.setStatus(returnApi.info.replace("\"", ""));
  425.  
  426.                                                 } else if (returnApi.value.equals("0")) {
  427.                                                     ctool.logError(" Co loi lay vi tri xay ra: " + returnApi.info);
  428.                                                 } else {
  429.                                                     ctool.logError(" Gia tri tra lai khong xac dinh: " + response);
  430.                                                 }
  431.  
  432.                                                 Intent broadcastIntent = new Intent();
  433.                                                 broadcastIntent.setAction(SettingGlobal.PROCESS_POSITION_SERVICE);
  434.                                                 broadcastIntent.addCategory(Intent.CATEGORY_APP_MAPS);
  435.                                                 sendBroadcast(broadcastIntent);
  436.                                             } else {
  437.                                                 Log.d(TAG, "Server chưa trả về đúng kiểu giá trị (-1, 0, 1, 2)");
  438.                                                 ctool.logError(TAG + ": Server chưa trả về đúng kiểu giá trị (-1, 0, 1, 2)");
  439.                                             }
  440.                                         } else {
  441.                                             Log.d(TAG, "Chưa nhận được dữ liệu khi request tới server");
  442.                                             ctool.logError(TAG + ": Chưa nhận được dữ liệu khi request tới server");
  443.  
  444.                                         }
  445.                                     } catch (Exception e) {
  446.                                         //Đưa ra log lỗi
  447.                                         ctool.logError(e.getMessage());
  448.                                     }
  449.  
  450.                                 } else {
  451.                                     Log.e(TAG, "Có lỗi chưa nhận được phản hồi từ server(Polling 1 phút / 1 lần)");
  452.                                     ctool.logError(TAG + ": Có lỗi chưa nhận được phản hồi từ server(Polling 1 phút / 1 lần)");
  453.                                 }
  454.  
  455.                             } catch (IOException e) {
  456.                                 ctool.logError(e);
  457.                             }
  458. //                                ctool.ol1("JobService0TSleep, ret = " + response);
  459.                         } else
  460.                             ctool.ol1("Not need do task - " + jobType);
  461.  
  462.                     } else {
  463.                         Log.d(TAG, "Không polling được tới server, do chưa lấy được vị trí hiện tại");
  464.                     }
  465.  
  466.                 } catch (Exception e) {
  467.                     e.printStackTrace();
  468.                     ctool.logError(e);
  469.                 }
  470.  
  471.             }
  472.  
  473.  
  474. //                try {
  475. //                    Thread.sleep(60000);
  476. //                } catch (InterruptedException e) {
  477. //                    e.printStackTrace();
  478. //                    ctool.logError(e);
  479. //                }
  480.  
  481. //            }
  482.         }
  483.     }
  484.  
  485.  
  486.     @Override
  487.     public void onLocationChanged(Location location) {
  488.  
  489.     }
  490.  
  491.     @Override
  492.     public void onStatusChanged(String provider, int status, Bundle extras) {
  493.  
  494.     }
  495.  
  496.     @Override
  497.     public void onProviderEnabled(String provider) {
  498.  
  499.     }
  500.  
  501.     @Override
  502.     public void onProviderDisabled(String provider) {
  503.  
  504.     }
  505.  
  506.  
  507. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement