我正面临在Android应用程序中连续与服务器交互的错误

时间:2016-10-13 08:57:10

标签: android

我已经制作了一个运行良好的应用程序,它不断向服务器发送用户lat,以及与服务器的其他一些交互(如配置文件图像,名称,朋友列表以及从服务器显示的所有内容)。但问题是,当应用程序处于后台/用户使用其他应用程序进行phonecall / user时,我的应用程序将断开其连接并且用户退出从服务器检索的服务(所有服务都取决于用户在登录期间获得的用户ID)。我试图解决这个问题,就像我的应用程序将永远是好的,并与其服务器活动进行交互,没有任何错误或中断,例如Facebook应用程序。如何使我的网络连接和管理行为像facebook或whatsApp应用程序。 检查图像。第一个是应用程序交互良好(配置文件名称和图片),第二个是错误(没有配置文件名称和图片),例如。

我的asyncTaskClass:

public class GetPostAsyncTaskWithInterface extends AsyncTask<String, Void, String> {

    public AsyncResult asyncResult;
//    HttpURLConnection httpURLConnection;

    ProgressDialog progressDialog;
    private final String baseUrl = UserInfo.getSiteUrl();

    public Context context=null;


    GetPostAsyncTaskWithInterface(Context context,AsyncResult asyncResult) {

        this.context=context;
        this.asyncResult= asyncResult;
    }

    @Override
    protected void onPreExecute() {
        //Toast.makeText(context,"Loading..",Toast.LENGTH_SHORT).show();
        progressDialog=new ProgressDialog(context);
        progressDialog.show();

    }

    @Override
    protected String doInBackground(String... args) {

        try {
            // setting the URL
            URL url = new URL(baseUrl+args[1]);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();

            // setting the method type
            httpURLConnection.setRequestMethod(args[0]);
//                httpURLConnection.setChunkedStreamingMode(0);
            httpURLConnection.setDoInput(true);
            httpURLConnection.setDoOutput(true);
            OutputStream outputStream = httpURLConnection.getOutputStream();
            BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(outputStream, "UTF-8"));

            Log.v("Url", args[2]);
            // setting the identification key name with query params
            bufferedWriter.write(args[2]);
            bufferedWriter.flush();
            bufferedWriter.close();

            Log.v("GetPostA", url.toString());

            httpURLConnection.setReadTimeout(10*1000);
            httpURLConnection.setConnectTimeout(15000 );

            httpURLConnection.connect();
            int getPostStatus = httpURLConnection.getResponseCode();

            Log.v("GetPostSts", String.valueOf(getPostStatus));


            String line = "";
            String res = "";
//                if(getPostStatus == 200){

            // prepare the output buffer
            InputStream inputStream = httpURLConnection.getInputStream();
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

            while ((line = bufferedReader.readLine()) != null) {

                res += line;

            }

            inputStream.close();

//                }

            httpURLConnection.disconnect();

//                Log.v("ResD", res.toString());
            return res.toString();

        } catch (MalformedURLException e) {

            e.printStackTrace();
            Log.v("GetPostCatchMal",e.toString());

        } catch (IOException e) {

            e.printStackTrace();
            Log.v("GetPostCatchIOE", e.toString());

        }

        return null;

    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }


    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);

        if(progressDialog.isShowing()){
            try{
                progressDialog.dismiss();
            }catch (Exception e){

            }
        }
        if(result!=null) {
            asyncResult.asyncResult(result);
        }

    }

}

我的活动类就像:

      @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_navigation_drawer);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);
        context = NavigationDrawerActivity.this;

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);
        View hView = navigationView.getHeaderView(0);


        ownProfilePic = (ImageView) hView.findViewById(R.id.ownImageShowDrawerHeaderIvId_navigationDrawer);
        ownNameShow = (TextView) hView.findViewById(R.id.showUserNameTvId_navigationDrawer);

        /******************************   own profile name and image show **************************  */

        ownNameShow.setText(UserInfo.getOwnProfileName());
