Java 如何使用Eclipse在Android中实现/链接运行Keeper API?

Java 如何使用Eclipse在Android中实现/链接运行Keeper API?,java,android,api,webviewclient,Java,Android,Api,Webviewclient,我想在我的代码中使用RunKeeperAPI,因为我正在开发跟踪步行距离等的应用程序。这可以通过使用RunKeeper API来实现。 在注册我的应用程序时,它要求我输入回拨后的URL,我不知道从哪里获取回拨URL:( 这是我被卡住的代码 package com.example.testapp; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.htt

我想在我的代码中使用RunKeeperAPI,因为我正在开发跟踪步行距离等的应用程序。这可以通过使用RunKeeper API来实现。 在注册我的应用程序时,它要求我输入回拨后的URL,我不知道从哪里获取回拨URL:(

这是我被卡住的代码

package com.example.testapp;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.webkit.CookieManager;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    private Button button;
    private WebView webView;

    private final static String CLIENT_ID = "b25ef732fdea4fc1a5d59036f05cfad0";
    private final static String CLIENT_SECRET = "741a1216e5f14c38b5768840d6720d2c";
    private final static String CALLBACK_URL = "";

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

        // Force to login on every launch.
        CookieManager cookieManager = CookieManager.getInstance();
        cookieManager.removeAllCookie();

        button = (Button) findViewById(R.id.button);
        webView = (WebView) findViewById(R.id.webView);
        webView.getSettings().setJavaScriptEnabled(true);
    }

    @Override
    public void onClick(View v) {
        button.setVisibility(View.GONE);
        webView.setVisibility(View.VISIBLE);

        getAuthorizationCode();
    }

    private void getAuthorizationCode() {
        String authorizationUrl = "https://runkeeper.com/apps/authorize";
        authorizationUrl = String.format(authorizationUrl, CLIENT_ID,CALLBACK_URL);
        Toast.makeText(MainActivity.this, "Milestone 1", Toast.LENGTH_SHORT).show();

        webView.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Toast.makeText(MainActivity.this, url, Toast.LENGTH_SHORT).show();

                if (url.startsWith(CALLBACK_URL)) {
                    final String authCode = Uri.parse(url).getQueryParameter("code");
                    webView.setVisibility(View.GONE);
                    getAccessToken(authCode);
                    return true;
                }

                return super.shouldOverrideUrlLoading(view, url);
            }
        });

        webView.loadUrl(authorizationUrl);
    }

    private void getAccessToken(String authCode) {
        Toast.makeText(MainActivity.this, "Milestone 3", Toast.LENGTH_SHORT).show();
        String accessTokenUrl = "https://runkeeper.com/apps/token";
        final String finalUrl = String.format(accessTokenUrl, authCode,CLIENT_ID, CLIENT_SECRET);
        Thread networkThread = new Thread(new Runnable() {
            @Override
            public void run() {
                try {

                    HttpClient client = new DefaultHttpClient();
                    HttpPost post = new HttpPost(finalUrl);

                    HttpResponse response = client.execute(post);

                    String jsonString = EntityUtils.toString(response
                            .getEntity());
                    final JSONObject json = new JSONObject(jsonString);

                    String accessToken = json.getString("access_token");
                    getTotalDistance(accessToken);

                } catch (Exception e) {
                    displayToast("Exception occured:(");
                    e.printStackTrace();
                    resetUi();
                }

            }
        });

        networkThread.start();
    }

    private void getTotalDistance(String accessToken) {
        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet("http://api.runkeeper.com/user/");

            get.addHeader("Authorization", "Bearer " + accessToken);
            get.addHeader("Accept", "*/*");

            HttpResponse response = client.execute(get);

            String jsonString = EntityUtils.toString(response.getEntity());
            JSONArray jsonArray = new JSONArray(jsonString);
            findTotalWalkingDistance(jsonArray);

        } catch (Exception e) {
            displayToast("Exception occured:(");
            e.printStackTrace();
            resetUi();
        }
    }

    private void findTotalWalkingDistance(JSONArray arrayOfRecords) {
        try {
            // Each record has activity_type and array of statistics. Traverse
            // to activity_type = Walking
            for (int ii = 0; ii < arrayOfRecords.length(); ii++) {
                JSONObject statObject = (JSONObject) arrayOfRecords.get(ii);
                if ("Walking".equalsIgnoreCase(statObject
                        .getString("activity_type"))) {
                    // Each activity_type has array of stats, navigate to
                    // "Overall" statistic to find the total distance walked.
                    JSONArray walkingStats = statObject.getJSONArray("stats");
                    for (int jj = 0; jj < walkingStats.length(); jj++) {
                        JSONObject iWalkingStat = (JSONObject) walkingStats
                                .get(jj);
                        if ("Overall".equalsIgnoreCase(iWalkingStat
                                .getString("stat_type"))) {
                            long totalWalkingDistanceMeters = iWalkingStat
                                    .getLong("value");
                            double totalWalkingDistanceMiles = totalWalkingDistanceMeters * 0.00062137;
                            displayTotalWalkingDistance(totalWalkingDistanceMiles);
                            return;
                        }
                    }
                }
            }
            displayToast("Something went wrong!!!");
        } catch (JSONException e) {
            displayToast("Exception occured:(");
            e.printStackTrace();
            resetUi();
        }
    }

    private void resetUi() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                button.setVisibility(View.VISIBLE);
                webView.setVisibility(View.GONE);
            }
        });
    }

    private void displayTotalWalkingDistance(double totalWalkingDistanceMiles) {
        final String milesWalkedMessage = (totalWalkingDistanceMiles < 1) ? "0 miles?, You get no respect, Start walking already!!!"
                : String.format("Cool, You have walked %.2f miles so far.",
                        totalWalkingDistanceMiles);

        displayToast(milesWalkedMessage);
        resetUi();
    }

    private void displayToast(final String message) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                Toast.makeText(getApplicationContext(), message,
                        Toast.LENGTH_LONG).show();
            }
        });
    }

}
package com.example.testapp;
导入org.apache.http.HttpResponse;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.methods.HttpGet;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.util.EntityUtils;
导入org.json.JSONArray;
导入org.json.JSONException;
导入org.json.JSONObject;
导入android.annotation.SuppressLint;
导入android.app.Activity;
导入android.net.Uri;
导入android.os.Bundle;
导入android.view.view;
导入android.view.view.OnClickListener;
导入android.webkit.CookieManager;
导入android.webkit.WebView;
导入android.webkit.WebViewClient;
导入android.widget.Button;
导入android.widget.Toast;
公共类MainActivity扩展活动实现OnClickListener{
私人按钮;
私有网络视图;
私有最终静态字符串客户端\u ID=“b25ef732fdea4fc1a5d59036f05cfad0”;
私有最终静态字符串客户端_SECRET=“741A1216E5F14C38B576840D6720D2C”;
私有最终静态字符串回调_URL=“”;
@SuppressLint(“SetJavaScriptEnabled”)
@凌驾
创建时受保护的void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//每次发射时强制登录。
CookieManager CookieManager=CookieManager.getInstance();
cookieManager.removeAllCookie();
按钮=(按钮)findViewById(R.id.button);
webView=(webView)findviewbyd(R.id.webView);
webView.getSettings().setJavaScriptEnabled(true);
}
@凌驾
公共void onClick(视图v){
按钮。设置可见性(View.GONE);
设置可见性(View.VISIBLE);
getAuthorizationCode();
}
私有void getAuthorizationCode(){
字符串授权URL=”https://runkeeper.com/apps/authorize";
authorizationUrl=String.format(authorizationUrl、客户端ID、回调URL);
Toast.makeText(MainActivity.this,“里程碑1”,Toast.LENGTH_SHORT.show();
setWebViewClient(新的WebViewClient(){
@凌驾
公共布尔值shouldOverrideUrlLoading(WebView视图,字符串url){
Toast.makeText(MainActivity.this,url,Toast.LENGTH_SHORT).show();
if(url.startsWith(CALLBACK_url)){
最后一个字符串authCode=Uri.parse(url.getQueryParameter(“代码”);
webView.setVisibility(View.GONE);
getAccessToken(authCode);
返回true;
}
返回super.shouldOverrideUrlLoading(视图、url);
}
});
loadUrl(授权URL);
}
私有void getAccessToken(字符串authCode){
Toast.makeText(MainActivity.this,“里程碑3”,Toast.LENGTH_SHORT.show();
字符串accessTokenUrl=”https://runkeeper.com/apps/token";
final String finalUrl=String.format(accessTokenUrl、authCode、客户端ID、客户端机密);
线程networkThread=新线程(new Runnable(){
@凌驾
公开募捐{
试一试{
HttpClient=new DefaultHttpClient();
HttpPost=新的HttpPost(最终);
HttpResponse response=client.execute(post);
字符串jsonString=EntityUtils.toString(响应
.getEntity());
最终JSONObject json=新的JSONObject(jsonString);
String accessToken=json.getString(“访问令牌”);
getTotalInstance(accessToken);
}捕获(例外e){
displayToast(“发生异常:(”);
e、 printStackTrace();
resetUi();
}
}
});
networkThread.start();
}
私有void getTotalInstance(字符串访问令牌){
试一试{
HttpClient=new DefaultHttpClient();
HttpGet=新的HttpGet(“http://api.runkeeper.com/user/");
get.addHeader(“授权”、“承载人”+accessToken);
get.addHeader(“接受”,“*/*”);
HttpResponse response=client.execute(get);
字符串jsonString=EntityUtils.toString(response.getEntity());
JSONArray JSONArray=新的JSONArray(jsonString);
查找总通行距离(jsonArray);
}捕获(例外e){
displayToast(“发生异常:(”);
e、 printStackTrace();
resetUi();
}
}
专用void find总通行距离(JSONArray阵列记录){
试一试{
//每个记录都有活动类型和统计数组
//活动类型=步行
对于(int ii=0;iicom.example.runkeeperapi://RunKeeperIsCallingBack"