/* * Copyright (c) 2013 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License.› */ package com.example.authsample; import java.io.IOException; import java.util.LinkedList; import java.util.List; import android.accounts.AccountManager; import android.app.FragmentManager; import android.content.Intent; import android.content.SharedPreferences; import android.os.Bundle; import android.preference.PreferenceManager; import android.view.View; import android.widget.EditText; import android.widget.Toast; import com.google.android.gms.gcm.GoogleCloudMessaging; import com.google.api.client.googleapis.extensions.android.gms.auth.GoogleAccountCredential; import com.google.cloud.backend.android.CloudBackendActivity; import com.google.cloud.backend.android.CloudBackendMessaging; import com.google.cloud.backend.android.CloudCallbackHandler; import com.google.cloud.backend.android.CloudEntity; import com.google.cloud.backend.android.Consts; import com.google.cloud.backend.android.CloudQuery.Order; import com.google.cloud.backend.android.CloudQuery.Scope; /** * Sample Guestbook app with Mobile Backend Starter. * */ public class MainActivity extends CloudBackendActivity { private static final int REQUEST_ACCOUNT_PICKER = 2; private static final String PREF_KEY_ACCOUNT_NAME = "PREF_KEY_ACCOUNT_NAME"; private static final String BROADCAST_PROP_DURATION = "duration"; private static final String BROADCAST_PROP_MESSAGE = "message"; private GoogleAccountCredential credential; // UI components private EditText mEditText; private View mSendBtn; // a list of posts on the UI List<CloudEntity> posts = new LinkedList<CloudEntity>(); // initialize UI @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); CloudBackendMessaging cloudBackend = getCloudBackend(); // create credential credential = GoogleAccountCredential.usingAudience(this, Consts.AUTH_AUDIENCE); cloudBackend.setCredential(credential); // get account name from the shared pref String accountName = PreferenceManager.getDefaultSharedPreferences(this).getString(PREF_KEY_ACCOUNT_NAME, null); if (accountName == null) { // let user pick an account startActivityForResult(credential.newChooseAccountIntent(), REQUEST_ACCOUNT_PICKER); return; // continue init in onActivityResult } else { credential.setSelectedAccountName(accountName); } mEditText = (EditText) findViewById(R.id.edit_text); mSendBtn = findViewById(R.id.send_btn); } /** * Returns account name selected by user, or null if any account is * selected. */ protected String getAccountName() { return credential == null ? null : credential.getSelectedAccountName(); } @Override protected void onDestroy() { GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this); gcm.close(); super.onDestroy(); } @Override protected void onPostCreate() { super.onPostCreate(); listAllPosts(); } /** * Handles callback from Intents like authorization request or account * picking. */ @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); switch (requestCode) { case REQUEST_ACCOUNT_PICKER: if (data != null && data.getExtras() != null) { // set the picked account name to the credential String accountName = data.getStringExtra(AccountManager.KEY_ACCOUNT_NAME); credential.setSelectedAccountName(accountName); // save account name to shared pref SharedPreferences.Editor e = PreferenceManager.getDefaultSharedPreferences(this).edit(); e.putString(PREF_KEY_ACCOUNT_NAME, accountName); e.commit(); } // post create initialization onPostCreate(); break; } } // execute query "SELECT * FROM Guestbook ORDER BY _createdAt DESC LIMIT 50" // this query will be re-executed when matching entity is updated private void listAllPosts() { // create a response handler that will receive the query result or an // error CloudCallbackHandler<List<CloudEntity>> handler = new CloudCallbackHandler<List<CloudEntity>>() { @Override public void onComplete(List<CloudEntity> results) { posts = results; updateGuestbookUI(); } @Override public void onError(IOException exception) { handleEndpointException(exception); } }; // execute the query with the handler getCloudBackend().listByKind("Guestbook", CloudEntity.PROP_CREATED_AT, Order.DESC, 50, Scope.FUTURE_AND_PAST, handler); } private void handleEndpointException(IOException e) { Toast.makeText(this, e.toString(), Toast.LENGTH_LONG).show(); mSendBtn.setEnabled(true); } // convert posts into string and update UI private void updateGuestbookUI() { FragmentManager manager = getFragmentManager(); PostListFragment f = (PostListFragment) manager.findFragmentById(R.id.fragment_list); f.setEntities(posts); } // post a new message to server public void onSendButtonPressed(View view) { // create a CloudEntity with the new post CloudEntity newPost = new CloudEntity("Guestbook"); newPost.put("message", mEditText.getText().toString()); // create a response handler that will receive the result or an error CloudCallbackHandler<CloudEntity> handler = new CloudCallbackHandler<CloudEntity>() { @Override public void onComplete(final CloudEntity result) { posts.add(0, result); updateGuestbookUI(); mEditText.setText(""); mSendBtn.setEnabled(true); } @Override public void onError(final IOException exception) { handleEndpointException(exception); } }; // execute the insertion with the handler getCloudBackend().insert(newPost, handler); mSendBtn.setEnabled(false); } // handles broadcast message and show a toast @Override public void onBroadcastMessageReceived(List<CloudEntity> l) { for (CloudEntity e : l) { String message = (String) e.get(BROADCAST_PROP_MESSAGE); int duration = Integer.parseInt((String) e.get(BROADCAST_PROP_DURATION)); Toast.makeText(this, message, duration).show(); } } }