为什么我的任务应用程序在android中失败

时间:2012-12-09 10:31:49

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

我对Android开发很新,我打算做一个与任务相关的应用程序,但是我在寻找完美的例子时面临很多困难。 我已经做了一周的研究并且生气了:( ...我希望你们能帮助我解决我的问题。

最初我在这里阅读了Google提供的任务文档,但无法获得成功,因此弃用了许多API。所以我直接继续从谷歌这里下载任务示例应用程序。

我能够在我的PC上成功构建应用程序,并且我已经从API控制台配置了AUTH。但我得到404禁止错误,它表示访问未配置。

当我在这个谷歌群组中搜索时,我找到了一个简单的示例示例,因为它描述了我在API控制台中启用的任务(也是日历我启用了更安全的一面)。我使用应用包名称和密钥库证书生成了API密钥。在这也我得到相同的404禁止错误,原因是访问没有配置。这是完整的代码。

package com.android.imran.gtasksample;

import com.google.api.client.extensions.android2.AndroidHttp;
import com.google.api.client.googleapis.auth.oauth2.draft10.GoogleAccessProtectedResource;
import com.google.api.client.googleapis.extensions.android2.auth.GoogleAccountManager;
import com.google.api.client.http.HttpResponse;
import com.google.api.client.http.HttpResponseException;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.json.JsonHttpRequest;
import com.google.api.client.http.json.JsonHttpRequestInitializer;
import com.google.api.client.json.jackson.JacksonFactory; 
import com.google.api.services.tasks.Tasks;
import com.google.api.services.tasks.TasksRequest;
import com.google.api.services.tasks.Tasks.Tasklists;
import com.google.api.services.tasks.model.Task;
import com.google.api.services.tasks.model.TaskList;
import com.google.api.services.tasks.model.TaskLists;

import android.accounts.Account;
import android.accounts.AccountManager;
import android.accounts.AccountManagerCallback;
import android.accounts.AccountManagerFuture;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.logging.Level;
import java.util.logging.Logger;

import org.apache.http.client.ClientProtocolException;

public class GTaskSample extends ListActivity {

    private static final Level LOGGING_LEVEL = Level.OFF;

    private static final String TAG = "GTaskSample";

    final String API_KEY = "AIzaSyDTNHitJIgg_ZP3rJM1uBsXs1_IZGLb_do";
    String AUTH_TOKEN_TYPE = "oauth2:https://www.googleapis.com/auth/tasks";

    private static final String PREF = "GTaskSamplePref";
    private static final int DIALOG_ACCOUNTS = 0;
    private static final int MENU_ACCOUNTS = 0;
    public static final int REQUEST_AUTHENTICATE = 0;

    private final HttpTransport transport = AndroidHttp
            .newCompatibleTransport();

    Tasks service;
    GoogleAccessProtectedResource accessProtectedResource = new GoogleAccessProtectedResource(
            null);

    // TODO: save auth token in preferences?
    GoogleAccountManager accountManager;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        service = Tasks.builder(transport, new JacksonFactory())
                .setApplicationName("Google-TasksSample")
                .setHttpRequestInitializer(accessProtectedResource)
                .setJsonHttpRequestInitializer(
                        new JsonHttpRequestInitializer() {

                            public void initialize(JsonHttpRequest request)
                                    throws IOException {
                                TasksRequest tasksRequest = (TasksRequest) request;
                                tasksRequest.setPrettyPrint(true);
                                tasksRequest.setKey(API_KEY);
                            }
                        }).build();




        accountManager = new GoogleAccountManager(this);
        Logger.getLogger("com.google.api.client").setLevel(LOGGING_LEVEL);
        gotAccount(false);


    }

    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_ACCOUNTS:
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setTitle("Select a Google account");
            final Account[] accounts = accountManager.getAccounts();
            final int size = accounts.length;
            String[] names = new String[size];
            for (int i = 0; i < size; i++) {
                names[i] = accounts[i].name;
            }
            builder.setItems(names, new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    gotAccount(accounts[which]);
                }
            });
            return builder.create();
        }
        return null;
    }

    void gotAccount(boolean tokenExpired) {
        SharedPreferences settings = getSharedPreferences(PREF, 0);
        String accountName = settings.getString("accountName", null);
        Account account = accountManager.getAccountByName(accountName);
        if (account != null) {
            if (tokenExpired) {
                accountManager.invalidateAuthToken(accessProtectedResource
                        .getAccessToken());
                accessProtectedResource.setAccessToken(null);
            }
            gotAccount(account);
            return;
        }
        showDialog(DIALOG_ACCOUNTS);
    }

    void gotAccount(final Account account) {
        SharedPreferences settings = getSharedPreferences(PREF, 0);
        SharedPreferences.Editor editor = settings.edit();
        editor.putString("accountName", account.name);
        editor.commit();
        accountManager.manager.getAuthToken(account, AUTH_TOKEN_TYPE, true,
                new AccountManagerCallback<Bundle>() {

                    public void run(AccountManagerFuture<Bundle> future) {
                        try {
                            Bundle bundle = future.getResult();
                            if (bundle.containsKey(AccountManager.KEY_INTENT)) {

                                Intent intent = bundle
                                        .getParcelable(AccountManager.KEY_INTENT);
                                intent.setFlags(intent.getFlags()
                                        & ~Intent.FLAG_ACTIVITY_NEW_TASK);
                                startActivityForResult(intent,
                                        REQUEST_AUTHENTICATE);
                            } else if (bundle
                                    .containsKey(AccountManager.KEY_AUTHTOKEN)) {
                                accessProtectedResource
                                        .setAccessToken(bundle
                                                .getString(AccountManager.KEY_AUTHTOKEN));
                                String authToken=bundle.getString(AccountManager.KEY_AUTHTOKEN).toString();
                                Log.d("TasksSample", "Autho Toke ="+authToken);
                                onAuthToken();
                            }
                        } catch (Exception e) {
                            handleException(e);
                        }
                    }
                }, null);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case REQUEST_AUTHENTICATE:
            if (resultCode == RESULT_OK) {
                gotAccount(false);
            } else {
                showDialog(DIALOG_ACCOUNTS);
            }
            break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_ACCOUNTS, 0, "Switch Account");
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        case MENU_ACCOUNTS:
            showDialog(DIALOG_ACCOUNTS);
            return true;
        }
        return false;
    }

    void handleException(Exception e) {
        e.printStackTrace();
        if (e instanceof HttpResponseException) {
            HttpResponse response = ((HttpResponseException) e).getResponse();
            int statusCode = response.getStatusCode();
            try {
                response.ignore();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
            //  should only try this once to avoid infinite loop
            if (statusCode == 401) {
                gotAccount(true);
                return;
            }
        }
        Log.e(TAG, e.getMessage(), e);
    }

    void onAuthToken() {
        try {
            insertTaskList();
            List<String> taskTitles = new ArrayList<String>();
            List<TaskList> taskLists = service.tasklists().list().execute()
                    .getItems();
            if (taskLists != null) {
                for (TaskList taskList : taskLists) {
                    List<Task> tasks = service.tasks().list(taskList.getId())
                            .execute().getItems();
                    if (tasks != null) {
                        for (Task task : tasks) {
                            taskTitles.add(task.getTitle());
                        }
                    } else {
                        taskTitles.add("No sub tasks.");
                    }
                }
            } else {
                taskTitles.add("No tasks.");
            }
            setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item,
                    taskTitles));

        } catch (IOException e) {
            Log.d(TAG, "Exception ::"+e.getMessage());
            handleException(e);
        }
        setContentView(R.layout.main_task);
    }

    public void addTaskListAction(View view){
        Thread thread=new Thread(new Runnable() {

            @Override
            public void run() {

                insertTaskList();
            }
        });
        thread.start();
    }

    private void insertTaskList(){
        //TODO: testing
        try{

        TaskList tempTaskList=new TaskList();
        tempTaskList.setTitle("Task List :-"+new Random().nextInt(30));
        TaskList newTaskList=service.tasklists().insert(tempTaskList).execute();
        Log.d(TAG, "Inserted TaskList ::"+newTaskList.toString());
        }catch(ClientProtocolException exp){
            Log.d(TAG, "ClientProtocolException msg="+exp.getMessage());
        }
        catch(Exception exp){
            Log.d(TAG, "Exception msg="+exp.getMessage());
            handleException(exp);
        }
    }
}

以下是此邮件list中的API控制台图片。我不能粘贴图像,因为我没有权限,我是这个论坛的新手

我正在做的错误是什么,为什么我无法检索特定帐户的任务?这种方法有误吗?建议我这个好技术。请不要忽略这封电子邮件。请

提前致谢 -Solo

0 个答案:

没有答案