Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/android/233.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 启动后台服务中的密集POST导致崩溃_Java_Android - Fatal编程技术网

Java 启动后台服务中的密集POST导致崩溃

Java 启动后台服务中的密集POST导致崩溃,java,android,Java,Android,因此,有一个后台服务,该服务在GPS位置更改后立即创建可运行的对象Runnable包含通过sendBroadcast()进行POST和两次发送广播消息的HTTPConnection 因此,如果没有机会通过此方案发送数据,我将面临的问题是发生了一些事情,应用程序崩溃。 当newTaskAsync准备就绪时,是否有重构代码或更改方法的线索,以TaskAsync和取消挂起TaskAsync 有线索吗 import android.app.Service; import android.content.

因此,有一个后台服务,该服务在GPS位置更改后立即创建可运行的对象
Runnable
包含通过
sendBroadcast()
进行POST和两次发送广播消息的
HTTPConnection

因此,如果没有机会通过此方案发送数据,我将面临的问题是发生了一些事情,应用程序崩溃。

当new
TaskAsync
准备就绪时,是否有重构代码或更改方法的线索,以
TaskAsync
取消挂起
TaskAsync

有线索吗

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.text.format.DateFormat;
import android.util.Log;

import com.google.gson.Gson;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Date;


public class gps_service2 extends Service {
    private static final String TAG = "GPS SERVICE";
    private LocationManager mLocationManager = null;
    private static final int LOCATION_INTERVAL = 10000;
    private static final float LOCATION_DISTANCE = 10f;
    Context context;

    private class LocationListener implements android.location.LocationListener
    {
        Location mLastLocation;

        public LocationListener(String provider)
        {
            Log.e(TAG, "LocationListener " + provider);
            mLastLocation = new Location(provider);
        }

        @Override
        public void onLocationChanged(Location location)
        {
            Log.e(TAG, "onLocationChanged: " + location);

            try
            {
                ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences(context, "App_Settings", 0);
                AppSettings appSettings = complexPreferences.getObject("App_Settings", AppSettings.class);
                if (appSettings != null) {

                    LocationItem locationItem = new LocationItem();
                    locationItem.DeviceID = appSettings.getDeviceID();
                    locationItem.Latitude =  Double.toString(location.getLatitude());
                    locationItem.Longitude = Double.toString(location.getLongitude());
                    Date d = new Date();
                    CharSequence timeOfRequest = DateFormat.format("yyyy-MM-dd HH:mm:ss", d.getTime()); // YYYY-MM-DD HH:mm:ss
                    locationItem.TimeOfRequest = timeOfRequest.toString();
                    locationItem.SerialNumber = appSettings.getSerialNumber();


                    Gson gson = new Gson();
                    String requestObject = gson.toJson(locationItem);
                    String url = appSettings.getIpAddress() + "/api/staff/savedata";
                    makeRequest(url, requestObject, dLocation);
                }
            }
            catch (Exception ex)
            {                
            } 
        }

        @Override
        public void onProviderDisabled(String provider)
        {
            Log.e(TAG, "onProviderDisabled: " + provider);
        }

        @Override
        public void onProviderEnabled(String provider)
        {
            Log.e(TAG, "onProviderEnabled: " + provider);
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras)
        {
            Log.e(TAG, "onStatusChanged: " + provider);
        }
    }

    LocationListener[] mLocationListeners = new LocationListener[] {
            new LocationListener(LocationManager.GPS_PROVIDER),
            new LocationListener(LocationManager.NETWORK_PROVIDER)
    };

    @Override
    public IBinder onBind(Intent arg0)
    {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        Log.e(TAG, "onStartCommand");
        super.onStartCommand(intent, flags, startId);
        return START_STICKY;
    }

