Я работаю над API матрицы расстояний на карте Google, который работает в режиме отладки, но не в режиме выпуска - PullRequest
0 голосов
/ 15 ноября 2018

Я работаю над API матрицы расстояний Google Map, который работает в режиме отладки, но не в режиме выпуска.Я попробовал каждый метод, упомянутый в сообщениях.Это мой Gradle

 apply plugin: 'com.android.application'

        android {
            compileSdkVersion 28
            buildToolsVersion '28.0.3'
            defaultConfig {
                applicationId ""
                minSdkVersion 15
                targetSdkVersion 28
                versionCode 1
                versionName "1.0"
                testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
                vectorDrawables.useSupportLibrary = true
                generatedDensities = []
            }

            aaptOptions {
                additionalParameters "--no-version-vectors"
            }

            sourceSets {
                main {
                    res.srcDirs =
                            [
                                    'src/main/res_splash',
                                    'src/main/res_login',
                                    'src/main/res_home',
                                    'src/main/res_orderDetail',
                                    'src/main/res_commission',
                                    'src/main/res_shared',
                                    'src/main/res'
                            ]
                }
            }

            signingConfigs {
                release {
                    storeFile file("C:\\Users\\Daksh\\AndroidStudioProjects\\kurosign.jks")
                    storePassword "123456"
                    keyAlias "Key0"
                    keyPassword "123456"
                    v2SigningEnabled true
                    v1SigningEnabled true
                }
            }

            buildTypes {
                release {
                    minifyEnabled true
                    proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
                    signingConfig signingConfigs.release
                    proguardFile 'C:/Users/Daksh/AndroidStudioProjects/MrFixTechnician/app/proguard-rules.pro'
                    debuggable true
                    jniDebuggable true
                    renderscriptDebuggable true
                    pseudoLocalesEnabled true
                    zipAlignEnabled true
                }
            }
        }

        dependencies {
            implementation 'com.google.firebase:firebase-core:11.0.4'
            compile fileTree(include: ['*.jar'], dir: 'libs')
            androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
                exclude group: 'com.android.support', module: 'support-annotations'
            })
            compile 'com.android.support:design:26.+'
            compile 'com.android.support:appcompat-v7:26.+'
            compile 'com.android.support.constraint:constraint-layout:1.0.2'
            compile 'com.google.android.gms:play-services-maps:11.0.4'
            compile 'com.google.android.gms:play-services-location:11.0.4'
            compile 'jp.wasabeef:picasso-transformations:2.1.0'
            compile 'com.squareup.picasso:picasso:2.5.0'
            compile 'com.squareup.retrofit2:retrofit:2.1.0'
            compile 'com.google.code.gson:gson:2.6.2'
            compile 'com.squareup.retrofit2:converter-gson:2.1.0'
            compile 'com.google.firebase:firebase-messaging:11.0.4'
            compile 'com.google.android.gms:play-services-places:11.0.4'
            compile project(':libraries:UniversalImageLoader-Library')
            testCompile 'junit:junit:4.12'
        }

        apply plugin: 'com.google.gms.google-services'

Мой файл манифеста

<?xml version="1.0" encoding="utf-8"?>

<uses-permission android:name="com.javapapers.currentlocationinmap.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="ANDROID.PERMISSION.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CALL_PHONE" />

