Skip to content

Instantly share code, notes, and snippets.

@dyadica

dyadica/About Secret

Last active March 14, 2017 10:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyadica/589674ae346932183d64a8e7083810f5 to your computer and use it in GitHub Desktop.
Save dyadica/589674ae346932183d64a8e7083810f5 to your computer and use it in GitHub Desktop.
Android and Azure Integration via Mobile Services
Android and Azure Integration via Mobile Services
Please Note: Azure Mobile Services has been superseded by Azure App Service Mobile Apps and is scheduled for removal from Azure.
To make use of this example; please add the following to gradle:
compile 'com.microsoft.azure:azure-mobile-services-android-sdk:2.0.3'
compile (group: 'com.microsoft.azure', name: 'azure-notifications-handler', version: '1.0.1', ext: 'jar')
Use of this code afforded capability to mark an event during workshop data capture. In this instance accelerometer data was disregarded.
package com.example.iost_mobile_android;
public class Device_1
{
/**
* Item Id
*/
@com.google.gson.annotations.SerializedName("id")
private String mId;
// Session Reference
@com.google.gson.annotations.SerializedName("session")
private String mSession;
// Accelerometer Values
@com.google.gson.annotations.SerializedName("acc_x")
private String mAccX;
@com.google.gson.annotations.SerializedName("acc_y")
private String mAccY;
@com.google.gson.annotations.SerializedName("acc_z")
private String mAccZ;
@com.google.gson.annotations.SerializedName("event")
private boolean mEvent;
// Device_1 Constructors
public Device_1(){
}
public Device_1(String id, String session, String accX, String accY, String accZ)
{
this.setId(id);
this.setSession(session);
this.setAccX(accX);
this.setAccY(accY);
this.setAccZ(accZ);
}
// Get and Set the class id value
public String getId(){
return mId;
}
public final void setId(String id){
mId = id;
}
// Get and set the event state
public boolean getEvent(){
return mEvent;
}
public final void setEvent(boolean event){
mEvent = event;
}
// Get and Set the class id value
public String getSession(){
return mSession;
}
public final void setSession(String session){
mSession = session;
}
// Get the class accelerometer values
public String getAccX(){
return mAccX;
}
public String getAccY(){
return mAccY;
}
public String getAccZ(){
return mAccZ;
}
// Set the class accelerometer values
public final void setAccX(String accX){
mAccX = accX;
}
public final void setAccY(String accY){
mAccY = accY;
}
public final void setAccZ(String accZ){
mAccZ = accZ;
}
}
package com.example.iost_mobile_android;
import java.net.MalformedURLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ExecutionException;
import android.app.Activity;
import android.app.AlertDialog;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import com.google.common.util.concurrent.FutureCallback;
import com.google.common.util.concurrent.Futures;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.SettableFuture;
import com.microsoft.windowsazure.mobileservices.MobileServiceClient;
import com.microsoft.windowsazure.mobileservices.http.NextServiceFilterCallback;
import com.microsoft.windowsazure.mobileservices.http.ServiceFilter;
import com.microsoft.windowsazure.mobileservices.http.ServiceFilterRequest;
import com.microsoft.windowsazure.mobileservices.http.ServiceFilterResponse;
import com.microsoft.windowsazure.mobileservices.table.MobileServiceTable;
import com.microsoft.windowsazure.mobileservices.table.query.Query;
import com.microsoft.windowsazure.mobileservices.table.query.QueryOperations;
import com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncContext;
import com.microsoft.windowsazure.mobileservices.table.sync.MobileServiceSyncTable;
import com.microsoft.windowsazure.mobileservices.table.sync.localstore.ColumnDataType;
import com.microsoft.windowsazure.mobileservices.table.sync.localstore.MobileServiceLocalStoreException;
import com.microsoft.windowsazure.mobileservices.table.sync.localstore.SQLiteLocalStore;
import com.microsoft.windowsazure.mobileservices.table.sync.synchandler.SimpleSyncHandler;
import org.w3c.dom.Text;
import static com.microsoft.windowsazure.mobileservices.table.query.QueryOperations.*;
public class MobileActivity extends Activity
{
// Mobile Service Client reference
private MobileServiceClient mClient;
// Mobile Service Table used to access data
private MobileServiceTable<Device_1> mDevice_1_Table;
// Progress spinner to use for table operations
private ProgressBar mProgressBar;
// Buttons
Button addItemButton;
Button eventButton;
EditText sessionText;
TextView pressedText;
// boolean flag for event
boolean eventPressed = false;
// The url of the Azure Mobile Service
private static final String azureURL = "<< Your URL Here >>";
// The key for the Azure Mobile Service
private static final String azureKEY = "<< Your Key Here >>";
/**
* Initializes the activity
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_to_do);
mProgressBar = (ProgressBar) findViewById(R.id.loadingProgressBar);
// Initialize the progress bar
mProgressBar.setVisibility(ProgressBar.GONE);
try
{
// Create the Mobile Service Client instance, using the provided
// Mobile Service URL and key
mClient = new MobileServiceClient(azureURL, azureKEY,
this).withFilter(new ProgressFilter());
// Get the device_1 Mobile Service Table instance
mDevice_1_Table = mClient.getTable(Device_1.class);
}
catch (MalformedURLException e)
{
createAndShowDialog(new Exception("There was an error creating the Mobile Service. Verify the URL"), "Error");
}
catch (Exception e)
{
createAndShowDialog(e, "Error");
}
// Create a ref to the add item button
addItemButton = (Button)findViewById(R.id.buttonAddToDo);
// Add a click action to the button
addItemButton.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View view) {
addItem(view);
}
});
// Create a ref to the session id field
sessionText = (EditText)findViewById(R.id.textSession);
}
/**
* Initializes the activity menu
*/
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Add a new item
*
* @param view
* The view that originated the call
*/
public void addItem(View view)
{
if (mClient == null) {
return;
}
// Create a new device_1 item to be added to the cloud
final Device_1 device_1 = new Device_1();
// Populate the device_1 item properties
// First populate the session id
device_1.setSession(sessionText.getText().toString());
// Next populate the event state
device_1.setEvent(eventPressed);
// Create some dummy data for the acc values
int min = 0;
int max = 360;
Random r = new Random();
// Create some random values to test the system
int x = r.nextInt(max - min + 1) + min;
int y = r.nextInt(max - min + 1) + min;
int z = r.nextInt(max - min + 1) + min;
// Populate the class with the random values
device_1.setAccX(String.valueOf(x));
device_1.setAccY(String.valueOf(y));
device_1.setAccZ(String.valueOf(z));
// Insert the new device_1 item
AsyncTask<Void, Void, Void> task = new AsyncTask<Void, Void, Void>()
{
@Override
protected Void doInBackground(Void... params)
{
try
{
final Device_1 entity = addItemInTable(device_1);
runOnUiThread(new Runnable() {
@Override
public void run() {
// Update GUI here if needed
}
});
}
catch (final Exception e)
{
createAndShowDialogFromTask(e, "Error");
}
return null;
}
};
runAsyncTask(task);
}
/**
* Add an item to the Mobile Service Table
*
* @param item
* The item to Add
*/
public Device_1 addItemInTable(Device_1 item) throws ExecutionException, InterruptedException
{
Device_1 entity = mDevice_1_Table.insert(item).get();
return entity;
}
/**
* Creates a dialog and shows it
*
* @param exception
* The exception to show in the dialog
* @param title
* The dialog title
*/
private void createAndShowDialogFromTask(final Exception exception, String title)
{
runOnUiThread(new Runnable() {
@Override
public void run() {
createAndShowDialog(exception, "Error");
}
});
}
/**
* Creates a dialog and shows it
*
* @param exception
* The exception to show in the dialog
* @param title
* The dialog title
*/
private void createAndShowDialog(Exception exception, String title)
{
Throwable ex = exception;
if(exception.getCause() != null){
ex = exception.getCause();
}
createAndShowDialog(ex.getMessage(), title);
}
/**
* Creates a dialog and shows it
*
* @param message
* The dialog message
* @param title
* The dialog title
*/
private void createAndShowDialog(final String message, final String title) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(message);
builder.setTitle(title);
builder.create().show();
}
/**
* Run an ASync task on the corresponding executor
* @param task
* @return
*/
private AsyncTask<Void, Void, Void> runAsyncTask(AsyncTask<Void, Void, Void> task)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
return task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
return task.execute();
}
}
private class ProgressFilter implements ServiceFilter
{
@Override
public ListenableFuture<ServiceFilterResponse> handleRequest(ServiceFilterRequest request, NextServiceFilterCallback nextServiceFilterCallback) {
final SettableFuture<ServiceFilterResponse> resultFuture = SettableFuture.create();
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mProgressBar != null) mProgressBar.setVisibility(ProgressBar.VISIBLE);
}
});
ListenableFuture<ServiceFilterResponse> future = nextServiceFilterCallback.onNext(request);
Futures.addCallback(future, new FutureCallback<ServiceFilterResponse>() {
@Override
public void onFailure(Throwable e) {
resultFuture.setException(e);
}
@Override
public void onSuccess(ServiceFilterResponse response) {
runOnUiThread(new Runnable() {
@Override
public void run() {
if (mProgressBar != null) mProgressBar.setVisibility(ProgressBar.GONE);
}
});
resultFuture.set(response);
}
});
return resultFuture;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment