Success Tips

Hello,

Just came across a very nice post titled as 9 Beliefs of Remarkably Successful People, http://www.inc.com/jeff-haden/9-beliefs-of-remarkably-successful-people.html
I found many of these beliefs very inspiring, so hope you will have the chance to read and get inspired from them too!

In titles:
1. Time doesn’t fill me. I fill time.
2. The people around me are the people I chose.
3. I have never paid my dues.
4. Experience is irrelevant. Accomplishments are everything.
5. Failure is something I accomplish; it doesn’t just happen to me.
6. Volunteers always win.
7. As long as I’m paid well, it’s all good.
8. People who pay me always have the right to tell me what to do.
9. The extra mile is a vast, unpopulated wasteland.

I would definitely suggest reading the whole post, not just the titles of the beliefs! Just summarized them here, cause this helps me (and maybe you as well) to further think about them!

Posted in Management | Tagged , | Leave a comment

Android mixing preferences with view widgets

Hello Android devs and fans!

It’s been a long time since my last post, cause I had to work hard on a project, but here I am again willing to share a lot of the technical info I gathered during all this period!

Some time ago, during the development of the settings for an Android app, I wanted to mix a preferences screen with another screen that only contained a list view. This task got quite complex, as the use of Fragments API seemed the only option, to me! As you might already know, the Fragments API can be used for prior to Honeycomb Android version, using the compatibility library! Unfortunately, I quickly started changing my activity containing the list view into a fragment, which I was going to embed in the new screen. Only later that I started thinking about the changes required for changing a PreferenceActivity into a fragment, I noticed the the PreferenceFragment class was not included in the support library, while this exists in the Android API for honeycomb Android and later. So, this really disappointed me and made me mad, based on that they intended to provide the full Fragments API for older Android version, but finally decided to leave out a little thing that can cause a lot of trouble! This became a barrier and made be revert back to the previous state.

After a while, it became a requirement of my project for a preferences screen to have some buttons at the bottom of the screen for canceling or saving the changes persistently! This was proved similar to the requirement described before, just I was a bit more lucky this time, or I thought of it in a different way, which probably helped me find a blog post about this (http://baroqueworksdev.blogspot.gr/2012/03/create-preferenceactivity-with-header.html)

So, I am summing up everything here:

1. Create a layout file that should include a list view (with attribute android:id=”@+id/android:list”) and any other view widget you need your screen to have. (main.xml)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <ListView
        android:id="@+id/android:list"
        android:layout_width="fill_parent"
        android:layout_height="0.0dp"
        android:layout_weight="1" >
    </ListView>

    <!-- Footer -->
    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        style="@android:style/ButtonBar" >

        <Button
            android:id="@+id/cancelBtn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"     
            android:layout_weight="1"
            android:text="@string/notification_cancel" />
        
        <Button
            android:id="@+id/saveBtn"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="@string/notification_save" />        
    </LinearLayout>

</LinearLayout>

2. Create a preferences xml file, from which any preferences will be attached to the screen. (preferences.xml)

<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

    <CheckBoxPreference
        android:key="@string/pref_enabled_key"
        android:summaryOff="@string/pref_enabled_summaryoff"
        android:summaryOn="@string/pref_enabled_summaryon"
        android:title="@string/pref_enabled_title" />

</PreferenceScreen>

3. You can now attach both the layout (containing the view widgets) and the preferences (that will replace the list view from the layout file).

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    addPreferencesFromResource(R.xml.preferences);
}

This is the way that I managed to put a static set of buttons below the preferences screen! Hope this will prove useful to you as well!

Enjoy!

Posted in Android | Tagged , , , , | Leave a comment

Android Service Performance Tip

Hi there!

