Sunday, December 23, 2012

Simple Mono Droid Entry point for new features.


One of the things I've needed, in order to create a rapid development environment, is an entry point that is extensible.    Using this setup, I was able to easily throw in new features at a running pace.


public static class Selector
    {
        public static void Selected (string component,Activity act,int Id)
        {
            switch (component) 
            {
                case "Participant List":
                    var intent = new Intent();
                    intent.SetClass(act, typeof (ParticipantListActivity));
                    intent.PutExtra("Type","");
                    intent.PutExtra("Id","");
                    act.StartActivity(intent);
                break;
                case "Child Detail":
                    var childintent = new Intent();
                    childintent.SetClass(act, typeof (ChildDetailsActivity));
                    childintent.PutExtra("currentChildId",Id);
                    act.StartActivity(childintent);
                break;
                case "Parent List":
                    var parentintent = new Intent();
                    parentintent.SetClass(act, typeof (ParentListActivity));
                    act.StartActivity(parentintent);
                break;
                case "Scanner":
                var scannerintent = new Intent();
                scannerintent.SetClass(act,typeof(ScannerActivity));
                act.StartActivity(scannerintent);
                break;
                case "School List":
                    var schoolintent = new Intent();
                    schoolintent.SetClass(act,typeof(SchoolListActivity));
                    act.StartActivity (schoolintent);
                break;
                case "Kiosk":
                var kioskintent = new Intent();
                kioskintent.SetClass(act,typeof(LocationListActivity));
                act.StartActivity(kioskintent);
                break;
                default:
                break;


            }
        }
    }


public class Main : ListActivity
    {
        ProgressDialog progress;

        string[] Entries = { "Participant List","Parent List","Scanner","Kiosk"};

        protected override void OnCreate (Bundle bundle)
        {
            base.OnCreate (bundle);
            SetContentView (Resource.Layout.TextViewItem);

            this.ListAdapter = new ArrayAdapter<string>(this,Android.Resource.Layout.SimpleListItem1,Entries);

        }

        protected override void OnStart ()
        {
            base.OnStart ();
        }

        protected override void OnResume ()
        {
            base.OnResume();
        }

        protected override void OnListItemClick (ListView l, View v, int position, long id)
        {

            string place = ((ArrayAdapter<string>)this.ListAdapter).GetItem(position);
        
            Selector.Selected(place,this,0);
        }
    }

Rest Sharp MonoDroid, Post in Body.

   I needed to add an item in the body of a post via RestSharp in Mono Droid.  Luckily, the way I've built things, doesn't really expose any endpoints via code, for this reference.  So here is the code.. if you want to know how to post an object in the body of a Rest Sharp request.

public static Credentials Login(Credentials credentials)
        {
            var client = new RestClient();
            var request = new RestRequest();
            request.Method = Method.POST;
            var json = JsonConvert.SerializeObject(credentials);
            request.AddParameter("application/json; charset=utf-8", json, ParameterType.RequestBody);
            request.Resource = ServiceBase+string.Format(Data.Service.Login);

            RestResponse<Credentials> response = (RestResponse<Credentials>)client.Execute<Credentials>(request);
            Credentials item = new Credentials();
            JsonConvert.PopulateObject(response.Content,item);
            return item;
        }

Pretty simple, yes? -smiles-

On Boot Receiver in MonoDroid.



Sometimes your samples, for the technology you are using don't have a great example for what you need to accomplish.

Here is a working example for a class that uses a BroadcastReceiver to receive the On Boot Completed Event, and then start an Activity.

Get into your solution.  Right click on your Project, select Options. Go to Mono for Android Applications :



This is your class. Feel free to tweak the Intent to your own Activity class that you wish to start.

    [BroadcastReceiver] 
    [IntentFilter(new string[] { Intent.ActionBootCompleted }, Priority = (int)IntentFilterPriority.HighPriority)]
    public class BootBroadcastReceiver : BroadcastReceiver {

        public override void OnReceive(Context context, Intent intent) {
            Intent startServiceIntent = new Intent();

            startServiceIntent.SetClass(context, typeof(Login));
            startServiceIntent.AddFlags(ActivityFlags.NewTask);
            context.StartActivity(startServiceIntent);
        }
    }