<application
    android:name=".CustomGallery.MyApplication"
    android:allowBackup="false"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:hardwareAccelerated="true"
    android:largeHeap="true"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/Theme.AppCompat.Light.NoActionBar">
    <activity
        android:screenOrientation="portrait"
        android:name=".Splash.Splash">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity
        android:screenOrientation="portrait"
        android:name=".Login.LoginActivity"/>
    <activity
        android:screenOrientation="portrait"
        android:name=".Login.ForgotPassword"/>
    <activity
        android:screenOrientation="portrait"
        android:name=".Home.HomeActivity"/>

    <activity
        android:screenOrientation="portrait"
        android:name=".Detail.DetailActivity">
    <intent-filter>
        <!-- Intent filter action for receiving multiple images  -->
        <action android:name="android.intent.action.SEND_MULTIPLE" />
        <category android:name="android.intent.category.DEFAULT" />

        <!--  To receive Images set mime type to image -->
        <data android:mimeType="image/*" />
    </intent-filter>
    </activity>

    <activity
        android:screenOrientation="portrait"
        android:name=".OrderQuota.OrderQuotaActivity"/>
    <activity
        android:screenOrientation="portrait"
        android:name=".Commisions.CommisionActivity"/>

    <activity
        android:screenOrientation="portrait"
        android:name=".Home.CompletedOrdersActivity"/>

    <activity
        android:screenOrientation="portrait"
        android:name=".CustomGallery.CustomGallery_Activity"/>

    <meta-data
        android:name="com.google.android.gms.version"
        android:value="@integer/google_play_services_version" />

    <meta-data
        android:name="com.google.android.geo.API_KEY"
        android:value="@string/google_maps_key" />

    <service android:name=".Firebase.MyFirebaseMessagingService">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
        </intent-filter>
    </service>

    <service
        android:name=".Firebase.MyFirebaseInstanceIDService"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
        </intent-filter>
    </service>

    <service android:name=".Shared.MyLocationService"
        android:exported="false"/>

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="com.vysh.fullsizeimage.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths"></meta-data>
    </provider>

</application>

Это мой код для использования матрицы расстояний Google Map

public class OrderDetailFragment  extends Fragment implements View.OnClickListener,OnMapReadyCallback, LocationListener {

private View view;
private Fragment fragment;
private GoogleMap mMap;
private BitmapDescriptor icon;
private RecyclerView addressList;
private ImageView menu_icon, back_icon, footer_icon, start, call;
private final int REQUEST_FINE_LOCATION = 1234;
private LocationManager locationManager;
private Location mLastLocation;
private String provider;
private TextView heading, footer_txt, orderNo, orderType, orderTime, cName, cContact, techEmail, techJob, techName, pModel,
        pType,pProblem;
private TextView specialInst,timeDistance, txt_time;
private LinearLayout searchBox, footer, jobStatus, paymentDetail, compNameLay,p_type1,p_type2;
private TransparentProgressDialog pd;
private SharedPreference sharedPreference;
private APIInterface apiInterface,apiInterface1;
private int order_id;
private AddressListAdaper adapter;
private String contact;
private LatLng customerLatLng,techLatLng;
private double tLat, tLong, cLat, cLong;
private Marker marker;
private OrderDetailData orderDetailData;

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    view = inflater.inflate(R.layout.order_detail, container, false);

    Bundle bundle = this.getArguments();
    if (bundle != null) {
        orderDetailData = (OrderDetailData) bundle.getSerializable("data");
        order_id = bundle.getInt("order_id");
    }

    sharedPreference = new SharedPreference(getContext());
    apiInterface1 = APIClient.getClient3().create(APIInterface.class);
    apiInterface = APIClient.getClient().create(APIInterface.class);
    pd = new TransparentProgressDialog(getContext(), R.drawable.ic_app_loader);

    if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        ActivityCompat.requestPermissions(getActivity(), new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_FINE_LOCATION);