While working on an Android project, I had modified a Service in a way that it didn’t stop itself anymore. This made me feel really embarrassed, when I found out that I had broken a critical rules, which I found in a very nice Android Best Practices presentation that I came across (http://www.slideshare.net/retomeier/being-epic-best-practices-for-building-android-apps). I confirmed that my Service was still running by visiting the running services page on the Android settings (Press Menu -> Manage Apps -> Running tab). There I noticed that a whole process was being kept awake because of this Service that was left running forever!

Indeed, the best use of a Service is made by starting it and ensuring that it will call selfStop(), when it reaches a certain state. This ensures that the service will keep running only for the period that it has real work to do (this might not stand in every Service use case, but still think a lot before concluding to let a Service run forever!). If a Service needs to start at different points in time to do some work, you can use the AlarmManager to wake the Service app, or register a BroadcastReceiver to instantiate the Service to do the required work.

So, probably there is always a better way to use a Service than let it run forever. In this way you respect the users of your application, who should really appreciate that you don’t drain their battery!

Happy coding!

Posted in Android | Tagged , , , , , , , | Leave a comment

Android LinearLayout gravity and layout_gravity explanation

Heya,

Just came across a really informative post about the difference between the gravity and the layout_gravity attributes for Android UI design. These attributes are very important for laying everything where you want and can become quite complex when you nest LinearLayouts.

Here is the post: http://sandipchitale.blogspot.com/2010/05/linearlayout-gravity-and-layoutgravity.html

If you have any issues with layouts, feel free to ask.
Good Luck!

Posted in Android | Tagged , , , , , | Leave a comment

SMS Content Providers and Delivery Reports

Hi there,

I am back again, after a busy development period that didn’t leave enough time to write a post. But still it helped me that I had taken notes of what I would like to post for!

As part of an Android project that I have been working on, was to implement an activity for sending quick SMS replies, with full support of delivery reports. The documentation was poor and the stackoverflow.com discussions can become confusing, when most of the people don’t have an official reference to base their answers on.
The fact that even Google developers and bloggers discourage the usage of Content Provider that are not documented, and may change between Android version or distributions without prior notice, made me mad (http://android-developers.blogspot.com/2010/05/be-careful-with-content-providers.html). There are so many applications on the market, trying to give a better experience with messaging on the Android Platform, whose stock SMS application looks very poor in functionality and easy of use. So, a question came to my mind: “How can a mobile platform owner decide to have a undocumented part of the Platform, when it comes to a so integral aspect of a mobile platform, the SMS?”. And what the platform owner decides to say is that this part of the platform is free to change, which would of course result in breaking all the applications that almost of the Android device user use in order to fill the gap of the poor stock SMS application.

I spent quit some time to implement the delivery reports reception and sms DB updates required for integrating well with the native or third-party SMS applications, where the SMS status that my application will be setting the SMS to will be one that will correctly describe the SMS status on the other SMS applications. So, I give you some of the code (of course its not all mine, I had to copy parts from online resources to end up with this code!) for senging SMS and handling the delivery reports.

public void sendMessage(String dest, String message) {

		SmsManager smsManager = SmsManager.getDefault();
		PendingIntent deliveryIntent = null, sentIntent = null;

		Uri smsUri = null;
		try {
			smsUri = addMessage(mContext.getContentResolver(), dest, mMessageText, null, mTimestamp, requestDeliveryReport, mThreadId);
		} catch (SQLiteException e) {
			// SqliteWrapper.checkSQLiteException(mContext, e);
		}

		if (requestDeliveryReport) {
			Intent delIntent = new Intent(ServiceSms.ACTION_MESSAGE_DELIVERY_STATUS);
			delIntent.putExtra(ServiceSms.EXTRA_SMS_URI, smsUri);
			deliveryIntent = PendingIntent.getBroadcast(mContext, 0, delIntent, 0);
		}
		Intent sIntent = new Intent(ServiceSms.ACTION_MESSAGE_SENT);
		sIntent.putExtra(ServiceSms.EXTRA_SMS_URI, smsUri);
		sentIntent = PendingIntent.getBroadcast(mContext, 0, sIntent, 0);

		smsManager.sendTextMessage(dest, mServiceCenter, message, sentIntent, deliveryIntent);

	}

public static Uri addMessage(ContentResolver resolver, String address, String body, Long date, long threadId) {
		
		final Uri CONTENT_URI = Uri.parse("content://sms/sent");
		ContentValues values = new ContentValues();

		values.put(ADDRESS, address);
		if (date != null) {
			values.put(DATE, date);
		}
		values.put(READ, read ? Integer.valueOf(1) : Integer.valueOf(0));
		values.put(BODY, body);
		if (threadId != -1L) {
			values.put(THREAD_ID, threadId);
		}

		return resolver.insert(uri, values);
	}

The above was just for sending an SMS and specifying how to be notified about initial status of the SMS (sentIntents) or the final status of the SMS (deliveryIntents). But to successfully receive these callback, you will need to register a BroadcastReceiver for the ACTION_MESSAGE_SENT action and the ACTION_MESSAGE_DELIVERY_STATUS action (these are some final strings with the namespace of my app, that I have defined). Because the reception of these events might need to be handled with queries to the SMS DB, you ll need to pass the intent to a Service to actually handle the events:

public class ServiceSms extends Service {

private final class ServiceHandler extends Handler {
		public ServiceHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			int serviceId = msg.arg1;
			Intent intent = (Intent) msg.obj;
			int resultCode = msg.arg2;
			String action = intent.getAction();
			String dataType = intent.getType();

			if (ACTION_MESSAGE_SENT.equals(action)) {
				handleSmsSent(intent, resultCode);
			} else if (ACTION_MESSAGE_DELIVERY_STATUS.equals(action)) {
				handleSmsDelivered(intent, resultCode);
			}
		}
}

private void handleSmsSent(Intent intent, int resultCode) {
		ContentValues values = null;
		Uri smsUri = null;
		if (intent != null && intent.getExtras() != null && intent.getExtras().getParcelable(EXTRA_SMS_URI) != null) {
			smsUri = (Uri) intent.getExtras().getParcelable(EXTRA_SMS_URI);
		}
		switch (resultCode) {
		case Activity.RESULT_OK:
			if (smsUri != null) {
				values = new ContentValues();

				SharedPreferences mPrefs = PreferenceManager.getDefaultSharedPreferences(mContext);
				boolean requestDeliveryReport = mPrefs.getBoolean(mContext.getString(R.string.pref_delivery_report_key), Boolean.valueOf(mContext.getString(R.string.pref_delivery_report_default)));
				if (requestDeliveryReport) {
					values.put(SmsMessageSender.STATUS, SmsMessageSender.STATUS_PENDING);
				} else {
					values.put(SmsMessageSender.STATUS, SmsMessageSender.STATUS_NONE);
				}

				getContentResolver().update(smsUri, values, null, null);
				mToastHandler.sendEmptyMessage(TOAST_MESSAGE_SENT);
			}
			break;
		case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
			if (smsUri != null) {
				values = new ContentValues();
				values.put(SmsMessageSender.STATUS, SmsMessageSender.STATUS_FAILED);
				getContentResolver().update(smsUri, values, null, null);
				mToastHandler.sendEmptyMessage(TOAST_MESSAGE_SENDING_FAILURE);
			}
			break;
		case SmsManager.RESULT_ERROR_NO_SERVICE:
			if (smsUri != null) {
				values = new ContentValues();
				values.put(SmsMessageSender.STATUS, SmsMessageSender.STATUS_FAILED);
				getContentResolver().update(smsUri, values, null, null);
				mToastHandler.sendEmptyMessage(TOAST_MESSAGE_SENDING_FAILURE);
			}
			break;
		case SmsManager.RESULT_ERROR_NULL_PDU:
			if (smsUri != null) {
				values = new ContentValues();
				values.put(SmsMessageSender.STATUS, SmsMessageSender.STATUS_FAILED);
				getContentResolver().update(smsUri, values, null, null);
				mToastHandler.sendEmptyMessage(TOAST_MESSAGE_SENDING_FAILURE);
			}
			break;
		case SmsManager.RESULT_ERROR_RADIO_OFF:
			if (smsUri != null) {
				values = new ContentValues();
				values.put(SmsMessageSender.STATUS, SmsMessageSender.STATUS_FAILED);
				getContentResolver().update(smsUri, values, null, null);
				mToastHandler.sendEmptyMessage(TOAST_MESSAGE_SENDING_FAILURE);
			}
			break;
		}
	}

	private void handleSmsDelivered(Intent intent, int resultCode) {
		ContentValues values = null;
		Uri smsUri = null;
		if (intent != null && intent.getExtras() != null && intent.getExtras().getParcelable(EXTRA_SMS_URI) != null) {
			smsUri = (Uri) intent.getExtras().getParcelable(EXTRA_SMS_URI);
		}

		switch (resultCode) {
		case Activity.RESULT_OK:
			if (smsUri != null) {
				values = new ContentValues();
				values.put(SmsMessageSender.STATUS, SmsMessageSender.STATUS_COMPLETE);
				getContentResolver().update(smsUri, values, null, null);
				mToastHandler.sendEmptyMessage(TOAST_MESSAGE_DELIVERED);
			}
			break;
		case Activity.RESULT_CANCELED:
			if (smsUri != null) {
				values = new ContentValues();
				values.put(SmsMessageSender.STATUS, SmsMessageSender.STATUS_FAILED);
				getContentResolver().update(smsUri, values, null, null);
				mToastHandler.sendEmptyMessage(TOAST_MESSAGE_DELIVERY_FAILURE);
			}
			break;
		}
	}

}

Hope these code samples will help you implement our own SMS sending functions with delivery reports support. But always remember that the API might change, resulting in your code being broken, so be ready for fast updates!

Good luck!

Posted in Android | Tagged , , , , , | 2 Comments

Android Flash Led Notifications

Hello Android funs!

As we all know, many android phones, first being the HTC Dream (which I am glad to own, although I now use it just for testing apps), are featuring a LED on the front side of the device. This LED light comes in use when a notification is shown, which is usually accompanied by a sound, an icon on the notifications status bar, a ticker text on the status bar and a View that is shown, when the notification area is expanded!

As already mentioned, not all android phones come with a LED light, so if you are a potential buyer of a device based on the Android Platform, you should check the device specs first.

Also, it seems that the “poor” LED light is not there to decorate the already nice looking notification Views that can be attached to the Notifications sent by an application to the NotificationManager. So, the LED light blinks only when the notification is not viewable, when the device is on sleep and the screen is off.
This is when you should expect the LED light to flash, when a notification has come up (which uses the LED feature), but the device is on sleep.

This was something that took me some time to find out, and wanted to share with you!
There are so many threads on-line directing to nothing useful, which made me think that this could be another undocumented and unstable feature, which no one has explained clearly. But this is probably not the case.

So, the final statement is: The LED light on Android phones (if exists), will flash only when the device is in sleep mode!

Have fun with Android Platform!

Posted in Android | Tagged , , , , , | Leave a comment

Locating Android native resources

Hello Android funs,

Yesterday I started looking for the default contact photo used in Android Contacts list, to use it in a contacts list that I am creating. Although, I already knew that many of Android resources can be referenced through the android.R package, I couldn’t find the image that I was looking for. After googleing, I found a page hosting all the drawables from the Android SDK 2.2 (http://androiddrawableexplorer.appspot.com/), another with drawables from the 1.5 SDK version (http://www.darshancomputing.com/android/1.5-drawables.html) and a nice app for developers that shows the list of drawables from the android.R package of the Android version it is running on(http://mgmblog.com/2008/12/12/listing-androids-drawable-resources/). All these references can prove very useful, cause using native images will make our apps look a bit more native, making the experience of the end-user better possible.

After all, when I opened the Android SDK location on my local disk, I noticed there is a subdirectory platforms/android-x/data/res/ where all the Android native drawables, colors, animations, layouts etc. are located. There is one such directory for each Android SDK version, located in the ANDROID_HOME/platforms/android-x/ directories. Through this list of drawables should find any drawable that you might be looking for. The problem is that not all of them can be publicly referenced through the android.R.drawable class (for unknown reason to me). So, if trying to access an image via the android.R.drawable does not give access to an image that you can locate inside the ANDROID_HOME/platforms/android-x/data/res/ directory, the last resort would be to copy that image to the application resources! I don’t know if there is another way, so if somebody does, please share your knowledge!

Posted in Android | Tagged , , , , , , | Leave a comment

Posting source code in WordPress hosted blog

Hi there!

Two days after my last post, I noticed that the example code from that post had been removed 😦
This is really bad, and proves me a bad tester! Hope to improve on this soon, which should be important for becoming a good blogger!

So, I decided to write a post in WordPress about writing posts on WordPress, which present any kind of source code! Sounds funny at first, but it is very useful for developers, who want to use the free version of the WordPress hosted blog to present examples of code to their subscribers! Thanks to a post on stackoverflow (http://stackoverflow.com/questions/1273647/how-do-i-add-syntax-highlighting-to-a-wordpress-blog-hosted-on-wordpress-com), I reached a link on the WordPress support site that described, how an internal code highlighting and formatting plug-in can be used, which is also available for the hosted WordPress version as well.

The obvious reason why WordPress strip off the source code that is being included in any post, is for security. They are mostly trying to avoid running javascript code, which could cause problems to the whole WordPress platform, that holds all the hosted blogs.

So, to accomplish presenting and highlighting source code in your WordPress blog, you should wrap your code in the following tags:

[sourcecode language=”css”]
your code here
[/sourcecode]

For making use of more options that this plug-in offers, you should get the information presented here:
http://en.support.wordpress.com/code/posting-source-code/

Happy Blogging!

Posted in Technology, Tips | Tagged , , , , , | 4 Comments

Using a State List Drawable as a button background image

Hi there!

As a response to a subscriber’s question, I decided to present an example of making use of the State List Drawable as a Button’s background image.

For using text and image on a Button widget, you can make use of the appropriate attributes, as in the following example:

<Button
        android:layout_height="wrap_content"
    	android:layout_width="wrap_content"
        android:background="@drawable/button_background"
        android:text="@string/button_text"/>

For the background drawable you can use either an image or a State List Drawable, which is actually an XML file defining the images that the button should use in each of its statuses. Here is an example:
– res/drawable/button_status_list_drawable.xml (the status list drawable, which will later be used as a drawable itself)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/pressed_img" android:state_pressed="true"/>
    <item android:drawable="@drawable/hovered_img" android:state_hovered="true"/>
    <item android:drawable="@drawable/default_img"/>    
</selector>

– main.xml (an example of how to refer to the state list drawable)

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >    
    <Button
        android:layout_height="wrap_content"
    	android:layout_width="wrap_content"
        android:background="@drawable/state_list_drawable"
        android:text="@string/button_text"/>
</LinearLayout>

Hope this post will help you with what you are trying to do! In any case, I would suggest you to have a look at the Android SDK documentation of the Button widget:
http://developer.android.com/reference/android/widget/Button.html

In case you need further help, don’t hesitate to contact me!

Posted in Android | Tagged , , , , , , | 1 Comment

Specifying UI dimensions in Android

I am back with a very useful tip that will prevent us from lot of trouble, when it comes to UI elements size on different screen sizes and screen density.

In order to ensure that a graphic or text looks good in every Android device, despite of the varying parameters of a phone (screen size and density), a relative meter has to be used (rather than absolute). As such, use sp (space-independent pixels) for fonts size, which takes into account the user’s font size preference, and dp (dots per pixel) for anything else, like a graphic or border.

From Android SDK documentation (http://developer.android.com/guide/topics/resources/more-resources.html#Dimension):
You should use these units when specifying view dimensions in your layout, so the UI properly scales to render at the same actual size on different screens. (The compiler accepts both “dip” and “dp“, though “dp” is more consistent with “sp“.)

Take care of your code!

Posted in Android | Tagged , , , , , , , | Leave a comment