首页 > 解决方案 > kivy.network.urlrequest 无法在 Android 上运行,导致黑屏

问题描述

直到我为 Urlrequest 添加了以下行,我的 kivy 应用程序在我的 android 上运行并立即以正确的输出打开。现在添加 urlrequest 代码后,我的 android 上出现了永无止境的黑屏。为什么会这样?我的笔记本电脑虽然显示正确的输出。请帮我解决。还在等待解决方案!


    from kivy.network.urlrequest import UrlRequest
    
    def where(): 
        f = os.path.dirname(file) 
        return os.path.join(f, 'cacert.pem') 
    
    req = UrlRequest(scan_url, req_body=jdata, ca_file=where(), verify= True)
    req.wait()
    resp = req.result
    indicator_values = resp["data"][0]['d']
    ```
      
    class TA_Handler(BoxLayout):
        screener = ""
        exchange = ""
        symbol = ""
        interval = "1d"
    
        #Get analysis
        def on_getCloudEvents_success(self,request,result):
            print("on_getCloudEvents_success called:")
            print("  result="+str(result))
            self.resp = result
            self.SYNC_REQUEST_STAT="Success" # to end the synchronous wait
            
            
        def on_getCloudEvents_failure(self,request,result):
            print("on_getCloudEvents_failure called:")
            print("  request was sent to "+str(request.url))
            print("    request body="+str(request.req_body))
            print("    request headers="+str(request.req_headers))
            print("  result="+str(request.result))
            self.SYNC_REQUEST_STAT="Failure" # to end the synchronous wait
    
        def on_getCloudEvents_error(self,request,result):
            print("on_getCloudEvents_error called:")
            print("  request was sent to "+str(request.url))
            print("    request body="+str(request.req_body))
            print("    request headers="+str(request.req_headers))
            print("  result="+str(request.result))        
            self.SYNC_REQUEST_STAT="Error" # to end the synchronous wait
            
            
        def get_analysis(self):
            super(TA_Handler,self).__init__()
            """Get analysis from TradingView and compute it.
    
            Returns:
                Analysis: Contains information about the analysis.
            """
            if self.screener == "" or type(self.screener) != str:
                raise Exception("Error: screener is empty or not valid")
            elif self.exchange == "" or type(self.exchange) != str:
                raise Exception("Error: exchange is empty or not valid")
            elif self.symbol == "" or type(self.symbol) != str:
                raise Exception("Error: symbol is empty or not valid")
            elif self.interval == "" or type(self.symbol) != str:
                warnings.warn("Warning: interval is empty or not valid, defaulting to 1 day.")
    
            exch_smbl = self.exchange.upper() + ":" + self.symbol.upper()
            data = TradingView.data(exch_smbl, self.interval)
            scan_url = TradingView.scan_url + self.screener.lower() + "/scan"
            self.resp = None
    
            jdata = json.dumps(data).encode('utf-8')          
            request = UrlRequest(scan_url, req_body=jdata,ca_file=where(),verify=True,\
                on_success=self.on_getCloudEvents_success,
                on_failure=self.on_getCloudEvents_failure,
                on_error=self.on_getCloudEvents_error)
    
    #
            resp=request.result
            indicator_values = resp["data"][0]['d']  
            
    
            oscillators_counter, ma_counter = {"BUY": 0, "SELL": 0, "NEUTRAL": 0}, {"BUY": 0, "SELL": 0, "NEUTRAL": 0}
            computed_oscillators, computed_ma = {}, {}
    
            # RECOMMENDATIONS
            recommend_oscillators = Compute.Recommend(indicator_values[0])
            recommend_summary = Compute.Recommend(indicator_values[1])
            recommend_moving_averages = Compute.Recommend(indicator_values[2])
    
            # OSCILLATORS
            # RSI (14)
            # some code
            analysis.summary = {"RECOMMENDATION": recommend_summary, "BUY": oscillators_counter["BUY"] + ma_counter["BUY"], "SELL": oscillators_counter["SELL"] + ma_counter["SELL"], "NEUTRAL": oscillators_counter["NEUTRAL"] + ma_counter["NEUTRAL"]}
            return analysis
    
    class MainApp(App):
        def this_job(self):
        
            handler = TA_Handler()
            handler.symbol = "BTCUSDT"
            
            handler.exchange = "BITTREX"
            handler.screener = "crypto"
            osc=[]
            ma=[]
            sum1=[]
            for h in ['15m','1h','4h','1d','1W']:
                handler.interval = h # 1 day
                analysis = handler.get_analysis()
                osc1_rec = (analysis.oscillators).get('RECOMMENDATION')
                sum_rec = (analysis.summary).get('RECOMMENDATION')
                ma_rec = (analysis.moving_averages).get('RECOMMENDATION')
                osc.append(osc1_rec)
                ma.append(ma_rec)
                sum1.append(sum_rec)
            return osc,ma, sum1
    
    
        def build(self):
    #        osc=[]
    #        ma=[]
    #        sum1=[]
            handler = TA_Handler()
            handler.symbol = "BTCUSDT"
            
            handler.exchange = "BITTREX"
            handler.screener = "crypto"
            osc=[]
            ma=[]
            sum1=[]
            for h in ['15m','1h','4h','1d','1W']:
                handler.interval = h # 1 day
                analysis = handler.get_analysis()
                osc1_rec = (analysis.oscillators).get('RECOMMENDATION')
                sum_rec = (analysis.summary).get('RECOMMENDATION')
                ma_rec = (analysis.moving_averages).get('RECOMMENDATION')
                osc.append(osc1_rec)
                ma.append(ma_rec)
                sum1.append(sum_rec)
            x=osc[0]
    #        osc,ma,sum1 = this_job()
            label = Label(text='Hello from Kivy' + x,
                          size_hint=(.5, .5),
                          pos_hint={'center_x': .5, 'center_y': .5})
    
            
            return label
            
    
    
    if __name__ == '__main__':
        app = MainApp()
        app.run()

I also copied cacert.pem to my project folder. 

Just these lines make the screen go black. And the output with these same lines is perfect on my laptop but not just on the android.

Also, the app doesn't crash like with an error, the screen just becomes all black!!

标签: pythonandroidkivybuildozerurlrequest

解决方案


我正在回答我自己的问题。req.wait() 是同步的。当我删除 req.wait() 并改为使用 request = UrlRequest(scan_url, req_body=jdata, on_success=self.on_get_success) 时。它不再停留在黑屏上。

但是,我仍然需要找到一种方法将结果返回给调用类。


推荐阅读