    timeDistance = view.findViewById(R.id.timeDistance);
    txt_time = view.findViewById(R.id.txt_time);
    pd.show();
    locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, this);
    Criteria criteria = new Criteria();
    provider = locationManager.getBestProvider(criteria, false);
    mLastLocation = locationManager.getLastKnownLocation(provider);

    menu_icon = getActivity().findViewById(R.id.menu_icon);
    back_icon = getActivity().findViewById(R.id.back_icon);
    heading = getActivity().findViewById(R.id.heading);
    searchBox = getActivity().findViewById(R.id.searchBox);

    footer = view.findViewById(R.id.footer);
    footer_icon = view.findViewById(R.id.footer_icon);
    footer_txt = view.findViewById(R.id.footer_txt);
    jobStatus = view.findViewById(R.id.jobStatus);
    paymentDetail = view.findViewById(R.id.paymentDetail);
    start = view.findViewById(R.id.start);
    call = view.findViewById(R.id.call);
    pProblem = view.findViewById(R.id.pProblem);

    addressList = view.findViewById(R.id.addressList);
    addressList.setLayoutManager(new LinearLayoutManager(getContext()));
    compNameLay = view.findViewById(R.id.compNameLay);
    orderNo = view.findViewById(R.id.orderNo);
    orderType = view.findViewById(R.id.orderType);
    orderTime = view.findViewById(R.id.orderTime);
    cName = view.findViewById(R.id.cName);
    cContact = view.findViewById(R.id.cContact);
    techEmail = view.findViewById(R.id.techEmail);
    techJob = view.findViewById(R.id.techJob);
    techName = view.findViewById(R.id.techName);
    pModel = view.findViewById(R.id.pModel);
    pType = view.findViewById(R.id.pType);
    specialInst = view.findViewById(R.id.specialInst);
    p_type1 = view.findViewById(R.id.p_type1);
    p_type2 = view.findViewById(R.id.p_type2);

    menu_icon.setVisibility(View.GONE);
    back_icon.setVisibility(View.VISIBLE);
    heading.setVisibility(View.VISIBLE);
    searchBox.setVisibility(View.GONE);
    jobStatus.setVisibility(View.GONE);
    paymentDetail.setVisibility(View.GONE);
    compNameLay.setVisibility(View.GONE);

    footer.setEnabled(false);
    footer.setBackgroundColor(getResources().getColor(R.color.disable_color));
    footer_icon.setBackgroundResource(R.drawable.tap_here_icon);
    footer_txt.setText("Tap here to start a job");
    heading.setText("Order Detail");

    call.setOnClickListener(this);
    start.setOnClickListener(this);
    footer.setOnClickListener(this);
    back_icon.setOnClickListener(this);

    SupportMapFragment mapFragment = (SupportMapFragment) this.getChildFragmentManager()
            .findFragmentById(R.id.map);
    mapFragment.getMapAsync(this);
    return view;
}

private void getOrderDetail() {
    Call call = apiInterface.getOrderDetail(order_id, sharedPreference.getUid(), sharedPreference.getAppToken());
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            if (response.isSuccessful()) {
                OrderDetailModel orderDetailModel = (OrderDetailModel) response.body();
                if (orderDetailModel.getStatus().equals("ok")) {
                    OrderDetailData orderDetailData = orderDetailModel.getData();
                    OrderDetailTechData techData = orderDetailData.getTechnician();
                    OrderDetailCustomerData customerData = orderDetailData.getCustomer();
                    OrderDetailInnerData innerData = orderDetailData.getOrder();

                    orderNo.setText(innerData.getOrderId());
                    orderType.setText(innerData.getOrderType());
                    orderTime.setText(innerData.getTime());
                    pProblem.setText(innerData.getReportedIssue());
                    cLat = Double.valueOf(innerData.getCustomerLatitude());
                    cLong = Double.valueOf(innerData.getCustomerLongitude());
                    customerLatLng = new LatLng(cLat, cLong);

                    if(innerData.getP_type().equals("1")){
                        p_type1.setVisibility(View.GONE);
                        p_type2.setVisibility(View.GONE);
                    }else {
                        p_type1.setVisibility(View.VISIBLE);
                        p_type2.setVisibility(View.VISIBLE);
                        pModel.setText(innerData.getModelNumber());
                        pType.setText(innerData.getProductType());
                    }

                    cName.setText(customerData.getName());
                    contact = customerData.getContact();
                    cContact.setText(contact);
                    adapter = new AddressListAdaper(getContext(), customerData.getAddress());
                    addressList.setAdapter(adapter);
                    techEmail.setText(techData.getEmail());
                    techJob.setText(techData.getMobile());
                    techName.setText(techData.getName());
                    specialInst.setText(innerData.getSpecialInstructions());
                    addMarkersToMap();
                    getTimeDistance();
                    pd.dismiss();
                } else {
                    pd.dismiss();
                    CommonObjects.showToast(getContext(), "Data not Available");
                }
            }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            call.cancel();
            pd.dismiss();
        }
    });
}