    @Override
    public void onCreate()
    {
        context = this;
        Log.e(TAG, "onCreate");
        initializeLocationManager();
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[1]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "network provider does not exist, " + ex.getMessage());
        }
        try {
            mLocationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE,
                    mLocationListeners[0]);
        } catch (java.lang.SecurityException ex) {
            Log.i(TAG, "fail to request location update, ignore", ex);
        } catch (IllegalArgumentException ex) {
            Log.d(TAG, "gps provider does not exist " + ex.getMessage());
        }
    }

    @Override
    public void onDestroy()
    {
        Log.e(TAG, "onDestroy");
        super.onDestroy();
        if (mLocationManager != null) {
            for (int i = 0; i < mLocationListeners.length; i++) {
                try {
                    mLocationManager.removeUpdates(mLocationListeners[i]);
                } catch (Exception ex) {
                    Log.i(TAG, "fail to remove location listners, ignore", ex);
                }
            }
        }
    }

    private void initializeLocationManager() {
        Log.e(TAG, "initializeLocationManager");
        if (mLocationManager == null) {
            mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        }
    }

    public static double round(double value, int places) {
        if (places < 0) throw new IllegalArgumentException();
        BigDecimal bd = new BigDecimal(value);
        bd = bd.setScale(places, RoundingMode.HALF_UP);
        return bd.doubleValue();
    }

    public void makeRequest(String uri, String json, DLocation dLocation) {

        HandlerThread handlerThread = new HandlerThread("URLConnection");
        handlerThread.start();
        Handler mainHandler = new Handler(handlerThread.getLooper());
        Runnable myRunnable = createRunnable(uri, json, dLocation);
        mainHandler.post(myRunnable);
    }

    private Runnable createRunnable(final String uri, final String data,final DLocation dLocation){

        Runnable aRunnable = new Runnable(){
            public void run(){
                try {
                    //Connect
                    HttpURLConnection urlConnection;
                    urlConnection = (HttpURLConnection) ((new URL(uri).openConnection()));
                    urlConnection.setDoOutput(true);
                    urlConnection.setRequestProperty("Content-Type", "application/json");
                    urlConnection.setRequestProperty("Accept", "application/json");
                    urlConnection.setRequestMethod("POST");
                    urlConnection.connect();

                    //Write
                    OutputStream outputStream = urlConnection.getOutputStream();
                    BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));
                    try {
                        writer.write(data);
                    } catch (IOException e) {
                        e.printStackTrace();
                        Log.d(TAG,"Ошибка записи в буфер для пережачи по HTTP");
                    }
                    writer.close();
                    outputStream.close();

                    //Read
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(urlConnection.getInputStream(), "UTF-8"));

                    String line = null;
                    StringBuilder sb = new StringBuilder();

                    while ((line = bufferedReader.readLine()) != null) {
                        sb.append(line);
                    }

                    bufferedReader.close();
                    String result = sb.toString();

                    Log.d(TAG, result);

                    Intent iResult = new Intent("location_update");

                    DLocation dLocation = new DLocation();                    
                    iResult.putExtra("result", dLocation);
                    sendBroadcast(iResult);                   

                }catch( Exception err){
                    err.printStackTrace();
                    Log.d(TAG, "HTTP " + err.getMessage());
                }
            }
        };

        return aRunnable;
    }
}
导入android.app.Service;
导入android.content.Context;
导入android.content.Intent;
导入android.location.location;
导入android.location.LocationManager;
导入android.os.Bundle;
导入android.os.Handler;
导入android.os.HandlerThread;
导入android.os.IBinder;
导入android.text.format.DateFormat;
导入android.util.Log;
导入com.google.gson.gson;
导入java.io.BufferedReader;
导入java.io.BufferedWriter;
导入java.io.IOException;
导入java.io.InputStreamReader;
导入java.io.OutputStream;
导入java.io.OutputStreamWriter;
导入java.math.BigDecimal;
导入java.math.RoundingMode;
导入java.net.HttpURLConnection;
导入java.net.URL;
导入java.util.Date;
公共类gps_服务2扩展服务{
专用静态最终字符串TAG=“GPS服务”;
私有位置管理器mLocationManager=null;
专用静态最终整数位置\u间隔=10000;
专用静态最终浮动位置_距离=10f;
语境;
私有类LocationListener实现android.location.LocationListener
{
位置mLastLocation;
公共位置侦听器(字符串提供程序)
{
Log.e(标记“LocationListener”+提供者);
mLastLocation=新位置(提供商);
}
@凌驾
已更改位置上的公共无效(位置)
{
Log.e(标签“onLocationChanged:+位置);
尝试
{
ComplexPreferences ComplexPreferences=ComplexPreferences.getComplexPreferences(上下文,“应用程序设置”,0);
AppSettings-AppSettings=complexPreferences.getObject(“App\u Settings”,AppSettings.class);
if(appSettings!=null){
LocationItem LocationItem=新的LocationItem();
locationItem.DeviceID=appSettings.getDeviceID();
locationItem.Latitude=Double.toString(location.getLatitude());
locationItem.Longitude=Double.toString(location.getLongitude());
日期d=新日期();
CharSequence timeOfRequest=DateFormat.format(“yyyy-MM-dd HH:MM:ss”,d.getTime());//yyy-MM-dd HH:MM:ss
locationItem.TimeOfRequest=TimeOfRequest.toString();
locationItem.SerialNumber=appSettings.getSerialNumber();
Gson Gson=新的Gson();
字符串requestObject=gson.toJson(locationItem);
字符串url=appSettings.getIpAddress()+“/api/staff/savedata”;
makeRequest(url、requestObject、dLocation);
}
}
捕获(例外情况除外)
{                
} 
}
@凌驾
公共无效onProviderDisabled(字符串提供程序)
{
Log.e(标记“onProviderDisabled:+提供程序”);
}
@凌驾
公共无效onProviderEnabled(字符串提供程序)
{
Log.e(标记“onProviderEnabled:+提供程序”);
}
@凌驾
public void onStatusChanged(字符串提供程序、int状态、Bundle extra)
{
Log.e(标记“onStatusChanged:+提供者”);
}
}
LocationListener[]mlLocationListeners=新LocationListener[]{
新LocationListener(LocationManager.GPS_提供程序),
新LocationListener(LocationManager.NETWORK\u提供程序)
};
@凌驾
公共IBinder onBind(意图arg0)
{
返回null;
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId)
{
Log.e(标记“onStartCommand”);
super.onStartCommand(intent、flags、startId);
返回开始时间;
}
@凌驾
public void onCreate()
{
上下文=这个;
Log.e(标记为“onCreate”);
初始化ElocationManager();
试一试{
mLocationManager.RequestLocationUpdate(
LocationManager.NETWORK_提供程序、位置间隔、位置距离、,
mLocationListeners[1]);
}catch(java.lang.SecurityException ex){
Log.i(标记“无法请求位置更新,忽略”,例如);
}捕获(IllegalArgumentException ex){
Log.d(标记“网络提供商不存在”+ex.getMessage());
}
试一试{
mLocationManager.RequestLocationUpdate(
LocationManager.GPS\u提供程序、位置\u间隔、位置\u距离、,
mLocationListeners[0]);
}catch(java.lang.SecurityException ex){
Log.i(标记“无法请求位置更新,忽略”,例如);
}捕获(IllegalArgumentException ex){
Log.d(标记“gps提供程序不存在”+ex.getMessage());
}
}
@凌驾
公共空间
{
Log.e(标签“onDestroy”);
super.ondestory();
if(mLocationManager!=null){
for(int i=0;ipublic class WebService extends AsyncTask<String,String,String> {
private static final String TAG="SyncToServerTAG";




private String urlString;
private JSONObject jsonObject=null;
private int screenId=1;

public WebService(String url) {
    this.urlString=url;
}

public WebService(Context context, String url, JSONObject jsonObject) {
    this.urlString = url;
    this.jsonObject = jsonObject;
}

@Override
protected String doInBackground(String... strings) {
    try {
        URL url = new URL(urlString);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.setChunkedStreamingMode(0);
        urlConnection.setConnectTimeout(5000);
        urlConnection.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
        urlConnection.setDoOutput(true);
        urlConnection.setDoInput(true);
        urlConnection.setRequestMethod("POST");
        if(jsonObject!=null) {
            OutputStream os = urlConnection.getOutputStream();
            os.write(jsonObject.toString().getBytes("UTF-8"));
        }

        InputStream in = new BufferedInputStream(urlConnection.getInputStream());
        BufferedReader br = new BufferedReader(new InputStreamReader(
                (urlConnection.getInputStream())));

        String output="";
        while (true) {
            String line=br.readLine();
                Log.d(TAG,line+" ");
            if(line!=null)
                output+=line;
            else
                break;
        }

        in.close();
        urlConnection.disconnect();
        JSONObject j;
        if(output.equals(""))
            publishProgress("Server give null");
        else {
            j=new JSONObject(output);
            return output;
        }
        return output;
    } catch (MalformedURLException e) {
        e.printStackTrace();
        publishProgress(e.toString());
    } catch (IOException e) {
        e.printStackTrace();
        publishProgress(e.toString());
    } catch (JSONException e) {
        e.printStackTrace();
        publishProgress(e.toString());
    }
    return null;
}

@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    fireError(values[0]);
}

@Override
protected void onPostExecute(String s) {
    super.onPostExecute(s);
    if(s!=null) {
        try {
            JSONObject jsonObject=new JSONObject(s);
            fireComplete(0, jsonObject);
        } catch (JSONException e) {
            e.printStackTrace();
            fireError("Non acceptable responds from server ["+urlString+"]");
        }
    }
}

public interface OnWebCompleteListener{
    void onComplete(JSONObject result, int dataSource);
    void onError(String error);
}
private OnWebCompleteListener onWebCompleteListener;
private void fireComplete(int sourse,JSONObject cache){
    if(onWebCompleteListener!=null)
        onWebCompleteListener.onComplete(cache,sourse);
}
private void fireError(String message){
    if(onWebCompleteListener!=null)
        onWebCompleteListener.onError(message);
}
public void start(OnWebCompleteListener onWebCompleteListener){
    if(onWebCompleteListener==null)
        throw new RuntimeException("You must provide non-null value as start listener");
    this.onWebCompleteListener=onWebCompleteListener;
    execute((String)null);
}

}
    WebService webService=new WebService(context,"url",jsonObject);
    webService.start(new WebService.OnWebCompleteListener() {
    @Override
    public void onComplete(JSONObject result, int dataSource) {

    }

    @Override
    public void onError(String error) {

    }
    });