如何在不同的活动中使用Asynctask?

时间:2018-03-30 13:02:09

标签: android api android-asynctask fitbit

我正在编写一个正确连接到Fitbit API的应用程序,并将我需要的数据拉回来。我有一个扩展AsyncTask的内部类,可以让我完成这个。例如,我的 MainActivity.java 会打开Fitbit OAuth2页面并且用户会登录。然后,用户将被定向回 UserActivity.java 并显示其信息。

我现在想要添加另一个Activity来回收他们执行的活动的信息。所以,我的问题是,我是否需要在 ActivitiesActivity.java 中添加另一个内部类,或者是否有其他方法来获取数据。我知道之前有人使用过界面,但我不确定它们是如何与AsyncTask一起使用的。

    package com.jordan.fitbit_connect;

import android.net.Uri;
import android.os.Bundle;
import android.support.customtabs.CustomTabsIntent;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {


    String response_type = "token";
    String client_id = "22CJH3";
    String redirect_uri = "myapplication://login";
    String scope = "activity%20nutrition%20heartrate%20location%20nutrition%20profile%20settings%20sleep%20social%20weight";
    String url = "https://www.fitbit.com/oauth2/authorize?" + "response_type=" + response_type + "&client_id=" + client_id + "&redirect_uri=" + redirect_uri + "&scope=" + scope;


    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
//
//        CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build();
//        customTabsIntent.launchUrl(this, Uri.parse(url));

            connectToFitbit();
    }

    public void connectToFitbit()
    {
        Button btn = (Button)findViewById(R.id.btnConnect);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

                CustomTabsIntent customTabsIntent = new CustomTabsIntent.Builder().build();
                customTabsIntent.launchUrl(getApplicationContext(), Uri.parse(url));
            }
        });
    }

}


package com.jordan.fitbit_connect;

