I’m trying to build a app that uses the SmsMessage class but there are two versions depending on the API level of the device:
android.telephony.gsm.SmsMessage (deprecated for 1.6 and above)
android.telephony.SmsMessage (the new class for 1.6 and up)
I want to target 1.5 and yet have the newer class (android.telephony.SmsMessage) run on devices with 1.6 or higher. How do I do this?
I have already tired this: http://devtcg.blogspot.com/2009/12/gracefully-supporting-multiple-android.html but I couldn’t get it to work (the author doesn’t mention how he/she handles the different imports, the exact api level settings etc.)
Thanks.
import java.util.Date;
import com.apps.myapp.Utilities;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;//*NOTE* depreciated in v1.6+
public class OfflineSMSReceiver extends SMSReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
System.out.println("SMS_RECEIVED");
System.out.println(Utilities.getNow());
//---get the SMS message passed in---
Bundle bundle = intent.getExtras();
SmsMessage[] msgs = null;
Date date;
long timeStamp;
String time;
String str = "";
if (bundle != null)
{
//---retrieve the SMS message received---
Object[] pdus = (Object[]) bundle.get("pdus");
msgs = new SmsMessage[pdus.length];
for (int i=0; i<msgs.length; i++){
msgs[i] = SmsMessage.createFromPdu((byte[])pdus[i]);
timeStamp = msgs[i].getTimestampMillis();
date = new Date(timeStamp);
time = this.getTime(date.getHours(),date.getMinutes(),date.getSeconds());
str += "SMS from " + msgs[i].getOriginatingAddress();
str += " :";
str += msgs[i].getMessageBody().toString();
str += "\n";
str += "TIME: "+time+"\t"+this.getNowDate();
}
System.out.println(str);
}
}
}
You will need to target
android-4or higher, otherwise the newer class will not exist.With respect to loading in the correct version, you can use conditional class loading, demonstrated in this sample project for the two editions of the contacts content provider. Also, this article is what Google has to say on the subject.