Commit 02686eaf by cuiliang.shi

okhttp 网络优化

1 parent ed730052
...@@ -29,7 +29,7 @@ ...@@ -29,7 +29,7 @@
</value> </value>
</option> </option>
</component> </component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_1_7" project-jdk-name="JDK" project-jdk-type="JavaSDK"> <component name="ProjectRootManager" version="2" languageLevel="JDK_1_8" project-jdk-name="1.8" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/build/classes" /> <output url="file://$PROJECT_DIR$/build/classes" />
</component> </component>
<component name="ProjectType"> <component name="ProjectType">
......
...@@ -6,8 +6,8 @@ android { ...@@ -6,8 +6,8 @@ android {
applicationId "com.agenew.location_server.application" applicationId "com.agenew.location_server.application"
minSdkVersion 23 minSdkVersion 23
targetSdkVersion 28 targetSdkVersion 28
versionCode 5 versionCode 6
versionName "1.5" versionName "1.6"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
} }
buildTypes { buildTypes {
...@@ -27,6 +27,9 @@ android { ...@@ -27,6 +27,9 @@ android {
sourceCompatibility JavaVersion.VERSION_1_8 sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8 targetCompatibility JavaVersion.VERSION_1_8
} }
lintOptions {
abortOnError false
}
} }
dependencies { dependencies {
......
...@@ -62,6 +62,14 @@ ...@@ -62,6 +62,14 @@
android:exported="true"> android:exported="true">
</service> </service>
<receiver android:name="com.agenew.location_server.application.AlarmReceiver"></receiver> <receiver android:name="com.agenew.location_server.application.AlarmReceiver"></receiver>
<!-- <receiver android:name=".BirdService$NetWorkChangReceiver" >
<intent-filter>
<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.wifi.STATE_CHANGE" />
</intent-filter>
</receiver>-->
</application> </application>
</manifest> </manifest>
\ No newline at end of file
...@@ -7,14 +7,19 @@ import android.app.NotificationChannel; ...@@ -7,14 +7,19 @@ import android.app.NotificationChannel;
import android.app.NotificationManager; import android.app.NotificationManager;
import android.app.PendingIntent; import android.app.PendingIntent;
import android.app.Service; import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Context;
import android.content.Intent; import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color; import android.graphics.Color;
import android.location.GpsSatellite; import android.location.GpsSatellite;
import android.location.GpsStatus; import android.location.GpsStatus;
import android.location.Location; import android.location.Location;
import android.location.LocationListener; import android.location.LocationListener;
import android.location.LocationManager; import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build; import android.os.Build;
import android.os.Bundle; import android.os.Bundle;
import android.os.Handler; import android.os.Handler;
...@@ -81,6 +86,7 @@ public class BirdService extends Service { ...@@ -81,6 +86,7 @@ public class BirdService extends Service {
private double mWifiLongitude = 0; private double mWifiLongitude = 0;
private double mGpsLatitude = 0; private double mGpsLatitude = 0;
private double mGpsLongitude = 0; private double mGpsLongitude = 0;
private boolean mHasSendTheLocationInfo = false;
@Override @Override
public IBinder onBind(Intent intent) { public IBinder onBind(Intent intent) {
...@@ -91,10 +97,19 @@ public class BirdService extends Service { ...@@ -91,10 +97,19 @@ public class BirdService extends Service {
public void onCreate() { public void onCreate() {
super.onCreate(); super.onCreate();
} }
private NetWorkChangReceiver netWorkChangReceiver;
private boolean isRegistered = false;
@Override @Override
public int onStartCommand(Intent intent, int flags, int startId) { public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand"); Log.d(TAG, "onStartCommand");
if (netWorkChangReceiver !=null){
unregisterReceiver(netWorkChangReceiver);
}
mWifiAvailableErrorCount = 0;
mNetworkAvailableErrorCount = 0;
mLocationCount = 0;
mErrorCount = 0;
mContext = getApplicationContext(); mContext = getApplicationContext();
...@@ -111,6 +126,7 @@ public class BirdService extends Service { ...@@ -111,6 +126,7 @@ public class BirdService extends Service {
+ ", cfgv: " + ret_cfgv + ", path: " + mPath); + ", cfgv: " + ret_cfgv + ", path: " + mPath);
searchGPS(); searchGPS();
IotApi.init();
mHandler.sendEmptyMessageDelayed(0, 1000); mHandler.sendEmptyMessageDelayed(0, 1000);
return super.onStartCommand(intent, flags, startId); return super.onStartCommand(intent, flags, startId);
...@@ -129,12 +145,26 @@ public class BirdService extends Service { ...@@ -129,12 +145,26 @@ public class BirdService extends Service {
private float mAccuracy = 10000; private float mAccuracy = 10000;
private float mWifiAccuracy = 1000; private float mWifiAccuracy = 1000;
private float mGpsAccuracy = 1000; private float mGpsAccuracy = 1000;
private int mWifiAvailableErrorCount = 0;
private int mNetworkAvailableErrorCount = 0;
public AMapLocationListener mLocationListener = new AMapLocationListener() { public AMapLocationListener mLocationListener = new AMapLocationListener() {
@Override @Override
public void onLocationChanged(AMapLocation amapLocation) { public void onLocationChanged(AMapLocation amapLocation) {
Log.d(TAG, "onLocationChanged"); Log.d(TAG, "onLocationChanged");
if (!PhoneUtils.isWifiAvailable(getApplicationContext()) && mWifiAvailableErrorCount < 4){
mWifiAvailableErrorCount++;
Log.d(TAG, "wifi not available");
return;
}
if (!PhoneUtils.isNetwork(getApplicationContext()) && mNetworkAvailableErrorCount < 4){
mNetworkAvailableErrorCount++;
Log.d(TAG, "network not available");
return;
}
if (amapLocation != null) { if (amapLocation != null) {
if (amapLocation.getErrorCode() == 0) { if (amapLocation.getErrorCode() == 0) {
mLocationCount++; mLocationCount++;
...@@ -195,6 +225,7 @@ public class BirdService extends Service { ...@@ -195,6 +225,7 @@ public class BirdService extends Service {
SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); SimpleDateFormat dateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
mStartTime = dateformat.format(System.currentTimeMillis()); mStartTime = dateformat.format(System.currentTimeMillis());
mStartTime = mStartTime.replace(" ", "%");
if (mLocationClient != null) { if (mLocationClient != null) {
mLocationClient.stopLocation(); mLocationClient.stopLocation();
} }
...@@ -220,14 +251,10 @@ public class BirdService extends Service { ...@@ -220,14 +251,10 @@ public class BirdService extends Service {
}; };
private void handlerGpsError() { private void handlerGpsError() {
Log.d(TAG, "handlerGpsError");
mErrorCount++; mErrorCount++;
if (mErrorCount > 6){ if (mErrorCount > 6){
setAlarm(); setAlarm();
// close gps & network.
Intent intent = new Intent("com.bird.close_gps_switch");
intent.addFlags(0x01000000);
getApplicationContext().sendBroadcast(intent);
} }
} }
...@@ -250,11 +277,32 @@ public class BirdService extends Service { ...@@ -250,11 +277,32 @@ public class BirdService extends Service {
manger.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pendingIntent2); manger.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtTime, pendingIntent2);
} }
if (!mHasSendTheLocationInfo){
setNetworkListener();
return;
}
stopForeground(true); stopForeground(true);
Log.d(TAG, "time:" + new Date().toString()); Log.d(TAG, "time:" + new Date().toString());
stopSelf(); stopSelf();
} }
private void setNetworkListener() {
mLocationManager.removeUpdates(mLocListener);
mLocationManager.removeGpsStatusListener(mGpsListener);
mLocationClient.stopLocation();
// network listener
netWorkChangReceiver = new NetWorkChangReceiver();
IntentFilter filter = new IntentFilter();
filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
registerReceiver(netWorkChangReceiver, filter);
isRegistered = true;
}
private int mErrorCount = 0; private int mErrorCount = 0;
@SuppressLint("HandlerLeak") @SuppressLint("HandlerLeak")
private Handler mErrorHandler = new Handler(){ private Handler mErrorHandler = new Handler(){
...@@ -283,10 +331,26 @@ public class BirdService extends Service { ...@@ -283,10 +331,26 @@ public class BirdService extends Service {
} }
Log.d(TAG, "url: " + mPath + ", jsonBody: " + jsonBody.toString()); Log.d(TAG, "url: " + mPath + ", jsonBody: " + jsonBody.toString());
IotApi.post(mPath, jsonBody.toString() , new IotNetApiCallback() { /* StringBuilder strbuf = new StringBuilder();
strbuf.append("longitude=" + mLongitude);
strbuf.append("&latitude=" + mLatitude);
strbuf.append("&time=" + mStartTime);
strbuf.append("&meid=" + mIMEIStr);
strbuf.append("&tel=" + mMobile);
strbuf.append("&iccid=" + mICCIDStr);
strbuf.append("&imsi=" + mIMSIStr);
strbuf.append("&model=" + mModel);
strbuf.append("&cfgv=" + ret_cfgv);
strbuf.append("&gcs=" + "GCJ02");
Log.d(TAG, "REQUEST: URL: " + mPath + ", BODY:" + strbuf);
IotApi.get(mPath + "?" + strbuf.toString(), new IotNetApiCallback(){*/
IotApi.postLocationInfo(mPath, jsonBody , new IotNetApiCallback() {
@Override @Override
public void onSuccess(String response) { public void onSuccess(String response) {
Log.d(TAG, "server response: " + response); Log.d(TAG, "server response: " + response);
mHasSendTheLocationInfo = true;
JsonObject resp = new JsonParser().parse(response).getAsJsonObject(); JsonObject resp = new JsonParser().parse(response).getAsJsonObject();
ret_code = resp.get("ret_code").getAsInt(); ret_code = resp.get("ret_code").getAsInt();
...@@ -327,18 +391,14 @@ public class BirdService extends Service { ...@@ -327,18 +391,14 @@ public class BirdService extends Service {
@Override @Override
public void onFailed(Exception e) { public void onFailed(Exception e) {
Log.d(TAG, "Exception:" + e.toString()); Log.d(TAG, "Exception:" + e.toString());
mErrorCount++; setAlarm();
/*mErrorCount++;
if (mErrorCount > 5){ if (mErrorCount > 5){
setAlarm(); setAlarm();
// close gps & network.
Intent intent = new Intent("com.bird.close_gps_switch");
intent.addFlags(0x01000000);
getApplicationContext().sendBroadcast(intent);
}else{ }else{
long temp = DevicePreferences.getInstance(mContext).getLong("bird_location_upload_interval", DEFAULTINTERVAL); long temp = DevicePreferences.getInstance(mContext).getLong("bird_location_upload_interval", DEFAULTINTERVAL);
mErrorHandler.sendEmptyMessageDelayed(0, temp); mErrorHandler.sendEmptyMessageDelayed(0, temp);
} }*/
} }
}); });
} }
...@@ -394,6 +454,9 @@ public class BirdService extends Service { ...@@ -394,6 +454,9 @@ public class BirdService extends Service {
mLocationManager.removeUpdates(mLocListener); mLocationManager.removeUpdates(mLocListener);
mLocationManager.removeGpsStatusListener(mGpsListener); mLocationManager.removeGpsStatusListener(mGpsListener);
if (isRegistered) {
unregisterReceiver(netWorkChangReceiver);
}
super.onDestroy(); super.onDestroy();
Log.d(TAG, "onDestory"); Log.d(TAG, "onDestory");
} }
...@@ -504,5 +567,65 @@ public class BirdService extends Service { ...@@ -504,5 +567,65 @@ public class BirdService extends Service {
} }
} }
public class NetWorkChangReceiver extends BroadcastReceiver {
private String getConnectionType(int type) {
String connType = "";
if (type == ConnectivityManager.TYPE_MOBILE) {
connType = "3G NETWORK";
} else if (type == ConnectivityManager.TYPE_WIFI) {
connType = "WIFI NETWORK";
}
return connType;
}
@Override
public void onReceive(Context context, Intent intent) {
if (WifiManager.WIFI_STATE_CHANGED_ACTION.equals(intent.getAction())) {
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, 0);
Log.e("TAG", "wifiState:" + wifiState);
switch (wifiState) {
case WifiManager.WIFI_STATE_DISABLED:
break;
case WifiManager.WIFI_STATE_DISABLING:
break;
}
}
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
NetworkInfo info = intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (info != null) {
//
if (NetworkInfo.State.CONNECTED == info.getState() && info.isAvailable()) {
if (info.getType() == ConnectivityManager.TYPE_WIFI || info.getType() == ConnectivityManager.TYPE_MOBILE) {
Log.i("TAG", getConnectionType(info.getType()) + " CONNECTED");
startTheLocationTask();
}
} else {
Log.i("TAG", getConnectionType(info.getType()) + " DISCONNECTED");
}
}
}
}
}
private void startTheLocationTask() {
// open gps & network.
Intent intent2 = new Intent("com.bird.open_gps_switch");
intent2.addFlags(0x01000000);
sendBroadcast(intent2);
ret_cfgv = DevicePreferences.getInstance(getApplicationContext()).getString("bird_ret_cfgv", "2019031512");
mPath = DevicePreferences.getInstance(mContext).getString("bird_location_upload_url", DEFAULTPATH);
long temp = DevicePreferences.getInstance(mContext).getLong("bird_location_upload_interval", DEFAULTINTERVAL);
Log.d(TAG, "CONFIG - PARAM, time minutes: " + temp
+ ", cfgv: " + ret_cfgv + ", path: " + mPath);
searchGPS();
IotApi.init();
mHandler.sendEmptyMessageDelayed(0, 1000);
}
} }
...@@ -4,6 +4,7 @@ import android.content.Context; ...@@ -4,6 +4,7 @@ import android.content.Context;
import android.content.pm.PackageManager; import android.content.pm.PackageManager;
import android.net.ConnectivityManager; import android.net.ConnectivityManager;
import android.net.NetworkInfo; import android.net.NetworkInfo;
import android.net.wifi.WifiManager;
import android.os.Build; import android.os.Build;
import android.provider.Settings; import android.provider.Settings;
import android.telephony.SubscriptionInfo; import android.telephony.SubscriptionInfo;
...@@ -156,6 +157,15 @@ public class PhoneUtils { ...@@ -156,6 +157,15 @@ public class PhoneUtils {
return false; return false;
} }
static boolean isWifiAvailable(Context contxt) {
WifiManager wifiManager = (WifiManager) contxt.getSystemService(Context.WIFI_SERVICE);
return wifiManager.isWifiEnabled();
/* ConnectivityManager connectivityManager = (ConnectivityManager) contxt.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = connectivityManager.getActiveNetworkInfo();
return (networkInfo != null && networkInfo.isConnected() && networkInfo
.getType() == ConnectivityManager.TYPE_WIFI);*/
}
public static void setDefaultDataSub(SubscriptionManager subscriptionManager, int slotId) { public static void setDefaultDataSub(SubscriptionManager subscriptionManager, int slotId) {
try { try {
Method method = subscriptionManager.getClass().getMethod("setDefaultDataSubId", int.class); Method method = subscriptionManager.getClass().getMethod("setDefaultDataSubId", int.class);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!