【问题标题】:I have a problen whith AsyncTask class我对 AsyncTask 类有疑问
【发布时间】:2014-09-12 00:51:38
【问题描述】:

我是 android 编程新手,我有两个问题,一个是名为 RetrieveTokenTask() 的 AsyncTask 类中的一个问题,在这个类中,我得到一个用于访问 gmail 电子邮件帐户的令牌,当我调用 AsyncTask 类时创建一个无限循环和该应用程序的批准消息是打开和关闭的。

另一个问题是当我按下按钮撤销对数据的访问时,当我再次尝试登录应用程序时不显示包含数据的布局。

我是按照一些教程完成的。

任何帮助都会有所帮助。

感谢并为我的写作中的任何错误感到抱歉,但我的英语不好。

这个mi app的代码是下一个:

`protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

` ...

    //Initializing google plus api client
    mGoogleApiClient = new GoogleApiClient.Builder(this)
    .addConnectionCallbacks(this)
    .addOnConnectionFailedListener(this).addApi(Plus.API)
    .addScope(Plus.SCOPE_PLUS_LOGIN).build();

}

protected void onStart(){
    super.onStart();
    mGoogleApiClient.connect();
}

protected void onStop(){
    super.onStop();
    if(mGoogleApiClient.isConnected()){
        mGoogleApiClient.disconnect();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

@Override
public void onClick(View v) {
    switch(v.getId()){
    case R.id.btn_sign_in:
        signInWithGplus();
        break;
    case R.id.btn_sign_out:
        signOutFromGplus();
        break;
    case R.id.btn_revoke_access:
        revokeGplusAccess();
        break;
    }   
}

@Override
public void onConnectionFailed(ConnectionResult result) {
    if(!result.hasResolution()){
        GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 
                0).show();
        return;
    }

    if(!mIntentInProgress){
        //Store the connection for later usage
        mConnectionResult = result;

        if(mSignInClicked){
            // The user has already clicked 'sign-in' so we attempt to
            // resolve all
            // errors until the user is signed in, or they cancel.
            resolveSignInError();
        }
    }

}

@Override
public void onConnected(Bundle arg0) {
    mSignInClicked = false;
    Toast.makeText(this, "User is connected", Toast.LENGTH_LONG).show();

    // Get User's information
    getProfileInformation();

    // Update the UI after sign-in
    updateUI(true);     
}

@Override
public void onConnectionSuspended(int arg0) {
    mGoogleApiClient.connect();
    updateUI(false);
}

private void updateUI(boolean isSignedIn){
    if(isSignedIn){
        btnSignIn.setVisibility(View.GONE);
        btnSignOut.setVisibility(View.VISIBLE);
        btnRevokeAccess.setVisibility(View.VISIBLE);
        llProfileLayout.setVisibility(View.VISIBLE);
    }
    else {
        btnSignIn.setVisibility(View.VISIBLE);
        btnSignOut.setVisibility(View.GONE);
        btnRevokeAccess.setVisibility(View.GONE);
        llProfileLayout.setVisibility(View.GONE);
    }
}

/*
 * Sign-in into google
 */
private void signInWithGplus(){
    if(!mGoogleApiClient.isConnecting()){
        mSignInClicked = true;
        resolveSignInError();
    }
}

/*
 * Method to resolve any sign-in errors
 */
private void resolveSignInError(){
    if(mConnectionResult.hasResolution()){
        try{
            mIntentInProgress = true;
            mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
        }
        catch(SendIntentException e){
            mIntentInProgress = false;
            mGoogleApiClient.connect();
        }
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == RC_SIGN_IN) {
        mIntentInProgress = false;
        if (resultCode == RESULT_OK) {
            // Make sure the app is not already connected or attempting to connect
            if (!mGoogleApiClient.isConnecting() &&
                    !mGoogleApiClient.isConnected()) {
                mGoogleApiClient.connect();
            }
        }
    }
}

/*
 * User's information name, email, profile pic 
 */
private void getProfileInformation(){
    try{
        if(Plus.PeopleApi.getCurrentPerson(mGoogleApiClient) != null){
            Person currentPerson = Plus.PeopleApi.getCurrentPerson(mGoogleApiClient);

            String personName = currentPerson.getDisplayName();
            String perosnPhotoUrl = currentPerson.getImage().getUrl();
            String personGooglePlusProfile = currentPerson.getUrl();
            String email = Plus.AccountApi.getAccountName(mGoogleApiClient);

            Log.e(TAG, "Name: " + personName + ", plusProfile: "
                    + personGooglePlusProfile + ", email: " + email
                    + ", Image: " + perosnPhotoUrl);

            txtName.setText(personName);
            txtEmail.setText(email);
            perosnPhotoUrl = perosnPhotoUrl.substring(0,
                    perosnPhotoUrl.length() - 2)
                    + PROFILE_PIC_SIZE;

            new LoadProfileImage(imgProfilePic).execute(perosnPhotoUrl);

            new RetrieveTokenTask(txtToken).execute(email);
        }
        else{
            Toast.makeText(getApplicationContext(), 
                    "Person informations is null", Toast.LENGTH_LONG).show();
        }
    }
    catch(Exception e){
        e.printStackTrace();
    }
}

/*
 * Background Async task to load user profile picture from url
 */
private class LoadProfileImage extends AsyncTask<String, Void, Bitmap>{
    ImageView bmImage;

    public LoadProfileImage(ImageView bmImage){
        this.bmImage = bmImage;
    }

    @Override
    protected Bitmap doInBackground(String... urls) {
        String urldisplay = urls[0];
        Bitmap mIcon11 = null;

        try{
            InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
        }
        catch(Exception e){
            Log.e("Error", e.getMessage());
            e.printStackTrace();
        }
        return mIcon11;
    }

    protected void onPostExecute(Bitmap result){
        bmImage.setImageBitmap(result);
    }
}

/*
 * Sign-out from google 
 */
private void signOutFromGplus(){
    if(mGoogleApiClient.isConnected()){
        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
        mGoogleApiClient.disconnect();
        mGoogleApiClient.connect();
        updateUI(false);
    }
}

/*
 * Revoking access from google 
 */
private void revokeGplusAccess(){
    if(mGoogleApiClient.isConnected()){
        Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
        Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
            .setResultCallback(new ResultCallback<Status>() {

                @Override
                public void onResult(Status arg0) {
                    Log.e(TAG, "User acces revoked!");
                    mGoogleApiClient.connect();
                    updateUI(false);
                }
            });
    }
}

private class RetrieveTokenTask extends AsyncTask<String, Void, String> {
    TextViewTkn Tkn;

    private RetrieveTokenTask(TextView tkn){
        this.Tkn = tkn;
    }

    @Override
    protected String doInBackground(String... params) {
        String accountName = params[0];
        String scopes = "oauth2:https://www.googleapis.com/auth/gmail.compose";
        String token = null;
        try {
            token = GoogleAuthUtil.getToken(getApplicationContext(), accountName, scopes);
        } catch (IOException e) {
            Log.e(TAGTKN, e.getMessage());
        } catch (UserRecoverableAuthException e) {
            startActivityForResult(e.getIntent(), REQ_SIGN_IN_REQUIRED);
        } catch (GoogleAuthException e) {
            Log.e(TAGTKN, e.getMessage());
        }
        return token;
    }

    @Override
    protected void onPostExecute(String result) {
        txtToken.setText(result);
    }
}

【问题讨论】:

    标签: java android google-api google-api-client


    【解决方案1】:

    对于第二个问题,asynctask 不会多次运行。如果您尝试重新执行实例,它将不会运行。每次要执行时都必须创建新的 AsyncTask 实例。

    你最好在 doBackground 方法中设置一个断点并检查它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-06-20
      • 2020-12-30
      • 2017-02-22
      • 2019-05-06
      • 1970-01-01
      • 2020-10-17
      • 2021-05-23
      • 1970-01-01
      相关资源
      最近更新 更多