Invalid Host Id Ошибка канала связи Последний пакет, успешно отправленный на сервер, был 0 миллисекунд назад - PullRequest
0 голосов
/ 04 мая 2020

enter image description here Пожалуйста, помогите мне, как решить эту ошибку с объяснением !!! Здравствуйте, ребята, я использую mariaDB имеет базу данных, и я использую ее в android приложении: это мои файлы:

1) Постоянный файл: содержит localHost, имя пользователя и пароль для mariaDB

 package com.drivertracking.utils;

 import android.location.Location;


 public class Constants {
 public static String BASE_URL = "https://bodyweightsecrets.app/trackingDrivers/api/";
 public static int READ_TIMEOUT = 50000;
 //Dev
 //    public static String DRIVER_NAME = "com.mysql.jdbc.Driver";
 //    public static String USERNAME = "doriath";
 //    public static String PASSWORD = "doriath586";
 //    public static String PORT = "5000";
 //    public static String DATABASE_NAME = "elfosmobiletrans_00001";
 //    public static String HOST_NAME = "192.168.100.20";
 //    private static String JDBC_PATH = "jdbc:mysql://" + HOST_NAME + ":" + PORT + "/" + 
       DATABASE_NAME;
 //    public static String GPS_TABLE_NAME = "mt_gmapsactual";
 //    public static String GPS_DETAIL_TABLE_NAME = "mt_gmapsactual_historico";
 //Live
 public static String DRIVER_NAME = "com.mysql.jdbc.Driver";
 public static String USERNAME = "root";
 public static String PASSWORD = "doriath586";
 public static String PORT = "3306";
 public static String DATABASE_NAME = "elfosmobiletrans_00001";
 public static String HOST_NAME = "127.0.0.1";
 private static String JDBC_PATH = "jdbc:mysql://" + HOST_NAME + ":" + PORT + "/" + DATABASE_NAME;
 public static String GPS_TABLE_NAME = "mt_gmapsactual";
 public static String GPS_DETAIL_TABLE_NAME = "mt_gmapsactual_historico";

 public static String IS_NOTIFY = "IS_NOTIFY";
 public static String LAST_LOCATION_PREF = "LAST_LOCATION_PREF";
 public static String NAME_PREF = "NAME_PREF";
 public static String HOST_ID_PREF = "HOST_ID";
 public static String DRIVER_ID_PREF = "DRIVER_ID";

 public static String DISCONNECT = "DISCONNECT";
 public static String CONNECT = "CONNECT";


 public static String LOCATION_UPDATE = "LOCATION_UPDATE";
 public static Location lastLoc;

 public final int UNKNOWN = -1;
 public final int ERROR = 0;
 public final int SUCCESS = 1;

 public static String getJDBC(String hostName) {
    JDBC_PATH = "jdbc:mysql://" + hostName + ":" + PORT + "/" + DATABASE_NAME;

    return JDBC_PATH;
}
}

Это мой файл активности: Файл активности аутентифицируется и устанавливает соединение с БД

package com.drivertracking.views;