import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import com.squareup.picasso.Picasso;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class TestActivity extends AppCompatActivity
{

    //String to hold the data sent back by the Intent
    String string;

    //String to extract the token from 'string' above
    private static String token;

    //Strings to get the data from the JSON Object
    public static String name, avatar, age, weight, height;


    TextView username, txtAge, txtWeight, txtHeight, txtBMI;
    float bmi;
    ImageView imgViewAvatar;



    //-------------------------------------- START onNewIntent()------------------------------------
    /*
        This method returns the URI from the Intent as an encoded String
    */
    @Override
    protected void onNewIntent(Intent intent)
    {
        string = intent.getDataString();
    }
    //-------------------------------------- END onNewIntent()--------------------------------------

    //-------------------------------------- START onCreate()---------------------------------------
    /*
        Default method when the class is created
    */
    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test);
        onNewIntent(getIntent());

        token = string.substring(string.indexOf("&access_token")+36,308);



        Log.i("TAG", "Access Token: "+ token);
        Log.i("TAG", "Data String: " + string);

        //new JSONTask().execute("https://api.fitbit.com/1.2/user/-/sleep/date/2017-10-26.json");
        //new JSONTask().execute("https://api.fitbit.com/1/user/-/activities/steps/date/today/6m.json");
        new JSONTask().execute("https://api.fitbit.com/1/user/-/profile.json");


    }
    //-------------------------------------- END onCreate()-----------------------------------------



    //-------------------------------------- START of inner class JSONTask -------------------------
     public class JSONTask extends AsyncTask<String,String,String>
    {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            username = (TextView)findViewById(R.id.txtUser);
            imgViewAvatar = (ImageView)findViewById(R.id.imgViewAvatar);
            txtAge = (TextView)findViewById(R.id.txtAge);
            txtWeight = (TextView) findViewById(R.id.txtWeight);
            txtHeight = (TextView) findViewById(R.id.txtHeight);
            txtBMI = (TextView) findViewById(R.id.txtBMI);


        }

        //-------------------------------------- START doInBackground()-----------------------------
        /*
            This method is what happens on the background thread when the
            app is running. It will
        */
        @Override
        protected String doInBackground(String... params)
        {

            HttpURLConnection connection = null;
            BufferedReader reader = null;

            try
            {
                URL url = new URL(params[0]);
                connection = (HttpURLConnection)url.openConnection();
                connection.setRequestMethod("GET");
                connection.setDoOutput(false);
                connection.addRequestProperty("Authorization", "Bearer " + token);
                connection.connect();

                InputStream stream = (InputStream)connection.getInputStream();
                reader = new BufferedReader(new InputStreamReader(stream));

                StringBuffer buffer = new StringBuffer();

                String line = "";

                while((line = reader.readLine()) !=null)
                {
                    buffer.append(line);
                }

                return buffer.toString();

            } catch (MalformedURLException e)
            {

                e.printStackTrace();
            } catch (IOException e)
            {
                e.toString();
            }

            return null;

        }
        //-------------------------------------- END doInBackground()-------------------------------

        //-------------------------------------- START onPostExecute()------------------------------
        @Override
        protected void onPostExecute(String data)
        {
            super.onPostExecute(data);
            Log.i("TAG", data);




           try
            {

                //GET ALL THE JSON DATA
                JSONObject allData = new JSONObject(data);

                //GET THE USERNAME
                JSONObject userObject = allData.getJSONObject("user");
                name = userObject.getString("fullName");
                username.append(" "+name);

                //GET THE USER'S AVATAR
                avatar = userObject.getString("avatar640");
                Picasso.get().load(avatar).into(imgViewAvatar);

                //GET THE USER'S AGE
                age = userObject.getString("age");
                txtAge.append(" "+age);


                weight = userObject.getString("weight");
                txtWeight.append(" "+weight);
                float weightFloat = Float.parseFloat(weight);

                height = userObject.getString("height");
                txtHeight.append(" "+height);
                float heightFloat= Float.parseFloat(height)/100;

                bmi = (float)(weightFloat/(heightFloat * heightFloat));


                if(bmi <= 16)
                {
                    txtBMI.setTextColor(Color.YELLOW);
                    txtBMI.append(" "+ String.valueOf(bmi) + " - You are severely underweight!");
                }
                else if(bmi <= 18.5)
                {
                    txtBMI.setTextColor(Color.GRAY);
                    txtBMI.append(" "+ String.valueOf(bmi) + " - You are underweight!");
                }
                else if(bmi <= 25)
                {
                    txtBMI.setTextColor(Color.GREEN);
                    txtBMI.append(" "+ String.valueOf(bmi) + " - Your weight is normal");
                }
                else if(bmi <= 30)
                {
                    txtBMI.setTextColor(Color.parseColor("#FFA500"));
                    txtBMI.append(" "+ String.valueOf(bmi) + " - You are overweight!");
                }
                else
                {
                    txtBMI.setTextColor(Color.RED);
                    txtBMI.append(" " + String.valueOf(bmi) + " - You are obese!");
                }






               // for(int i =0; i< userObject.length(); i++) {
                    //3.DECLARE ANOTHER JSONOBJECT THAT EXTRACTS THE OBECT FROM THE SPECIFIED ARRAY
                    //JSONObject sleep = sleepArray.getJSONObject(i);

                    //4.Then use a getString to get the data from the object
                    //name = userObject.getString("firstName");
                   // Log.i("TAG",name);


            }
            catch (JSONException e)
            {
                e.printStackTrace();
            }
        }
    }
    //-------------------------------------- END of inner class JSONTask ---------------------------
}

1 个答案:

答案 0 :(得分:0)

在不同的Activity中使用AsynTask的方法之一,创建一个回调接口。

创建回调界面

interface AsyncTaskListener<T> {
    public void onComplete(T result);
}

然后在您的 MainActivity TestActivity中:

public class MainActivity extends AppCompatActivity
       implements AsyncTaskListener<String> {

      public void onComplete(String result) {
              // your staff here
      }
}

public class TestActivity extends AppCompatActivity
       implements AsyncTaskListener<String> {

      public void onComplete(String result) {
              // your staff here
      }
}

并添加到您的 AsyncTask 类:

public class JSONTask extends AsyncTask<String, String, String>
    private AsyncTaskListener<String> listener;

    public JSONTask (AsyncTaskListener<String> callback) {
        this.listener = callback;
}

    protected void onPostExecute(String result) {
        listener.onComplete(result);  // calling onComplate interface
    }