1

在我的 DataField 应用程序中,我使用了一个 OAuth,它给了我一个令牌。所以现在我想下载一个 json 所以我有这个主要的 App 类

using Toybox.Application as App;
using Toybox.Background;
using Toybox.System as Sys;
using Toybox.WatchUi as Ui;
using Toybox.Time;
using Toybox.UserProfile;
using Toybox.PersistedContent;
using Toybox.System;
using Toybox.Communications as Comm;

(:background)
class KronosApp extends App.AppBase {
    var inBackground=false;
    var bg=null;

    function initialize() {
        AppBase.initialize();
        Sys.println("AppBase initialize");
        if(Toybox.System has :ServiceDelegate) {
            Background.registerForTemporalEvent(new Time.Duration(5 * 60));
        } else {
            Sys.println("****background not available on this device****");
        }
        Background.registerForOAuthResponseEvent();

      }

    // onStart() is called on application start up
    function onStart(state) { 
        System.println("start");

    }

    // onStop() is called when your application is exiting
    function onStop(state) {
        if(!inBackground) {
            Background.deleteTemporalEvent();
            System.println("stop");
        }
    }


    //! Return the initial view of your application here
    function getInitialView() {
        System.println("getInitialView");
        var Kview = new KronosView();
        return [ Kview];
    }

    //store json data in bgdata
    function onBackgroundData(data) {
        System.println("onbg "+ data);
    }    

    function getServiceDelegate(){
        inBackground=true;  
        System.println("getServiceDelegate");
        return [new JsonBackground()];
    }

以及执行 OAuth 的此类,然后获取自定义 JSon

using Toybox.Background as Bg;
using Toybox.Application as App;
using Toybox.System as Sys;
using Toybox.Time as Tm;
using Toybox.Communications as Comm;

// The Service Delegate is the main entry point for background processes
// our onTemporalEvent() method will get run each time our periodic event
// is triggered by the system.
const ClientId = "";
const ClientSecret = "";
const ApiUrl = "";
const RedirectUri = "https://localhost/";   

(:background)
class JsonBackground extends Toybox.System.ServiceDelegate {

    (:background_method)
    function initialize() {
        Sys.ServiceDelegate.initialize();
        Comm.registerForOAuthMessages(method(:accessCodeResult));
    }

    (:background_method)    
    function onTemporalEvent() {
        System.println("onTemporalEvent2");
            go();
    }

    (:background_method)
    function go() {
        Sys.println("go");
        Comm.makeOAuthRequest(
            // URL for the authorization URL
            " ... ",
            // POST parameters
            {
        //...params///              
            },
            // Redirect URL
            "...",
            // Response type
            Comm.OAUTH_RESULT_TYPE_URL,
            // Value to look for
            {"code"=>"value"}
            );
    }

    // Handle converting the authorization code to the access token
    // @param value Content of JSON resp    onse
    (:background_method)
    function accessCodeResult(response) {
        Sys.println("accessCodeResult " +response.data );
        if( response.data != null) {
            Sys.println("accessCodeResult Ok");
            getJson(response.data["value"]);
        }
        else {
            Sys.println("Error in accessCodeResult");
        }
    }

    (:background_method)
    function handleAccessResponse(responseCode, data) {
        Sys.println("handleAccessResponse");
        if( data != null) {
            Sys.println("data handleAccessResponse OK");
        } else {
            Sys.println("Error in handleAccessResponse"+responseCode);
        }
        Bg.exit(data);            
    }


    (:background_method)
    function getJson(accessCode) {
        Sys.println("getJson " + accessCode);
        var url = "https://jsonplaceholder.typicode.com/posts/1";
        var params = {};
        var options = {                                             // set the options
           :method => Comm.HTTP_REQUEST_METHOD_GET,      // set HTTP method
           :headers => {
                "Content-Type" => Communications.REQUEST_CONTENT_TYPE_JSON
            },
           :responseType => Comm.HTTP_RESPONSE_CONTENT_TYPE_JSON
        };

        var responseCallback = self.method(:handleAccessResponse);
        Comm.makeWebRequest(url, params, options,responseCallback);

    }

}

OAuth 的 URL 已被混淆

在控制台中我有这个日志:

Background: AppBase initialize
Background: start
Background: getServiceDelegate
Background: AppBase initialize
Background: start
Background: getServiceDelegate
Background: onTemporalEvent2
Background: go
AppBase initialize
start
getInitialView
Background: AppBase initialize
Background: start
Background: getServiceDelegate
Background: accessCodeResult {value=>4b90b6dabf72e29c3f07e84340bb1e34f0d0edf3}
Background: accessCodeResult Ok
Background: getJson 4b90b6dabf72e29c3f07e84340bb1e34f0d0edf3

所以你可以看到 handleAccessResponse 没有被调用。

4

0 回答 0