import android.Manifest;
import android.app.Activity;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.app.NotificationCompat;
import androidx.core.content.ContextCompat;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.drivertracking.LocationUpdatesService;
import com.drivertracking.R;
import com.drivertracking.model.LocationStruct;
import com.drivertracking.services.GPSTracker;
import com.drivertracking.utils.Constants;
import com.drivertracking.utils.Methods;
import com.drivertracking.utils.PrefManager;
import com.drivertracking.utils.RuntimePermissions;
import com.drivertracking.utils.SingletonClass;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.location.LocationRequest;
import com.google.gson.Gson;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import static com.drivertracking.utils.Constants.DRIVER_ID_PREF;
import static com.drivertracking.utils.Constants.HOST_ID_PREF;
import static com.drivertracking.utils.Constants.IS_NOTIFY;
import static com.drivertracking.utils.Constants.NAME_PREF;
import static com.drivertracking.utils.RuntimePermissions.REQUEST_CHECK_SETTINGS;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Activity mAct = MainActivity.this;
    private SingletonClass singleton;

    private EditText hostIdET;
    private EditText driverIdET;
    private EditText nameET;

    private Button connectBT;
    private TextView startTV, titleTV;
    private LinearLayout startStoptLL;
    private LinearLayout bottomLL;

    private GPSTracker gpsTracker;
    private LocationRequest mLocationRequest;
    private static final int ALARM_REQUEST_CODE = 133;
    private static final long LOCATION_UPDATE_INTERVAL = 30000;
    private static final long LOCATION_FASTEST_UPDATE_INTERVAL = LOCATION_UPDATE_INTERVAL / 2;

    public final int REQ_ID_MULTIPLE_PERMISSIONS = 1;

    private String NOTIFICATION_CHANNEL_ID = "CHANEL_ID111";
    public static final String JOB_STATE_CHANGED = "jobStateChanged";
    public static final String LOCATION_ACQUIRED = "locAcquired";

    private boolean exitByMe = false;
    private Connection connection = null;
    private ProgressDialog pd;

    //New Location Service Data
    private static final String TAG = MainActivity.class.getSimpleName();
    private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
    private MyReceiver myReceiver;
    private LocationUpdatesService mService = null;
    private boolean mBound = false;

    private final ServiceConnection mServiceConnection = new ServiceConnection() {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            LocationUpdatesService.LocalBinder binder = (LocationUpdatesService.LocalBinder) service;
            mService = binder.getService();
            mBound = true;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mService = null;
            mBound = false;
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);

        initViews();
    }

    private void initViews() {
        myReceiver = new MyReceiver();

        singleton = SingletonClass.getInstance();
        gpsTracker = new GPSTracker(mAct);
        startStoptLL = findViewById(R.id.startStoptLL);
        startTV = findViewById(R.id.startTV);
        titleTV = findViewById(R.id.titleTV);
        hostIdET = findViewById(R.id.hostIdET);
        driverIdET = findViewById(R.id.driverIdET);
        nameET = findViewById(R.id.nameET);
        connectBT = findViewById(R.id.connectBT);
        bottomLL = findViewById(R.id.bottomLL);

        startStoptLL.setOnClickListener(this);
        connectBT.setOnClickListener(this);
        titleTV.setOnClickListener(this);

        if (getSharedPreferences("track", MODE_PRIVATE).getBoolean("isServiceStarted", false)) {
            startTV.setText("STOP");
        } else {
            startTV.setText("START");
        }

        setData();
    }

    private void setData() {
        isDatabaseConnected(false, false);

        String hostID = PrefManager.getMyStringPref(mAct, singleton.HOST_ID_PREF, "");
        String driverID = PrefManager.getMyStringPref(mAct, singleton.DRIVER_ID_PREF, "");
        String nameStr = PrefManager.getMyStringPref(mAct, singleton.NAME_PREF, "");

        if (!hostID.equals("")) {
            Constants.HOST_NAME = hostID;
            nameET.setText(nameStr);
            hostIdET.setText(hostID);
            driverIdET.setText(driverID);

            makeDatabaseConnection();
        }
    }

    private void startCheckingPermissions() {
        if (checkPlayServices()) {
            checkAndRequestPermissions();
        } else {
            Methods.showDialog(mAct, "Alert", "Google play service not available in your tablet so you can't use location service.", "OK");
        }
    }

    public boolean checkPlayServices() {
        final int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;

        GoogleApiAvailability apiAvailability = GoogleApiAvailability.getInstance();
        int resultCode = apiAvailability.isGooglePlayServicesAvailable(mAct);

        if (resultCode != ConnectionResult.SUCCESS) {
            if (apiAvailability.isUserResolvableError(resultCode)) {
                apiAvailability.getErrorDialog(mAct, resultCode, PLAY_SERVICES_RESOLUTION_REQUEST).show();
            } else {
                Log.d("", "This device is not supported.");
            }

            return false;
        }

        return true;
    }

    private void checkAndRequestPermissions() {
        int locationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION);
        int accessCrossLocationPermission = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION);

        List<String> listPermissionsNeeded = new ArrayList<>();
        if (locationPermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_FINE_LOCATION);
        }
        if (accessCrossLocationPermission != PackageManager.PERMISSION_GRANTED) {
            listPermissionsNeeded.add(Manifest.permission.ACCESS_COARSE_LOCATION);
        }

        if (!listPermissionsNeeded.isEmpty()) {
            ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQ_ID_MULTIPLE_PERMISSIONS);
        } else if (gpsTracker.canGetLocation()) {
            checkAndStartService();
        } else {
            RuntimePermissions.displayLocationSettingsRequest(mAct);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case REQ_ID_MULTIPLE_PERMISSIONS: {
                Map<String, Integer> perms = new HashMap<>();
                perms.put(Manifest.permission.ACCESS_FINE_LOCATION, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.ACCESS_COARSE_LOCATION, PackageManager.PERMISSION_GRANTED);
                if (grantResults.length > 0) {
                    for (int i = 0; i < permissions.length; i++)
                        perms.put(permissions[i], grantResults[i]);
                    if (perms.get(Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED
                            && perms.get(Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
                        gpsTracker = new GPSTracker(mAct);
                        if (gpsTracker.canGetLocation()) {
                            checkAndStartService();
                        } else {
                            RuntimePermissions.displayLocationSettingsRequest(mAct);
                        }
                    } else {
                        Methods.showDialog(mAct, "Permission Denied!", "Please go to settings and enable permissions.", "OK");
                    }
                }
            }
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case REQUEST_CHECK_SETTINGS:
                switch (resultCode) {
                    case Activity.RESULT_OK:
                        checkAndStartService();
                        break;
                    case Activity.RESULT_CANCELED:
                        Methods.showDialog(mAct, "Alert", "You can't proceed without enabling Location. Please enable your location and login again.", "OK");
                        break;
                }
                break;
        }
    }

    private void checkAndStartService() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Log.d("registered", " on start service");
            startBackgroundService();
        } else {
            Toast.makeText(getBaseContext(), "Service for pre lollipop will be available in next update", Toast.LENGTH_LONG).show();
        }
    }


    private void startBackgroundService() {
        PrefManager.setMyBooleanPref(mAct, "ByMe", false);
        mService.requestLocationUpdates();

//        IntentFilter i = new IntentFilter(JOB_STATE_CHANGED);
//        i.addAction(LOCATION_ACQUIRED);
//
//        JobScheduler jobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
//        if (jobScheduler == null) throw new AssertionError();
//        jobScheduler.schedule(new JobInfo.Builder(LocationJobService.LOCATION_SERVICE_JOB_ID,
//                new ComponentName(this, LocationJobService.class))
//                .setOverrideDeadline(10 * 6000)
//                .setPersisted(true)
//                .setRequiresCharging(false)
//                .setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
//                .setRequiresDeviceIdle(false)
//                .build());

        finish();
//        showDialog();
    }

    private void stopBackgroundService() {
        PrefManager.setMyBooleanPref(mAct, "ByMe", true);

        if (getSharedPreferences("track", MODE_PRIVATE).getBoolean("isServiceStarted", false)) {
            startTV.setText("START");
            exitByMe = true;
            PrefManager.setMyBooleanPref(mAct, IS_NOTIFY, false);
            mService.removeLocationUpdates();

//            removeNotification();

//            getSharedPreferences("track", MODE_PRIVATE).edit().putBoolean("isServiceStarted", false).apply();
//
//            Intent stopJobService = null;
//            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
//                stopJobService = new Intent(LocationJobService.ACTION_STOP_JOB);
//                LocalBroadcastManager.getInstance(getBaseContext()).sendBroadcast(stopJobService);
//            } else {
//                Toast.makeText(getApplicationContext(), "yet to be coded - stop service", Toast.LENGTH_SHORT).show();
//            }
        }
    }

    private void showDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(mAct);
        builder.setTitle("Congratulations!");
        builder.setMessage("Tracking started successfully.");
        builder.setCancelable(true);

        builder.setPositiveButton(
                "OK",
                (dialog, id) -> {
                    finish();
                });


        AlertDialog alert = builder.create();
        alert.show();
    }

    @Override
    public void onClick(View view) {
        if (view.equals(startStoptLL)) {
            if (Methods.requestingLocationUpdates(mAct)) {
                stopBackgroundService();
            } else {
                startTV.setText("STOP");
                startCheckingPermissions();
            }
        } else if (view.equals(connectBT)) {
            if (connectBT.getText().equals(Constants.CONNECT)) {
                if (checkIsValid()) {
                    InputMethodManager imm = (InputMethodManager) getSystemService(Activity.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                    pd = ProgressDialog.show(mAct, "", "Connecting...", true);
                    connection = null;

                    new Handler().postDelayed(() -> {
                        makeDatabaseConnection();
                    }, 100);
                }
            } else {
                isDatabaseConnected(false, true);
                stopBackgroundService();
            }
        } else if (view.equals(titleTV)) {
            nameET.setText("Shahid");
            hostIdET.setText("192.168.100.24");
            driverIdET.setText("1");
        }
    }

    private boolean checkIsValid() {
        if (nameET.getText().toString().equals("")) {
            nameET.setError("");
            Toast.makeText(mAct, "Please enter your Name", Toast.LENGTH_SHORT).show();

            return false;
        } else if (hostIdET.getText().toString().equals("")) {
            hostIdET.setError("");
            Toast.makeText(mAct, "Please enter Host ID", Toast.LENGTH_SHORT).show();

            return false;
        } else if (!validateIP(hostIdET.getText().toString())) {
            hostIdET.setError("");
            Toast.makeText(mAct, "Please enter valid Host ID", Toast.LENGTH_SHORT).show();
        } else if (driverIdET.getText().toString().equals("")) {
            driverIdET.setError("");
            Toast.makeText(mAct, "Please enter your Driver ID", Toast.LENGTH_SHORT).show();

            return false;
        }

        Constants.HOST_NAME = hostIdET.getText().toString();

        return true;
    }

    public boolean validateIP(String ip) {
        String PATTERN = "^((0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)\\.){3}(0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)$";

        return ip.matches(PATTERN);
    }

    private void notifyByMe() {
        String msgStr = "";
        String lastLocationStr = PrefManager.getMyStringPref(mAct, singleton.LAST_LOCATION_PREF, "");
        if (!lastLocationStr.equals("")) {
            LocationStruct struct = new Gson().fromJson(lastLocationStr, LocationStruct.class);
            msgStr = "(" + struct.getLatitude() + ", " + struct.getLongitude() + ")";
        }

        showNotification(msgStr);
    }

    private void showNotification(String msgStr) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd MMM, yyyy hh:mm aa", Locale.getDefault());
        String formatStr = sdf.format(new Date());

        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("Location Updated : " + formatStr)
                .setAutoCancel(false)
                .setOngoing(true)
                .setContentText(msgStr);
        Intent notificationIntent = new Intent(this, SplashActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);
        // Add as notification
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
            NotificationChannel nChannel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, "NOTIFICATION_CHANNEL_NAME", NotificationManager.IMPORTANCE_HIGH);
            nChannel.enableLights(true);
            assert manager != null;
            builder.setChannelId(NOTIFICATION_CHANNEL_ID);
            manager.createNotificationChannel(nChannel);
        }
        assert manager != null;
        manager.notify(123321, builder.build());
    }

    private void removeNotification() {
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.cancel(123321);
    }

    private void makeDatabaseConnection() {
        if (connection == null) {
            try {
                Constants.HOST_NAME = hostIdET.getText().toString();
                Class.forName(Constants.DRIVER_NAME).newInstance();
                DriverManager.setLoginTimeout(20);

                connection = DriverManager.getConnection(singleton.getJDBC(Constants.HOST_NAME), Constants.USERNAME, Constants.PASSWORD);
                // Meta data
                DatabaseMetaData meta = connection.getMetaData();
                isDatabaseConnected(true, true);

                if (pd != null && pd.isShowing())
                    pd.dismiss();
            } catch (Exception e) {
                if (pd != null && pd.isShowing())
                    pd.dismiss();
                showDialog(e.getMessage());
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
        } else {
            if (pd != null && pd.isShowing())
                pd.dismiss();
            isDatabaseConnected(true, false);
        }
    }

    private void  isDatabaseConnected(boolean isConnected, boolean isResetValues) {
        if (isConnected) {
            hostIdET.setEnabled(false);
            driverIdET.setEnabled(false);
            nameET.setEnabled(false);

            connectBT.setText(Constants.DISCONNECT);
            bottomLL.setVisibility(View.VISIBLE);
        } else {
            if (isResetValues) {
                nameET.setText("");
                hostIdET.setText("");
                driverIdET.setText("");
            }

            hostIdET.setEnabled(true);
            driverIdET.setEnabled(true);
            nameET.setEnabled(true);

            connectBT.setVisibility(View.VISIBLE);
            bottomLL.setVisibility(View.INVISIBLE);

            connectBT.setText(Constants.CONNECT);
        }

        if (isResetValues) {
            PrefManager.setMyStringPref(mAct, NAME_PREF, nameET.getText().toString());
            PrefManager.setMyStringPref(mAct, HOST_ID_PREF, hostIdET.getText().toString());
            PrefManager.setMyStringPref(mAct, DRIVER_ID_PREF, driverIdET.getText().toString());
        }
    }

    private void showDialog(String msg) {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Invalid Host ID");
        builder.setMessage(msg)
                .setCancelable(false)
                .setPositiveButton("OK", (dialog, id) -> {
                    dialog.dismiss();
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    //New Functions
    @Override
    protected void onStart() {
        super.onStart();

        // Bind to the service. If the service is in foreground mode, this signals to the service
        // that since this activity is in the foreground, the service can exit foreground mode.
        bindService(new Intent(this, LocationUpdatesService.class), mServiceConnection,
                Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (!exitByMe || !getSharedPreferences("track", MODE_PRIVATE).getBoolean("isServiceStarted", false)) {
            PrefManager.setMyBooleanPref(mAct, IS_NOTIFY, false);
//            removeNotification();
        }

        LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver,
                new IntentFilter(LocationUpdatesService.ACTION_BROADCAST));
    }

    @Override
    protected void onPause() {
        if (getSharedPreferences("track", MODE_PRIVATE).getBoolean("isServiceStarted", false)) {
//            if (!exitByMe) {
//                notifyByMe();
//            }

            PrefManager.setMyBooleanPref(mAct, IS_NOTIFY, true);
        }

        LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
        super.onPause();
    }

    @Override
    protected void onStop() {
        if (mBound) {
            unbindService(mServiceConnection);
            mBound = false;
        }
        super.onStop();
    }

    private class MyReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            Location location = intent.getParcelableExtra(LocationUpdatesService.EXTRA_LOCATION);
            if (location != null) {
                Toast.makeText(MainActivity.this, Methods.getLocationText(location),
                        Toast.LENGTH_SHORT).show();
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...