//        new ImageDownloaderTask(ownProfilePic).execute(UserInfo.ownProfilePicUrl);
        Picasso.with(context).load(UserInfo.getOwnProfilePicUrl()).resize(100,100).placeholder(R.drawable.profile_show).error(R.drawable.profile_show).transform(new CircleTransform()).into(ownProfilePic);

        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        this.lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

        Criteria criteria=new Criteria();
        provider =lm.getBestProvider(criteria,false);
        location = this.lm.getLastKnownLocation(provider);
        this.locationListener = new NavigationDrawerActivity();
        this.lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 5, locationListener);


        if (location != null) {
            setUpMapIfNeeded(location);
            updateUserLatLong(location);

        }
        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.

        client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).addApi(LocationServices.API).build();

        //route
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }
    // option menu.......................option menu,.,
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.

        getMenuInflater().inflate(R.menu.navigation_drawer_option_menu, menu);
        return true;
    }


    @Override
    protected void onResume() {
        super.onResume();
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;

        }
        Location location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if (location != null) {
            setUpMapIfNeeded(location);
        }

    }


    @Override
    public void onMapReady(GoogleMap googleMap) {

        mMap = googleMap;

        mMap.setMyLocationEnabled(true);
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            return;
        }
        Location location = this.lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        Log.v("DangerNotification","locN M"+location);
        if (location != null) {
            setUpMapIfNeeded(location);

            UserInfo.setLat(location.getLatitude());
            UserInfo.setLng(location.getLongitude());
            UserInfo.setLocation(location);
        }
        //setUpMapIfNeeded(location);

        mMap.setOnInfoWindowClickListener(new GoogleMap.OnInfoWindowClickListener() {
            @Override
            public void onInfoWindowClick(Marker marker) {

                Intent intent = new Intent(context, Live_MapActivity.class);
                intent.putExtra("Driver", "anyFriend");

                UserInfo.setFriendsId(friendIds.optString(marker.getId()));
                startActivity(intent);

                Toast.makeText(context, "You tracking " + marker.getTitle(), Toast.LENGTH_LONG).show();

            }
        });
    }


    @Override
    public void onLocationChanged(Location location) {

        Log.v("DangerNotification", "locN " + location);

        if (location != null && SharedPreference.getDefaults("ownUserId", context) != "0") {

            updateUserLatLong(location);
            //setUpMapIfNeeded(location);
            float speed = location.getSpeed();
            UserInfo.setSpeed(speed);

            UserInfo.setLat(location.getLatitude());
            UserInfo.setLng(location.getLongitude());
            UserInfo.setLocation(location);
        }
        userPosition = new LatLng(location.getLatitude(),
                location.getLongitude());

        if (mMap != null) {
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userPosition,
                    12));
            mMap.setMapType(UserInfo.getMapType());
        }
    }


    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {

    }

    @Override
    public void onProviderEnabled(String provider) {
        boolean gps_enabled = false;
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }
        if (gps_enabled) {
            Toast.makeText(context, "Gps enabled", Toast.LENGTH_LONG).show();

        }
    }

    @Override
    public void onProviderDisabled(String provider) {

          /* *********************************************  Gps checking **********************************************************   */

        boolean gps_enabled = false;
        LocationManager lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        try {
            gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }
        if (!gps_enabled) {

            Toast.makeText(context, "Gps Disable", Toast.LENGTH_LONG).show();

        }

            /* ************************************************************************************************************ */

    }


    private void setUpMapIfNeeded(Location location) {

        //updateUserLatLong(location);


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }

//        Criteria criteria = new Criteria();
//        criteria.setAccuracy(Criteria.ACCURACY_COARSE);

        LatLng userPosition = new LatLng(location.getLatitude(),
                location.getLongitude());

        if (mMap != null) {
            mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(userPosition,
                    UserInfo.getZoomLevel()));

            mMap.setMapType(UserInfo.getMapType());

            userFriendsPos();

        }
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

            mMap.setMyLocationEnabled(true);
        }
    }


    @Override
    public void onStart() {
        super.onStart();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        client.connect();
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Maps Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,
                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.
                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.tracker.systechdigital.realtimetrackingandmonitoring/http/host/path")
        );
        AppIndex.AppIndexApi.start(client, viewAction);
    }


    @Override
    public void onStop() {
        super.onStop();

        // ATTENTION: This was auto-generated to implement the App Indexing API.
        // See https://g.co/AppIndexing/AndroidStudio for more information.
        Action viewAction = Action.newAction(
                Action.TYPE_VIEW, // TODO: choose an action type.
                "Maps Page", // TODO: Define a title for the content shown.
                // TODO: If you have web page content that matches this app activity's content,

                // make sure this auto-generated web page URL is correct.
                // Otherwise, set the URL to null.

                Uri.parse("http://host/path"),
                // TODO: Make sure this auto-generated app deep link URI is correct.
                Uri.parse("android-app://com.tracker.systechdigital.realtimetrackingandmonitoring/http/host/path")
        );
        AppIndex.AppIndexApi.end(client, viewAction);
        client.disconnect();
    }




    @Override
    public void onConnected(Bundle bundle) {


        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        location = LocationServices.FusedLocationApi.getLastLocation(
                client);


    }

    @Override
    public void onConnectionSuspended(int i) {

    }

    @Override
    public void asyncResult(String result) {

    }



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

    @Override
    protected void onPostResume() {
        super.onPostResume();
    }

    @Override
    protected void onRestart() {
        super.onRestart();

        ownNameShow.setText(UserInfo.getOwnProfileName());
//        new ImageDownloaderTask(ownProfilePic).execute(UserInfo.ownProfilePicUrl);
        Picasso.with(context).load(UserInfo.getOwnProfilePicUrl()).resize(100,100).placeholder(R.drawable.profile_show).error(R.drawable.profile_show).transform(new CircleTransform()).into(ownProfilePic);

        if (location != null) {
            setUpMapIfNeeded(location);
            updateUserLatLong(location);

        }
    }


}

请帮忙。 enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

AsyncTasks不是为此而设计的。它们主要用于需要一到两秒钟的任务。它们也可能导致很多问题。例如,对于您的代码示例,您在onPostExecute中更新UI,这可能导致NullPointerExceptions,您的Activity的内存泄漏。所以尽量避免使用它。

我建议你使用背景Service

服务是在后台继续运行并具有更好性能的组件,对您的案例非常有用。

您还可以观看Google Android Performance Tutorials Here