I thought I needed to modify the AndroidManifest.xml.  Boy, was that wrong.  Just use the Attributes.  They will make your broadcast receiver automatically respond to the event.

A good link to check out. Blue Stacks. Android on PC and Mac.

Friday, December 21, 2012

Some cross platform projects for Mono Develop.

I have to be careful with this blog, as it is labeled Android Development, however, I have made an application that works for both Android and IOS.  Now, keep in mind, you won't get all the features in Xamarin from this project in comparison to their Mono Droid / Mono Touch sdk's, but it does provide enough to make real applications.  MVC Style.

The Monocross Project

What I have found is, the best way to implement this sweet layer, is to make sure that your web services are truly restful.  If you are in .net land, and I assume you are, this means RIA Web Services, or the new .net 4.5 API, which is supported in Azure.. with the October 2012 Azure SDK.

In order to utilize this tool, I'll have to do some extensive reworking on my web service side.

I've already planned on doing it, but it will be delayed a little bit, due to side projects currently ongoing.

I've also looked at Cross platform Mobile Game Development environment.  Now, the real winner in this arena is Unity. Hands down.  They have the gear, and the right environment for full game development, but that comes at an expensive price tag.  A lot of people like doing homebrew in the XNA platform.  Currently, Mono Game.. supports 2D games.  It's working up for 3D games, but for my purposes.. Mono Game.. being free and all, works well enough to get my feet wet.  So I've been playing around there.

The Mono Game Project.

Thursday, December 20, 2012

Useful Mono Droid Snippets.


Nowdays, everybody loves JSON.  Truth is.. I feel it is much easier to use in some regards for Web, and Mobile projects than XML, but there is something to be said for both data formats.

This is a snippet for retrieving any web response in JSON, via Rest Sharp in a Mono Droid, or Mono Touch environment, that you can then parse with your JSON Deserializer (Whatever flavor you prefer, hopefully one that supports AsParallel()).

This isn't the code I am using anymore.  As the first security layer is in place.  Below I have a post semi-related to the 2nd security layer, which is semi in-progress.. involving X509 certificates.

I also have made a model for a web service that will provide all User Application management functions for all mobile applications that I'll be developing.  I prefer the cloud.  It's cheap, I don't need anyone other than myself.  (Even though I'm a pretty decent sys admin).

        private static RestClient CutDownBloat()
        {
            var client = new RestClient();
            client.AddHandler("application/json; charset=utf-8",new RestSharp.Deserializers.JsonDeserializer());
            return client;
        }
        private static RestResponse<Object> CutDownCode(string url)
        {
            var request = new RestRequest();
            request.Method = Method.GET;
            request.Resource = url;
            var client = CutDownBloat();
            RestResponse<Object> response = (RestResponse<Object>)client.Execute<Object>(request);
            return response;
        }


In order to make a true secure system for a mobile application, you need a unique ID for the device attempting to access your services.

Just getting a unique device ID is a key component.


This is a snippet that will return a Unique Device ID for Android devices.


public static class DeviceData
    {
        public static string getDeviceID(Context context)
        {
            TelephonyManager tm = (TelephonyManager) context.GetSystemService(Context.TelephonyService);
            return tm.DeviceId;
        }
    }

Sudden Change for the better.

Truth is, I've changed things up.  I dropped the native Java code.

I shifted to Xamarin.  The software for both MonoTouch and Mono Droid were about $800,
but I code faster.  Many things are re-usable.

I've added two new team members to the Developer Team.  I'm hoping for at least one more.

Here are some pictures from the new C# (Xamarin) Mono Develop application.

I also gave up on maintaining two separate code bases.  The mobile app, is now also the kiosk.

The staff will use tablets, or if I can sell the Board of Directors on it, they will use Mobile Phones.

A lot has changed, but I guess I'm just as dedicated.





Friday, November 2, 2012

WCF and Android combined!

So here is the screenshot. Data is being retrieved, and much progress has been made.

Wednesday, October 31, 2012

Barcode Integration.

Luckily, in some cases, I plan stuff out a bit in advance:

I integrated barcode scanning for the Youth Impact Mobile app, that the staff will have to carry on them.

Below are some screenshots and a couple great starting reference pages.  In total, it really took me no time to integrate barcode scanning via Intent.  I'd say 30 minutes.

