【问题标题】:Why will my program work in an emulator but not a real device?为什么我的程序可以在模拟器中运行,但不能在真实设备中运行?
【发布时间】:2016-06-12 19:45:47
【问题描述】:

我最近编写了一些代码,旨在通过 GPS 找到用户的位置。当我在模拟器中运行代码时,程序运行良好。但是,当我将其连接到手机时,该程序无法运行并处于空闲状态。这是我的 MainActivity.java:

package aw.com.testlocation;

import android.Manifest;
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.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import org.json.JSONException;
import org.json.JSONObject;

public class MainActivity extends AppCompatActivity {

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

        button = (Button) findViewById(R.id.button);
        textView = (TextView) findViewById(R.id.textView);

        requestQueue = Volley.newRequestQueue(this);

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String url = "https://maps.googleapis.com/maps/api/geocode/json?latlng=" + latitude + "," + longitude + "&key=AIzaSyCxSv54uAgGv-pRULO_KQ6QWEciWmmanZo";
                JsonObjectRequest request = new JsonObjectRequest(url, new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        try {
                            String address = response.getJSONArray("results").getJSONObject(0).getString("formatted_address");
                            textView.setText(address);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
                    @Override
                    public void onErrorResponse(VolleyError error) {

                    }
                });
                requestQueue.add(request);
            }
        });
                locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
                locationListener = new LocationListener() {
                    @Override
                    public void onLocationChanged(Location location) {
                        latitude = location.getLatitude();
                        longitude = location.getLongitude();
                        //textView.setText("Latitude: " + location.getLatitude() + " Longitude: " + location.getLongitude());
                    }

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

                    }

                    @Override
                    public void onProviderEnabled(String provider) {

                    }

                    @Override
                    public void onProviderDisabled(String provider) {
                        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        startActivity(intent);
                    }
                };
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                    if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        requestPermissions(new String[]{
                                Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.INTERNET
                        }, 10);
                        return;
                    }
                } else {
                    configureButton();
                }
                locationManager.requestLocationUpdates("gps", 20000, 0, locationListener);
            }

            @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)
                            configureButton();
                        return;
                }
            }

            private void configureButton() {
                button.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        locationManager.requestLocationUpdates("gps", 20000, 0, locationListener);
                    }
                });
            }

    Button button;
    TextView textView;
    private LocationManager locationManager;
    private LocationListener locationListener;
    RequestQueue requestQueue;
    double latitude;
    double longitude;

    }

这是我的 activity_main.xml 文件:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="aw.com.testlocation.MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="REQUEST LOCATION"
        android:id="@+id/button"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Location:"
        android:id="@+id/textView"
        android:layout_below="@+id/button"
        android:layout_centerHorizontal="true"
        android:textSize="24dp" />
</RelativeLayout>

这是我的清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="aw.com.testapp">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

我的 logcat 太长,无法发布:/ 但是,我确实不断收到错误消息:GoogleService 无法初始化,状态:10,缺少预期的资源:用于初始化 Google 服务的“R.string.google_app_id”。可能的原因是缺少 google-services.json 或 com.google.gms.google-services gradle 插件。

非常感谢任何帮助。谢谢。

【问题讨论】:

  • 您的设备上有有效的互联网连接?
  • “程序不工作,闲置”——请详细解释这是什么意思。
  • 我的设备确实有互联网连接。
  • “程序不工作并且空闲” -- 请详细解释这是什么意思。 - 应用程序启动,但当我按下按钮时不执行任何操作。
  • 您是否尝试过修复错误消息所说的问题? Missing an expected resource: 'R.string.google_app_id'...您必须使用该值更新您的 strings.xml 文件

标签: android


【解决方案1】:

这是因为在模拟器上你可能甚至没有 Google Play 服务,清理 AOSP。 Google 还提供了带有 GPS 的模拟器版本,但它是可选的,你可能不使用它(我也是 :))。在这个 os-image 版本上,由于没有 GPS-lib-on-device 连接,您的地图 API 甚至不会被尝试执行。

除此之外,还阅读了有关从 logcat 正确实施这些文件的信息。检查HERE。当您正确实施这部分导入时,您的应用也可以在具有 Google Play 服务的设备上运行。

请记住,大多数 Google Play 服务“部分”只能在具有 Play 商店的设备上运行

有关更多信息,请显示您的 Manifest 和 gradle 文件,这样我们就可以更多地说明您正在导入的内容,这显然来自 Google(logcat!)

【讨论】:

  • 我已经尝试过实现 google-services.json。可悲的是,它对我没有用 :(。我的清单文件现在已经存在 :D.
  • 您已尝试实现google-services.json 文件,但它对您不起作用,现在您的应用程序因Possible causes are missing google-services.json or com.google.gms.google-services gradle plugin. 而崩溃-您为什么要问这个问题?!像教程中那样正确实施地图,一切都会奏效。检查您是否将此 json 放置在正确的文件夹中并检查/显示您的 gradle,您必须在其中实现服务
猜你喜欢
  • 2014-03-27
  • 1970-01-01
  • 2017-05-01
  • 2013-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-13
相关资源
最近更新 更多