Kivy 应用程序(在 android 上)在尝试使用 google 方向时崩溃 api

Kivy app (on android) crashes when attempting to use google directions api

我是 Kivy 的新手(对 Python 来说相对较新),我在使用 UrlRequests 时遇到了问题。特别是,我正在尝试在 android 的应用程序中使用 google 方向 api。

首先,当我通过 python 运行 main.py 文件时,代码可以(完全)工作。 该应用程序还使用 buildozer 成功构建并部署到我的 phone。应用程序加载并 运行s 直到您按下按钮启动 url 请求,此时应用程序刚刚关闭。

所以我认为问题出在这个按钮上。现在我认为按钮的全部细节有点不需要解释,但基本上它使用一个函数(如下所示)几次 return 地方之间的距离。

import urllib2

#the google api key
google_api_key = '...'

def distance_checker(origin, destination):
    # This function outputs the distance between two places in meters
    api_key = google_api_key
    url = 'https://maps.googleapis.com/maps/api/directions/json?origin='
    start = origin.replace(' ', '%20')
    end = destination.replace(' ', '%20')
    final_url = url + start + '&destination=' + end + '&mode=walking' + '&key=' + api_key
    json_obj = urllib2.urlopen(final_url)
    data = json.load(json_obj)

    return data['routes'][0]['legs'][0]['distance']['value']

在我的 buildozer.spec 文件中,我确实包含了 'android.permissions = INTERNET'。

我还让我的应用尝试使用表单函数访问 google(由用户提交:10flow,在 Pinging servers in Python),

import os

def ping_function(self):
    hostname = "google.com" #example
    response = os.system("ping -c 1 " + hostname)

    #and then check the response...
    if response == 0:
        self.box.add_widget(Label(text=(hostname + ' is up!'), size_hint_y=None, height=40))
    else:
        self.box.add_widget(Label(text=(hostname + ' is down!'), size_hint_y=None, height=40))

为清楚起见,上面使用的 'box' 用于 ScrollView 小部件。此功能在 android 中的应用程序中确实有效(即它确实创建了一个标签说 'google.com is up!')。所以这会让我相信访问互联网本身不是问题:问题是要么使用 google api,要么使用 urllib2(这有意义吗?) .

我还编写了一个函数,该函数使用 UrlRequest 而不是 urllib2 执行 url 查询,但最终遇到了同样的问题(适用于 linux,不适用于android)。

所以我想问题出在使用 google apis。我认为这与在 buildozer.spec 文件中添加 'google-play-services_lib/' 作为 android.library 引用有关。

如果我到目前为止所说的有道理,那么有人可以对 google api/google-play-services_lib 问题发表评论吗?一般来说,我真的不太熟悉 apis,而且有点超出我的理解范围。或许这不是问题所在,我错过了一些明显的东西。

无论如何,先谢谢了。

编辑

我想我已经缩小了问题的范围。我可以使用不需要密钥的 apis,但我不能使用需要密钥的 apis。 How to get google map apikey in android 之类的帖子让我相信我只需要将 google api 键(在 google 方向 api 的情况下)添加到 [= buildozer.spec 文件中的 56=] 元数据。我尝试了以下几种变体均未成功,

# (list) Android application meta-data to set (key=value format)
android.meta_data = com.google.android.maps.v2.API_KEY=AI...

如果有人能告诉我我做错了什么,那将非常有帮助! 谢谢。

所以对于其他人和子孙后代,我通过 Kivy 用户论坛找到了答案(http://kivy.org/#forum,问题:UrlRequest 问题 api 需要 api 键)。

问题是我试图访问 https url,因此需要使用 openssl 构建 android apk。不需要 android 元数据或 google 播放服务,只需将 openssl 添加到 buildozer.spec 文件中的要求即可。 requirements = openssl,kivy

一旦发现 openssl 是问题所在,还有一个问题需要解决,即 buildozer 试图下载 openssl.org 网页上不再存在的 openssl tar 文件。但是,可以编辑 buildozer 尝试在 your_project/.buildozer/android/platform/python-for-android/recipes/openssl/recipe.sh 中下载的 openssl 版本。您还需要更新该文件中的 MD5 值。

希望这对以后的人有所帮助。