@Override
public void onClick(View view) {
    if (view == start) {
        footer.setEnabled(true);
        footer.setBackgroundColor(getResources().getColor(R.color.app_color));

    } else if (view == footer) {
        if (CommonObjects.isNetworkAvailable(getContext())) {
            pd.show();
            updateStatus();
        } else {
            CommonObjects.showToast(getContext(), "Internet not Available");
        }

    } else if (view == back_icon) {
        getActivity().finish();
    } else if (view == call) {
        showCallConfirmationDialog(contact);
    }
}


public void showCallConfirmationDialog(final String contact) {
    try {
        final Dialog dialog = new Dialog(getContext());
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setContentView(R.layout.confirm_call_dialog);
        dialog.setCancelable(false);

        final Window window = dialog.getWindow();
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));

        TextView cancel,ok;
        cancel = dialog.findViewById(R.id.cancel);
        ok = dialog.findViewById(R.id.ok);

        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent phoneIntent = new Intent(Intent.ACTION_DIAL);
                phoneIntent.setData(Uri.parse("tel:"+contact));
                startActivity(phoneIntent);
                dialog.dismiss();
            }
        });

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        dialog.show();
    } catch (Exception e) {
        Log.e("exception is", e.toString());
    }
}

@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;
}

private void addMarkersToMap() {
    mMap.clear();

    for (int i = 0; i < 2; i++) {

        if (i == 0) {
            icon = bitmapDescriptorFromVector(getActivity(), R.drawable.map_logo);
            marker = mMap.addMarker(new MarkerOptions().position(techLatLng)
                    .icon(icon));
        } else {
            icon = bitmapDescriptorFromVector(getActivity(), R.drawable.ic_green_marker);
            marker = mMap.addMarker(new MarkerOptions().position(customerLatLng)
                    .icon(icon));
        }
    }

}

private BitmapDescriptor bitmapDescriptorFromVector(Context context, int vectorResId) {
    Drawable vectorDrawable = ContextCompat.getDrawable(context, vectorResId);
    vectorDrawable.setBounds(0, 0, vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight());
    Bitmap bitmap = Bitmap.createBitmap(vectorDrawable.getIntrinsicWidth(), vectorDrawable.getIntrinsicHeight(), Bitmap.Config.ARGB_8888);
    Canvas canvas = new Canvas(bitmap);
    vectorDrawable.draw(canvas);
    return BitmapDescriptorFactory.fromBitmap(bitmap);
}


private void updateStatus() {
    Call call = apiInterface.updateStatus(sharedPreference.getUid(), order_id, "1");
    call.enqueue(new Callback() {
        @Override
        public void onResponse(Call call, Response response) {
            if (response.isSuccessful()) {
                ForgotModel forgotModel = (ForgotModel) response.body();
                if (forgotModel.getStatus().equals("ok")) {
                    CommonObjects.showToast(getContext(), forgotModel.getData());
                    Bundle b = new Bundle();
                    b.putInt("order_id", order_id);
                    fragment = new CustomerIdentificationFragment();
                    fragment.setArguments(b);
                    ((DetailActivity) getActivity()).showFragment(fragment);
                    pd.dismiss();
                } else {
                    pd.dismiss();
                    CommonObjects.showToast(getContext(), "Data not Available");
                }
            }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            call.cancel();
            pd.dismiss();
        }
    });
}

@Override
public void onLocationChanged(Location location) {
    mLastLocation = location;
    locationManager.removeUpdates(this);

    if (mLastLocation != null) {
        tLat = mLastLocation.getLatitude();
        tLong = mLastLocation.getLongitude();
        techLatLng = new LatLng(tLat,tLong);
    } else {
        CommonObjects.showToast(getContext(), "Couldn't get the location. Make sure location is enabled on the device");
    }

    if (CommonObjects.isNetworkAvailable(getContext())) {
        getOrderDetail();
    } else {
        CommonObjects.showToast(getContext(), "Internet not Available");
    }
}

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

@Override
public void onProviderEnabled(String provider) {
}

@Override
public void onProviderDisabled(String provider) {
}

@Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_FINE_LOCATION:
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                Log.d("gps", "Location permission granted");
                try {
                    locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
                    locationManager.requestLocationUpdates("gps", 0, 0, this);
                } catch (SecurityException ex) {
                    Log.d("gps", "Location permission did not work!");
                }
            }
            break;
    }
}


private void getTimeDistance(){
    String origin = cLat + "," + cLong;
    String destination = tLat + "," + tLong;

    Call call = apiInterface1.getTimeDistance(origin,destination);
    call.enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) {
            if(response.isSuccessful()){
                TimeDistanceModel model = (TimeDistanceModel) response.body();
                if(model.getStatus().equals("OK")) {
                    List<Row> data = model.getRows();
                    List<Element> elements = data.get(0).getElements();
                    Distance distance = elements.get(0).getDistance();
                    Duration duration = elements.get(0).getDuration();

                    if(distance != null) {
                        txt_time.setText(duration.getText());
                        timeDistance.setText(duration.getText() + " (" + distance.getText() + ")");
                        getRoute();
                    }else {
                        CommonObjects.showToast(getContext(),"No deriving route Between these locations");
                        pd.dismiss();
                    }
                }
            }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            call.cancel();
            pd.dismiss();
        }
    });
}


private void getRoute(){
    String origin = cLat + "," + cLong;
    String destination = tLat + "," + tLong;

    Call call = apiInterface1.getRoute(origin,destination);
    call.enqueue(new Callback() {

        @Override
        public void onResponse(Call call, Response response) {
            if(response.isSuccessful()){
                ArrayList<LatLng> routelist = new ArrayList<LatLng>();
                DirectionResult model = (DirectionResult) response.body();
                if(model.getRoutes().size()>0){
                    ArrayList<LatLng> decodelist;
                    Route routeA = model.getRoutes().get(0);
                    if(routeA.getLegs().size()>0){
                        List<Step> steps= routeA.getLegs().get(0).getSteps();
                        Step step;
                        StartLocation_ location;
                        EndLocation_ endLocation;
                        String polyline;
                        for(int i=0 ; i<steps.size();i++){
                            step = steps.get(i);
                            location =step.getStartLocation();
                            routelist.add(new LatLng(location.getLat(), location.getLng()));
                            Log.i("zacharia", "Start Location :" + location.getLat() + ", " + location.getLng());
                            polyline = step.getPolyline().getPoints();
                            decodelist = RouteDecode.decodePoly(polyline);
                            routelist.addAll(decodelist);
                            endLocation =step.getEndLocation();
                            routelist.add(new LatLng(endLocation.getLat() ,endLocation.getLng()));
                            Log.i("zacharia","End Location :"+endLocation.getLat() +", "+endLocation.getLng());
                        }
                    }
                }
                if(routelist.size()>0){
                    PolylineOptions rectLine = new PolylineOptions().width(10).
                            color(getResources().getColor(R.color.app_color));

                    for (int i = 0; i < routelist.size(); i++) {
                        rectLine.add(routelist.get(i));
                    }
                    mMap.addPolyline(rectLine);
                    mMap.moveCamera(CameraUpdateFactory.newLatLng(customerLatLng));
                    mMap.animateCamera(CameraUpdateFactory.zoomTo(Float.parseFloat(String.valueOf(10))));
                }

                pd.dismiss();
            }
        }

        @Override
        public void onFailure(Call call, Throwable t) {
            call.cancel();
            pd.dismiss();
        }
    });
}}

Я испробовал метод, о котором упоминалось в других постах, но он все еще не работает

Я добавил ключ SHA1 для выпуска и отладки в консоли, который все еще не работаетработа

Снимок экрана консоли

api hit

При использовании OkHttp я получаю этот ответ

 D/OkHttp: {

   "destination_addresses" : [],

   "error_message" : "This IP, site or mobile application is not authorized to use this API key. Request received from IP address 122.173.241.210, with empty referer",

   "origin_addresses" : [],

   "rows" : [],

   "status" : "REQUEST_DENIED"

}

<-- END HTTP (280-byte body)
...