This is ZXing's page for their Intent Integrator:

http://code.google.com/p/zxing/wiki/ScanningViaIntent

What they left out on the page (and I requested them to add to their page), was a link to this class:

http://code.google.com/p/zxing/source/browse/trunk/android-integration/src/com/google/zxing/integration/android/IntentResult.java?r=1273



Obviously, the first image is taken from my tablet.. the application itself is pretty plain right now, Haven't added in any of the fragments to modify the participants information, but I have a couple fragments for that in my other project that I'll migrate over.


  This is what the barcode looks like when it is captured by the Barcode app.

Saturday, October 27, 2012

Working with JSON and ListPreferences! Wooo Doggy, exciting!

So today, I made a preference screen, that dynamically pulled down JSON data.. and displayed it.

The issue with the Kiosks that it is resolving is pretty simple.  At read and respond, the person in charge wants to be able to see how long someone has been clocked in at their station.  Well, the current app didn't have any way really to give that information.  So, I added a web service method that would return that information for a given kiosk.  In .NET this was easy.  On the android side it took a little reading, and fiddling though.

This is how I do my HTTP requests.  I changed the URL to protect the innocent,
and it should allow me to use certificates in the headers eventually, so that only clients with
the right signature have access to the web service.

StringBuilder builder = new StringBuilder()
HttpClient client = new DefaultHttpClient();
HttpGet httpGet = new HttpGet("http://#####"+String.valueOf(arg0[0]));try {
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
    HttpEntity entity = response.getEntity();
    InputStream content = entity.getContent();
    BufferedReader reader = new BufferedReader(new InputStreamReader(content));
    String line;
    while ((line = reader.readLine()) != null) {
    builder.append(line);
   }
} else {
       }
} 
catch (ClientProtocolException e) {
 e.printStackTrace();
} 
catch (IOException e) {
e.printStackTrace();
}
return builder.toString();

This code, combined with this:

JSONArray jsonObject = new JSONArray(data);
ListPreference l = (ListPreference) findPreference("clocktimes");
CharSequence[] entries = new CharSequence[jsonObject.length()]
CharSequence[] entryValues = new CharSequence[jsonObject.length()];
for(int i = 0; i < jsonObject.length(); i++)
{
  JSONObject j = jsonObject.getJSONObject(i);
  entries[i] = (CharSequence) j.get("message");
  entryValues[i] = (CharSequence) String.valueOf(i);
}
l.setEntries(entries);
l.setEntryValues(entryValues);


Allowed me to customize a PreferenceScreen with a ListPreference inside to dynamically display data.

Keep in mind, there are going to be a lot of try / catches in there.. and you'll want to use that ASync task, that I mentioned in my post earlier.

Like so:


Monday, October 22, 2012

Start Application at Boot-up

So, I needed to add an autostart for the application for these Kiosks.

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

This goes below your <application> tag.

<receiver
        android:name=".StartMyServiceAtBootReceiver"
        android:enabled="true"
        android:exported="true"
        android:label="StartMyServiceAtBootReceiver">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
</receiver>

Then you add a class named "StartMyServiceAtBootReceiver" in your src folder of your Android Application project.  This is the code you should add for it.. assuming your main activity class is named: "MainActivity".

public class StartMyServiceAtBootReceiver extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
            Intent i = new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }
    }
}

Saturday, October 13, 2012

Background threads in Android.

Frequently, in Android, you need your application to actually "do" something.  Hey, it's an application, it's to be expected.  In Android, best practice dictates you don't use the main UI thread to do this. It makes your application non-responsive until the task completes.  In fact, a default Android Project won't even allow you to run things on the main thread. 

This is where your friendly ASyncTask comes in.   

This task below, takes an integer as input, and then the background thread then returns a string, the void method is where you can update your UI etc for the result, the string that is considered input for that method, is in fact the same string returned in the "doInBackground" method.

This code can be customized to take in whatever initial variable type, and whatever end variable type. (I.E. Modify "Integer" to "String")


private class task extends AsyncTask<Integer, Void, String> {

private Exception exception;

protected String doInBackground(Integer... arg0) 
{
   StringBuilder builder = new StringBuilder();
            
           
   return builder.toString();
}
protected void onPostExecute(String feed) throws NullPointerException 
{
            
}

}