获取GPS坐标适用于模拟器,但不适用于设备

时间:2016-10-27 20:20:13

标签: java android gps

美好的一天

我正在为我的计算机科学项目创建一个辅导应用程序,我遇到了获取GPS位置的问题。正如我的标题所述,它适用于模拟器(Toast the location以及写入数据库),但在我的手机或其他所有设备上我尝试过它甚至没有Toast,这意味着它甚至没有进入课堂。我环顾四周但找不到解决方案。

继承我的班级getlocation:

    package com.example.tutor;

import android.Manifest;
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.widget.Toast;

import static android.content.Context.LOCATION_SERVICE;

/**
 * Created by admin on 03-Oct-16.
 */


public class GetLocation2 {

    private LocationManager locationManager;
    private LocationListener locationListener;
    Activity parent;
    String TutorStudentID;
    int status;


    public GetLocation2(Activity par, String tsi, int i) {

        parent = par;
        TutorStudentID = tsi;
        final int[] count = {0};
        status = i;

        locationManager = (LocationManager) parent.getSystemService(LOCATION_SERVICE);
        locationListener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                //  txtLocation.append("\n " + location.getLatitude() + " "+ location.getLongitude());
                if (count[0] == 0) {

                    if (status == 0) {
                        Toast.makeText(parent.getApplicationContext(), "Lat: " + location.getLatitude() + " Long: " + location.getLongitude(), Toast.LENGTH_SHORT).show();
                        tutor_checkin connect2server = new tutor_checkin(parent, TutorStudentID, "Lat: " + location.getLatitude() + " Long: " + location.getLongitude());
                        connect2server.execute();
                    }
                    if (status == 1) {
                        Toast.makeText(parent.getApplicationContext(), "Lat: " + location.getLatitude() + " Long: " + location.getLongitude(), Toast.LENGTH_SHORT).show();
                        tutor_checkout connect2server1 = new tutor_checkout(parent, TutorStudentID, "Lat: " + location.getLatitude() + " Long: " + location.getLongitude());
                        connect2server1.execute();
                    }

                    count[0]++;
                }

                Toast.makeText(parent.getApplicationContext(), "Lat: " + location.getLatitude() + " Long: " + location.getLongitude(), Toast.LENGTH_SHORT).show();


            }

            @Override
            public void onStatusChanged(String s, int i, Bundle bundle) {

            }

            @Override
            public void onProviderEnabled(String s) {
                //  onLocationChanged();


            }

            @Override
            public void onProviderDisabled(String s) {
                Intent intent = new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                parent.startActivity(intent);



            }
        };
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {

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

                parent.requestPermissions(new String[]{
                                Manifest.permission.ACCESS_FINE_LOCATION,
                                Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.INTERNET}
                        , 10);
                return;
            }
        } else {

            //  if(count ==0) {
            locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);


            // count++ ;
            // }

            //  configureButton();
            // btnLocation.performClick();
            //  locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);

        }

    }

    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        // super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // int count = 0 ;
        switch (requestCode) {
            case 10:
                // if(count == 0 ) {
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if (ActivityCompat.checkSelfPermission(parent.getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(parent.getApplicationContext(), 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;
                    }
                    locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);
                      //  count++;

                    }
                //}


                //  configureButton();
        }

    }

}

我在哪里调用它(来自CardViewAdapter)

eventViewHolder.Checkin.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                String sText = eventViewHolder.Checkin.getText().toString() ;



                if(sText.toString().equals("Check in"))
                {
                    eventViewHolder.Checkin.setText("Check out");
                    new GetLocation2(H, Sessions.get(i).sessionID,0);



                }
});

3 个答案:

答案 0 :(得分:0)

也许您错过了'uses-permission' declaration in the AndroidManifest.xml

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

requesting permissions文档中所述,

  

在所有Android版本上,您的应用需要在其应用清单中声明其所需的正常和危险权限,如声明权限中所述。但是,该声明的效果因系统版本和应用程序的目标SDK级别而异:

     

如果设备运行的是Android 5.1或更低版本,或者您的应用的目标SDK为22或更低:如果您在清单中列出了危险权限,则用户必须在安装应用时授予权限;如果他们没有授予权限,系统根本不会安装应用程序。

     

如果设备运行的是Android 6.0或更高版本,并且您的应用的目标SDK为23或更高:该应用必须列出清单中的权限,并且必须在应用时请求它所需的每个危险权限运行即可。用户可以授予或拒绝每个权限,即使用户拒绝权限请求,应用也可以继续以有限的功能运行。

答案 1 :(得分:0)

尝试使用:

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 0, locationListener);

而不是:

locationManager.requestLocationUpdates("gps", 5000, 0, locationListener);

手机有没有修复?,它可以从GPS获取位置吗?,尝试使用房子外面的应用程序,这样你就可以确定GPS得到修复。是否在手机上启用了位置服务?

除了要求运行时权限之外,还需要将权限添加到清单文件中。

答案 2 :(得分:0)

问题是,如果你有onRequestPermissionsResult()方法,它不会覆盖超类中的任何方法,所以它永远不会被调用。

此方法覆盖需要进入活动。

使用@Override注释进行方法覆盖是一种很好的做法。 如果你把onRequestPermissionsResult()放在目前所在的地方,你会看到类似的东西:

enter image description here

为了解决这个问题,首先要创建一个实例变量来跟踪GetLocation2引用:

public class MainActivity extends AppCompatActivity {

    GetLocation2 getLoc2;
    //............

然后分配getLoc2引用:

eventViewHolder.Checkin.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String sText = eventViewHolder.Checkin.getText().toString() ;
            if(sText.toString().equals("Check in"))
            {
                eventViewHolder.Checkin.setText("Check out");
                getLoc2 = new GetLocation2(H, Sessions.get(i).sessionID,0);
            }
        });

然后将onRequestPermissionsResult()方法移动到Activity,而不是直接调用requestLocationUpdates(),调用您将在GetLocation2类中定义的新公共方法:

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    switch (requestCode) {
        case 10:

            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                        && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                    return;
                }

                if (getLoc2 != null) {
                    getLoc2.requestLocations();
                }
            }
    }
}

最后,在GetLocation2类中定义getLocations()方法:

public void requestLocations() {

    if (ActivityCompat.checkSelfPermission(parent, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
            || ActivityCompat.checkSelfPermission(parent, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
        return;
    }

    locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,5000,0,locationListener);
}