Posts Tagged ‘mobile’

English: A download symbol.

When our application does a task that takes a considerable amount of time, it is common sense to show the progress of the task to the user.
This is a good User Experience practice. In this tutorial i will be discussing the implementation of a process-progress dialog.

As an example, i am displaying a progress bar that runs while the app downloads an image from the web. And once the image is downloaded
completely i am showing the image in a image view. You could modify this example and try it with any file type you may wish. That could be fun!

Download Code

Creating new Project

1. Create a new project and fill all the details. File ⇒ New ⇒ Android Project
2. Open your main.xml are create a button to show download progress bar. Also define a ImageView to show downloaded image. Paste the following code in your main.xml

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" >
    <!-- Download Button -->
    <Button android:id="@+id/btnProgressBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Download File with Progress Bar"
        android:layout_marginTop="50dip"/>
    <!-- Image view to show image after downloading -->
    <ImageView android:id="@+id/my_image"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

3. Now in your main activity class import necessary classes and buttons. I am starting a new asynctask to download the file after clicking on show progress bar button.

public class AndroidDownloadFileByProgressBarActivity extends Activity {
    // button to show progress dialog
    Button btnShowProgress
    // Progress Dialog
    private ProgressDialog pDialog;
    // Progress dialog type (0 - for Horizontal progress bar)
    public static final int progress_bar_type = 0;
    // File url to download
    private static String file_url = "http://api.androidhive.info/progressdialog/hive.jpg";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // show progress bar button
        btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
        // Image view to show image after downloading
        my_image = (ImageView) findViewById(R.id.my_image);
        /**
         * Show Progress bar click event
         * */
        btnShowProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // starting new Async Task
                new DownloadFileFromURL().execute(file_url);
            }
        });
    }

4. Progress Dialog can be shown using ProgressDialog class. It is a subclass of normal AlertDialog class. So add an alert method in your main activity class.

/**
 * Showing Dialog
 * */
@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case progress_bar_type:
        pDialog = new ProgressDialog(this);
        pDialog.setMessage("Downloading file. Please wait...");
        pDialog.setIndeterminate(false);
        pDialog.setMax(100);
        pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
        pDialog.setCancelable(true);
        pDialog.show();
        return pDialog;
    default:
        return null;
    }
}

5. Now we need to add our Async Background thread to download file from url. In your main activity add a asynctask class and name it as DownloadFileFromURL(). After downloading image from the web i am reading the downloaded image from the sdcard and displaying in a imageview.

/**
 * Background Async Task to download file
 * */
class DownloadFileFromURL extends AsyncTask<String, String, String> {
    /**
     * Before starting background thread
     * Show Progress Bar Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(progress_bar_type);
    }
    /**
     * Downloading file in background thread
     * */
    @Override
    protected String doInBackground(String... f_url) {
        int count;
        try {
            URL url = new URL(f_url[0]);
            URLConnection conection = url.openConnection();
            conection.connect();
            // getting file length
            int lenghtOfFile = conection.getContentLength();
            // input stream to read file - with 8k buffer
            InputStream input = new BufferedInputStream(url.openStream(), 8192);
            // Output stream to write file
            OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
            byte data[] = new byte[1024];
            long total = 0;
            while ((count = input.read(data)) != -1) {
                total += count;
                // publishing the progress....
                // After this onProgressUpdate will be called
                publishProgress(""+(int)((total*100)/lenghtOfFile));
                // writing data to file
                output.write(data, 0, count);
            }
            // flushing output
            output.flush();
            // closing streams
            output.close();
            input.close();
        } catch (Exception e) {
            Log.e("Error: ", e.getMessage());
        }
        return null;
    }
    /**
     * Updating progress bar
     * */
    protected void onProgressUpdate(String... progress) {
        // setting progress percentage
        pDialog.setProgress(Integer.parseInt(progress[0]));
   }
    /**
     * After completing background task
     * Dismiss the progress dialog
     * **/
    @Override
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after the file was downloaded
        dismissDialog(progress_bar_type);
        // Displaying downloaded image into image view
        // Reading image path from sdcard
        String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
        // setting downloaded into image view
        my_image.setImageDrawable(Drawable.createFromPath(imagePath));
    }
}

6. Open your AndroidManifest.xml file and add internet connect permission and writing to sdcard permission.

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
    package="com.example.androidhive"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="8" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".AndroidDownloadFileByProgressBarActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <!-- Permission: Allow Connect to Internet -->
    <uses-permission android:name="android.permission.INTERNET" />
    <!-- Permission: Writing to SDCard -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>

7. Run your Application and click on show progress bar button to see your progress bar. You can see the downloaded image in imageView once it is downloaded.

android download file and showing progress bar

Final Code

package com.example.androidhive;
import java.io.BufferedInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class AndroidDownloadFileByProgressBarActivity extends Activity {
    // button to show progress dialog
    Button btnShowProgress;
    // Progress Dialog
    private ProgressDialog pDialog;
    ImageView my_image;
    // Progress dialog type (0 - for Horizontal progress bar)
    public static final int progress_bar_type = 0;
    // File url to download
    private static String file_url = "http://api.androidhive.info/progressdialog/hive.jpg";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        // show progress bar button
        btnShowProgress = (Button) findViewById(R.id.btnProgressBar);
        // Image view to show image after downloading
        my_image = (ImageView) findViewById(R.id.my_image);
        /**
         * Show Progress bar click event
         * */
        btnShowProgress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // starting new Async Task
                new DownloadFileFromURL().execute(file_url);
            }
        });
    }
    /**
     * Showing Dialog
     * */
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type: // we set this to 0
            pDialog = new ProgressDialog(this);
            pDialog.setMessage("Downloading file. Please wait...");
            pDialog.setIndeterminate(false);
            pDialog.setMax(100);
            pDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            pDialog.setCancelable(true);
            pDialog.show();
            return pDialog;
        default:
            return null;
        }
    }
    /**
     * Background Async Task to download file
     * */
    class DownloadFileFromURL extends AsyncTask<String, String, String> {
        /**
         * Before starting background thread
         * Show Progress Bar Dialog
         * */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            showDialog(progress_bar_type);
        }
        /**
         * Downloading file in background thread
         * */
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // this will be useful so that you can show a tipical 0-100% progress bar
                int lenghtOfFile = conection.getContentLength();
                // download the file
                InputStream input = new BufferedInputStream(url.openStream(), 8192);
                // Output stream
                OutputStream output = new FileOutputStream("/sdcard/downloadedfile.jpg");
                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // publishing the progress....
                    // After this onProgressUpdate will be called
                    publishProgress(""+(int)((total*100)/lenghtOfFile));
                    // writing data to file
                    output.write(data, 0, count);
                }
                // flushing output
                output.flush();
                // closing streams
                output.close();
                input.close();
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return null;
        }
        /**
         * Updating progress bar
         * */
        protected void onProgressUpdate(String... progress) {
            // setting progress percentage
            pDialog.setProgress(Integer.parseInt(progress[0]));
       }
        /**
         * After completing background task
         * Dismiss the progress dialog
         * **/
        @Override
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after the file was downloaded
            dismissDialog(progress_bar_type);
            // Displaying downloaded image into image view
            // Reading image path from sdcard
            String imagePath = Environment.getExternalStorageDirectory().toString() + "/downloadedfile.jpg";
            // setting downloaded into image view
            my_image.setImageDrawable(Drawable.createFromPath(imagePath));
        }
    }
}

The App Engine Cron Service allows you to configure regularly scheduled tasks that operate at defined times or regular intervals. These tasks are commonly known as cron jobs. These cron jobs are automatically triggered by the App Engine Cron Service. For instance, you might use this to send out a report email on a daily basis, to update some cached data every 10 minutes, or to update some summary information once an hour.

A cron job will invoke a URL, using an HTTP GET request, at a given time of day. A URL invoked by cron is subject to the same limits and quotas as a normal HTTP request, including the request time limit. Cron jobs run only for the default version of your application.

For example:

web.xml :

<!--?xml version="1.0" encoding="UTF-8"?> xmlns="http://java.sun.com/xml/ns/javaee"

xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance&#8221;

           xsi:schemaLocation="http://java.sun.com/xml/ns/javaee

http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&#8221;

           version="2.5">

<context-param>

<param-name>contextConfigLocation</param-name>

      /WEB-INF/applicationContext-quartz.xml</param-value>

</context-param>

 
</web-app>

ApplicationContext-quartz.xml:

<?xml version="1.0" encoding="UTF-8"?>

xmlns=http://www.springframework.org/schema/beans&#8221;

      xmlns:aop="http://www.springframework.org/schema/aop" 
    xmlns:tx="http://www.springframework.org/schema/tx"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
  http://www.springframework.org/schema/beans/spring-beans-2.0.xsd 
   http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd 
   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd">

<bean class=“org.springframework.scheduling.quartz.SchedulerFactoryBean”>

      <property name="triggers"> 
        <list> 
            // Add more cron job to be trigger.... 
        <ref local="userEngagementDailyJobTrigger"/> 
                ------2-----
                         -------3----- 
          <ref local="--n--"/> 
        </list> 
      </property> 
   </bean>

<bean id=“userEngagementDailyJob” class=“org.springframework.scheduling.quartz.JobDetailBean”>

      <property name="jobClass">
         <value>com.projectname.application.cron.UserEngagementDailyCron</value> 
     </property>
   </bean>

<bean id=“userEngagementDailyJobTrigger” class=“org.springframework.scheduling.quartz.CronTriggerBean”>

       <property name="jobDetail"> 
         <ref bean="userEngagementDailyJob"/> 
       </property> <property name="cronExpression">
              <!-- set a schedule time when to run the cron... (see the cron expression for time below)-->       
        <value>0 0/10 * * * ?</value>
       </property> 
    </bean> 
</beans>

package com.project_name.application.cron;

public class UserEngagementDailyCron extends QuartzJobBean implements org.quartz.StatefulJob{

Logger log=Logger.getLogger(UserEngagementDailyCron.class.getName());

  public void executeInternal(JobExecutionContext context){

try{

     UserEngagementService userEngagementService=(UserEngagementService)AppContext
                                              .getBean("userEngagementService"); 
  Date date=new Date(); 
  String fromDate=DateHelper.getDBFormat(DateHelper.substractDaysFromCalendarDate(date,
               MyWallSubscribe.DAILY_VALUE));
    String toDate=DateHelper.getDBFormat(date); 

  log.info("Started User Engagement Daily cron ");

List<User> users = userEngagementService.getMyWallSubscribeUsers(MyWallSubscribe.DAILY);

 
    for(User user:users){ 
    String body=userEngagementService.getMailTemplate(user, fromDate, toDate);

if(!body.equals(“”)){

          userEngagementService.sendMyWallMail(user, body,MyWallSubscribe.DAILY); 
    } 
  }

log.info(“Finished User Engagement Daily cron “);

  }

catch (Exception e) {

      // TODO: handle exception 
log.fatal("Error running DailyCron", e); 
} 
}

}

Cron expression for time :

#Expression                                 Meaning

# “0 0 12 * * ?” Fire at 12pm (noon) every day

# "0 15 10 ? * *"              Fire at 10:15am every day 
# "0 15 10 * * ?"              Fire at 10:15am every day 
# "0 15 10 * * ? *"            Fire at 10:15am every day 
# "0 15 10 * * ? 2005"         Fire at 10:15am every day during the year 2005 
# "0 * 14 * * ?"               Fire every minute starting at 2pm and ending at 2:59pm, every day 
# "0 0/5 14 * * ?"             Fire every 5 minutes starting at 2pm and ending at 2:55pm, every day 
# "0 0/5 14,18 * * ?"          Fire every 5 minutes starting at 2pm and ending at 2:55pm,  AND fire every
                             5 minutes starting at 6pm and ending at 6:55pm, every day 
# "0 0-5 14 * * ?"             Fire every minute starting at 2pm and ending at 2:05pm, every day 
# "0 10,44 14 ? 3 WED"         Fire at 2:10pm and at 2:44pm every Wednesday in the month of March. 
# "0 15 10 ? * MON-FRI"        Fire at 10:15am every Monday, Tuesday, Wednesday, Thursday and Friday 
# "0 15 10 15 * ?"             Fire at 10:15am on the 15th day of every month 
# "0 15 10 L * ?"              Fire at 10:15am on the last day of every month 
# "0 15 10 ? * 6L"             Fire at 10:15am on the last Friday of every month 
# "0 15 10 ? * 6L"             Fire at 10:15am on the last Friday of every month 
# "0 15 10 ? * 6L 2002-2005"   Fire at 10:15am on every last Friday of every month during the years 2002,
                             2003, 2004 and 2005 
# "0 15 10 ? * 6#3"           Fire at 10:15am on the third Friday of every month

It would be safe to say that nearly every mobile phone sold in the past decade has SMS messaging capabilities. In fact, SMS messaging is one great killer application for the mobile phone and it has created a steady revenue stream for mobile operators. Understanding how to use SMS messaging in your application can provide you with many ideas to create the next killer application.

 

In this article, we take a look at how you can programmatically send and receive SMS messages in your Android applications

 

English: SMS message received on a Motorola RA...

 

. The good news for Android developers is that you don’t need a real device to test out SMS messaging – the free Android emulator provides the capability to do so.

 

Sending SMS Messages

 

To get started, first launch Eclipse and create a new Android project. Name the project as shown in Figure 1.

 


Figure 1 Creating a new Android project using Eclipse

 

Android uses a permission-based policy where all the permissions needed by an application need to be specified in the AndroidManifest.xml file. By doing so, when the application is installed it will be clear to the user what specific access permissions are required by the application. For example, as sending SMS messages will potentially incur additional cost on the user’s end, indicating the SMS permissions in the AndroidManifest.xml file will let the user decide whether to allow the application to install or not.

 

In the AndroidManifest.xml file, add the two permissions – SEND_SMS and RECEIVE_SMS:

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>

 

In the main.xml file located in the res/layout folder, add the following code so that the user can enter a phone number as well as a message to send:

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="Enter the phone number of recipient"
        />     
    <EditText 
        android:id="@+id/txtPhoneNo"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"        
        />
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"         
        android:text="Message"
        />     
    <EditText 
        android:id="@+id/txtMessage"  
        android:layout_width="fill_parent" 
        android:layout_height="150px"
        android:gravity="top"         
        />          
    <Button 
        android:id="@+id/btnSendSMS"  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content"
        android:text="Send SMS"
        />    
</LinearLayout>

 

The above code creates the UI shown in Figure 2.

 


Figure 2 Creating the UI for sending SMS messages

 

Next, in the SMS activity, we wire up the Button view so that when the user clicks on it, we will check to see that the phone number of the recipient and the message is entered before we send the message using the sendSMS() function, which we will define shortly:

 

package net.learn2develop.SMSMessaging;

import android.app.Activity;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class SMS extends Activity 
{
    Button btnSendSMS;
    EditText txtPhoneNo;
    EditText txtMessage;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        

        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        txtPhoneNo = (EditText) findViewById(R.id.txtPhoneNo);
        txtMessage = (EditText) findViewById(R.id.txtMessage);

        btnSendSMS.setOnClickListener(new View.OnClickListener() 
        {
            public void onClick(View v) 
            {                
                String phoneNo = txtPhoneNo.getText().toString();
                String message = txtMessage.getText().toString();                 
                if (phoneNo.length()>0 && message.length()>0)                
                    sendSMS(phoneNo, message);                
                else
                    Toast.makeText(getBaseContext(), 
                        "Please enter both phone number and message.", 
                        Toast.LENGTH_SHORT).show();
            }
        });        
    }    
}

 

The sendSMS() function is defined as follows:

 

public class SMS extends Activity 
{
    //...

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        //...
    }

    //---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {        
        PendingIntent pi = PendingIntent.getActivity(this, 0,
            new Intent(this, SMS.class), 0);                
        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, pi, null);        
    }    
}

 

To send an SMS message, you use the SmsManager class. Unlike other classes, you do not directly instantiate this class; instead you will call the getDefault() static method to obtain an SmsManager object. The sendTextMessage() method sends the SMS message with a PendingIntent. The PendingIntent object is used to identify a target to invoke at a later time. For example, after sending the message, you can use a PendingIntent object to display another activity. In this case, the PendingIntent object (pi) is simply pointing to the same activity (SMS.java), so when the SMS is sent, nothing will happen.

 

If you need to monitor the status of the SMS message sending process, you can actually use two PendingIntent objects together with two BroadcastReceiver objects, like this:

 

    //---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {        
        String SENT = "SMS_SENT";
        String DELIVERED = "SMS_DELIVERED";

        PendingIntent sentPI = PendingIntent.getBroadcast(this, 0,
            new Intent(SENT), 0);

        PendingIntent deliveredPI = PendingIntent.getBroadcast(this, 0,
            new Intent(DELIVERED), 0);

        //---when the SMS has been sent---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS sent", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_GENERIC_FAILURE:
                        Toast.makeText(getBaseContext(), "Generic failure", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NO_SERVICE:
                        Toast.makeText(getBaseContext(), "No service", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_NULL_PDU:
                        Toast.makeText(getBaseContext(), "Null PDU", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case SmsManager.RESULT_ERROR_RADIO_OFF:
                        Toast.makeText(getBaseContext(), "Radio off", 
                                Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        }, new IntentFilter(SENT));

        //---when the SMS has been delivered---
        registerReceiver(new BroadcastReceiver(){
            @Override
            public void onReceive(Context arg0, Intent arg1) {
                switch (getResultCode())
                {
                    case Activity.RESULT_OK:
                        Toast.makeText(getBaseContext(), "SMS delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;
                    case Activity.RESULT_CANCELED:
                        Toast.makeText(getBaseContext(), "SMS not delivered", 
                                Toast.LENGTH_SHORT).show();
                        break;                        
                }
            }
        }, new IntentFilter(DELIVERED));        

        SmsManager sms = SmsManager.getDefault();
        sms.sendTextMessage(phoneNumber, null, message, sentPI, deliveredPI);        
    }

 

The above code uses a PendingIntent object (sentPI) to monitor the sending process. When an SMS message is sent, the first BroadcastReceiver‘s onReceive event will fire. This is where you check the status of the sending process. The second PendingIntent object (deliveredPI) monitors the delivery process. The second BroadcastReceiver‘s onReceive event will fire when an SMS is successfully delivered.

 

You can now test the application by pressing F11 in Eclipse. To send an SMS message from one emulator instance to another, simply launch another instance of the Android emulator by going to the Tools folder of the SDK and running Emulator.exe.

 


Figure 3 Sending an SMS message

 

Figure 3 shows how you can send an SMS message from one emulator to another; simply use the target emulator’s port number (shown in the top left corner of the window) as its phone number. When an SMS is sent successfully, it will display a “SMS sent” message. When it is successfully delivered, it will display a “SMS delivered” message. Note that for testing using the emulator, when an SMS is successfully delivered, the “SMS delivered” message does not appear; this only works for real devices.

 

Figure 4 shows the SMS message received on the recipient emulator. The message first appeared in the notification bar (top of the screen). Dragging down the notification bar reveals the message received. To view the entire message, click on the message.

 


Figure 4 The SMS message received by the Android emulator

 

If you do not want to go through all the trouble of sending the SMS message yourself, you can use an Intent object to help you send an SMS message. The following code shows how you can invoke the built-in SMS application to help you send an SMS message:

 

        Intent sendIntent = new Intent(Intent.ACTION_VIEW);
        sendIntent.putExtra("sms_body", "Content of the SMS goes here..."); 
        sendIntent.setType("vnd.android-dir/mms-sms");
        startActivity(sendIntent);

 

Figure 5 shows the built-in SMS application invoked to send the SMS message.

 


Figure 5 Invoking the built-in SMS application

 

Receiving SMS Messages

 

Besides programmatically sending SMS messages, you can also intercept incoming SMS messages using a BroadcastReceiver object.

 

To see how to receive SMS messages from within your Android application, in the AndroidManifest.xml file add the <receiver> element so that incoming SMS messages can be intercepted by the SmsReceiver class:

 

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="net.learn2develop.SMSMessaging"
      android:versionCode="1"
      android:versionName="1.0.0">
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".SMS"
                  android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>        

        <receiver android:name=".SmsReceiver"> 
            <intent-filter> 
                <action android:name=
                    "android.provider.Telephony.SMS_RECEIVED" /> 
            </intent-filter> 
        </receiver>

    </application>
    <uses-permission android:name="android.permission.SEND_SMS">
    </uses-permission>
    <uses-permission android:name="android.permission.RECEIVE_SMS">
    </uses-permission>
</manifest>

 

Add a new class file to your project and name it as SmsReceiver.java (see Figure 6).

 


Figure 6Adding the SmsReceiver.java file to the project

 

In the SmsReceiver class, extend the BroadcastReceiver class and override the onReceive() method:

 

package net.learn2develop.SMSMessaging;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class SmsReceiver extends BroadcastReceiver
{
	@Override
	public void onReceive(Context context, Intent intent) 
       {	
	}
}

 

When SMS messages are received, the onCreate() method will be invoked. The SMS message is contained and attached to the Intent object (intent – the second parameter in the onReceive() method) via a Bundle object. The messages are stored in an Object array in the PDU format. To extract each message, you use the static createFromPdu() method from the SmsMessage class. The SMS message is then displayed using the Toast class:

 

package net.learn2develop.SMSMessaging;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.gsm.SmsMessage;
import android.widget.Toast;public class SmsReceiver extends BroadcastReceiver
{
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        //---get the SMS message passed in---
        Bundle bundle = intent.getExtras();        
        SmsMessage[] msgs = null;
        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]);                
                str += "SMS from " + msgs[i].getOriginatingAddress();                     
                str += " :";
                str += msgs[i].getMessageBody().toString();
                str += "\n";        
            }
            //---display the new SMS message---
            Toast.makeText(context, str, Toast.LENGTH_SHORT).show();
        }                         
    }
}

 

That’s it! To test the application, press F11 in Eclipse. Deploy the application to each Android emulator. Figure 7 shows Eclipse showing the emulators currently running. All you need to do is to select each emulator and deploy the application onto each one.

 


Figure 7 Selecting an emulator/device to deploy the application onto

 

Figure 8 shows that when you send an SMS message to another emulator instance (port number 5556), the message is received by the target emulator and displayed via the Toast class.

 


Figure 8 Sending and receiving SMS messages using the Android emulators

 

Summary

 

In this article, you have seen how you can send and receive SMS messages programmatically from within your Android application. The capability to send and receive SMS messages is very useful as you can build very compelling applications. As an example, you can build a location tracker application where you can send a secret-coded SMS message to a device and when the device receives the secret SMS message it will reply with another SMS message containing its current geographical location using its built-in GPS receiver. How cool is that?!

 

Click the link below to download project source code

 

Attachment Size
SMSMessaging.zip 35.43 KB

 

Poor little android.. Dwarfed by Apple Devices...

 

While working on an Android App, I had to integrate the Camera API. User can take a photo from App and process it. With Android the Photo that you click cannot be accessed until the media scanner runs and index it. It is possible to triggeer programatically the Media Scanner in Android. Check the below code snippet:

 

import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
...
...
sendBroadcast (
    new Intent(Intent.ACTION_MEDIA_MOUNTED,
        Uri.parse("file://" + Environment.getExternalStorageDirectory()))
);
...

 

Here we are using sendBroadcast method from Activity class to send a broadcast message to an Intent. For our need we have used ACTION_MEDIA_MOUNTED intent which will invoke the media scanner. Also note that we have passed the path (URI) of our external storage directory.

 

So in your app whenever you want to trigger Media scanner, simply invoke the above intent via broadcast message.

 

Following is a Demo App to achieve this.

 

Demo App

 

The App will be very simple. It will have a button “Trigger Media Scanner”. On its click we will invoke the above sendBroadcast() code to trigger media scanner.

 

Step 1: Create Basic Android Project in Eclipse

 

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as MediaScannerDemo and select Android Runtime 2.1 or sdk 7. I have given package name net.viralpatel.android.mediascanner.

 

Once you are done with above steps, you will have a basic hello world Android App.

 

Step 2: Change the Layout

 

For our demo, we need simple layout. Just one button Trigger Image Scanner which does the job.

 

Open layout/main.xml in your android project and replace its content with following:

 

File: res/layout/main.xml

 

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:gravity="center">
    
    <Button
            android:id="@+id/buttonMediaScanner"
            android:layout_width="fill_parent"
            android:text="Trigger Media Scanner"
            android:textSize="25dp"
            android:layout_height="100dp"></Button>
</LinearLayout>

 

The UI is very simply. One LinearLayout to organize the button and one button. Note the id for button buttonMediaScanner which we will use in our Java code.

 

Step 3: Android Java Code to trigger Image Scanner Intent

 

Open MediaScannerDemoActivity class and add following code in OnCreate() method.

 

package net.viralpatel.android.mediascanner;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MediaScannerDemoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button buttonMediaScanner = (Button) findViewById(R.id.buttonMediaScanner);
        
        //Add onClick event on Media scanner button
        buttonMediaScanner.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                
                //Broadcast the Media Scanner Intent to trigger it
                sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
                        .parse("file://"
                                + Environment.getExternalStorageDirectory())));
                //Just a message
                Toast toast = Toast.makeText(getApplicationContext(),
                        "Media Scanner Triggered...", Toast.LENGTH_SHORT);
                toast.show();
            }
        });
    }
}

 

Thus in OnCreate() method, we have added an OnClickListener to button. In the listener class, we added logic to trigger media scanner and also a Toast message to show user that scanner has been triggered.

 

Screen shots of Android App

 

And that’s all! Just execute the app in Android emulator or real device and see following output.

 

android-media-scanner-trigger

 

On click of Trigger Media Scanner button, the media scanner is invoked which we can see in Title bar.
android media-scanner-app

 

Download Source Code

 

MediaScannerDemo.zip (45 KB)

 

OF + ZXing

Nowadays, Quick Response (QR) Codes are becoming more and more useful as they have gone mainstream, thanks to the smart phones. Right from the bus shelter, product packaging, home improvement store, automobile, a lot of internet websites are integrating QR Codes on their pages to let people quickly reach them. With increase in number of users of smart phones day by day, the QR codes usage is going up exponentially.

Let us see a quick overview of Quick Response (QR) codes and also how to generate these codes in Java.

Introduction to QR Codes

A QR code (abbreviated from Quick Response code) is a type of matrix barcode (or two-dimensional code) first designed for the automotive industry. More recently, the system has become popular outside of the industry due to its fast readability and comparatively large storage capacity. The code consists of black modules arranged in a square pattern on a white background. The information encoded can be made up of four standardized kinds (“modes”) of data (numeric, alphanumeric, byte/binary, Kanji), or by supported extensions virtually any kind of data.

Created by Toyota subsidiary Denso Wave in 1994 to track vehicles during the manufacturing process, the QR code is one of the most popular types of two-dimensional barcodes. It was designed to allow its contents to be decoded at high speed.

Hello World QR Code in Java

Zebra Crossing (ZXing) is an awesome open source library that one can use to generate / parse QR Codes in almost all the platforms (Android, JavaSE, IPhone, RIM, Symbian etc). But if you have to generate simple QR Codes, I found it a bit clumsy to implement.

However QRGen is a good library that creates a layer on top of ZXing and makes QR Code generation in Java a piece of cake. It has a dependency on ZXing, so you would need ZXing jar files along with QRGen to create QR Codes in Java.

On the download page of ZXing, you will not find the JAR files. Instead we have to create JAR files using the source code. I have already generated these JAR files. Here are the links:

zxing-core-1.7.jar (346 KB)
zxing-javase-1.7.jar (21 KB)

Also download the QRGen JAR File from their download page.

Include these JAR files in your Classpath and execute following Java code to generate QR Code.

package net.viralpatel.qrcode;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
public class Main {
    public static void main(String[] args) {
        ByteArrayOutputStream out = QRCode.from("Hello World")
                                        .to(ImageType.PNG).stream();
        try {
            FileOutputStream fout = new FileOutputStream(new File(
                    "C:\\QR_Code.JPG"));
            fout.write(out.toByteArray());
            fout.flush();
            fout.close();
        } catch (FileNotFoundException e) {
            // Do Logging
        } catch (IOException e) {
            // Do Logging
        }
    }
}

The code is pretty straight forward. We used QRCode class to generate QR Code Stream and write the byte stream to a file C:\QR_Code.JPG.

Download Source Code

QR_Code_Java.zip (339 KB)

If you open this JPEG file and scan using your iPhone or Android QR scanner, you’ll find a cool “Hello World” in it :)

Apart from generating Sterams of data using QRGen API, we can also use below APIs to create QR Codes:

// get QR file from text using defaults
File file = QRCode.from("Hello World").file();
// get QR stream from text using defaults
ByteArrayOutputStream stream = QRCode.from("Hello World").stream();
 
// override the image type to be JPG
QRCode.from("Hello World").to(ImageType.JPG).file();
QRCode.from("Hello World").to(ImageType.JPG).stream();
 
// override image size to be 250x250
QRCode.from("Hello World").withSize(250, 250).file();
QRCode.from("Hello World").withSize(250, 250).stream();
 
// override size and image type
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).file();
QRCode.from("Hello World").to(ImageType.GIF).withSize(250, 250).stream();

Website Link (URLs) QR Code in Java

One of the most common use of a QR Code is to bring traffic to a particular webpage or download page of website. Thus QR Code encodes a URL or website address which a user can scan using phone camera and open in their browser. URLs can be straight forward included in QR Codes. In above Java Hello World example, just replace “Hello World” string with the URL you want to encode in QR Code. Below is the code snippet:

ByteArrayOutputStream out = QRCode.from("http://viralpatel.net")
                .to(ImageType.PNG).stream();

QR Code in Servlet

Most of the time you would need to generate QR Codes dynamically in some website. We already saw how easy it is to generate QR code in Java. Now we will see how to integrate this QR Code generation in a Java Servlet.

Following is a simple Http Servlet that creates QR Code using QRGen and ZXing library. User provides the text for which QR Code is generated.

The index jsp file contains a simple html form with a textbox and submit button. User can enter the text that she wishes to generate QR code of and presses submit.

File: index.jsp

<html>
<head>
<title>QR Code in Java Servlet - viralpatel.net</title>
</head>
<body>
    
    <form action="qrservlet" method="get">
        <p>Enter Text to create QR Code</p>
        <input type="text" name="qrtext" />
        <input type="submit" value="Generate QR Code" />
    </form>
</body>
</html>

The magic happens in QRCodeServlet.java. Here we uses QRGen library along with ZXing and generates QR Code for given text (Text we get from request.getParameter). Once the QR Stream is generated, we write this to response and set appropriate content type.

File: QRCodeServlet.java

package net.viralpatel.qrcodes;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.glxn.qrgen.QRCode;
import net.glxn.qrgen.image.ImageType;
public class QRCodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        String qrtext = request.getParameter("qrtext");
        ByteArrayOutputStream out = QRCode.from(qrtext).to(
                ImageType.PNG).stream();
        
        response.setContentType("image/png");
        response.setContentLength(out.size());
        
        OutputStream outStream = response.getOutputStream();
        outStream.write(out.toByteArray());
        outStream.flush();
        outStream.close();
    }
}

The below web.xml simply maps QRCodeServlet.java with /qrservlet URL.

File: web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns="http://java.sun.com/xml/ns/javaee"
        xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
        id="WebApp_ID" version="2.5">
        
  <display-name>QR_Code_Servlet</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
    <servlet>
        <servlet-name>QRCodeServlet</servlet-name>
        <servlet-class>net.viralpatel.qrcodes.QRCodeServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>QRCodeServlet</servlet-name>
        <url-pattern>/qrservlet</url-pattern>
    </servlet-mapping>
    
</web-app>

Download Source Code

QR_Code_Servlet.zip (340 KB)

Output

qr-code-java-servlet-index

qr-code-java-servlet-image

 

Conclusion

Generating QR Codes in Java is not only easy, but quite straight forward. Integrating this functionality with any existing Java based app is just a piece of cake! In this tutorial we saw how to generate these QR codes in Java and also with Servlet.

Hope you’ll like this :)

English: Iceland, from the NASA Visible Earth ...

To start with let us see how to integrate Image Gallery with your App. Consider a requirement, you want your app user to select Image from the Gallery and use that image to do some stuff. For example, in Facebook app you can select Picture from your phone and upload directly to your profile.

Let us create an example with following requirement:

  1. First screen shows user with and Image view and a button to loan Picture.
  2. On click of “Load Picture” button, user will be redirected to Android’s Image Gallery where she can select one image.
  3. Once the image is selected, the image will be loaded in Image view on main screen.

So lets start.

Step 1: Create Basic Android Project in Eclipse

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as ImageGalleryDemo and select Android Runtime 2.1 or sdk 7.

Once you are done with above steps, you will have a basic hello world Android App.

Step 2: Change the Layout

For our demo, we need simple layout. One Image view to display user selected image and one button to trigger Image gallery.

Open layout/main.xml in your android project and replace its content with following:

File: res/layout/main.xml

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <ImageView
        android:id="@+id/imgView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_weight="1"></ImageView>
    <Button
        android:id="@+id/buttonLoadPicture"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_weight="0"
        android:text="Load Picture"
        android:layout_gravity="center"></Button>
</LinearLayout>

So our Android’s app UI is very simple, One LinearLayout to organize Image view and Button linearly. Note that the id of Image view is imgView and that of Button is buttonLoadPicture.

Step 3: Android Java Code to trigger Image Gallery Intent

We now need to write some Java code to actually handle the button click. On click of buttonLoadPicture button, we need to trigger the intent for Image Gallery.

Thus, on click of button we will trigger following code:

1
2
3
4
Intent i = new Intent(
Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, RESULT_LOAD_IMAGE);

Note how we passed an integer RESULT_LOAD_IMAGE to startActivityForResult() method. This is to handle the result back when an image is selected from Image Gallery.

So the above code will trigger Image Gallery. But how to retrieve back the image selected by user in our main activity?

Step 4: Getting back selected Image details in Main Activity

Once user will select an image, the method onActivityResult() of our main activity will be called. We need to handle the data in this method as follows:

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
 protected void onActivityResult(int requestCode, int resultCode, Intent data) {
     super.onActivityResult(requestCode, resultCode, data);
     
     if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
         Uri selectedImage = data.getData();
         String[] filePathColumn = { MediaStore.Images.Media.DATA };
         Cursor cursor = getContentResolver().query(selectedImage,
                 filePathColumn, null, null, null);
         cursor.moveToFirst();
         int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
         String picturePath = cursor.getString(columnIndex);
         cursor.close();
                     
         // String picturePath contains the path of selected Image
     }

Note that method onActivityResult gets called once an Image is selected. In this method, we check if the activity that was triggered was indeed Image Gallery (It is common to trigger different intents from the same activity and expects result from each). For this we used RESULT_LOAD_IMAGE integer that we passed previously to startActivityForResult() method.

Final Code

Below is the final code of ImageGalleryDemoActivity class.

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
package net.viralpatel.android.imagegalleray;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class ImageGalleryDemoActivity extends Activity {
    
    
    private static int RESULT_LOAD_IMAGE = 1;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
        buttonLoadImage.setOnClickListener(new View.OnClickListener() {
            
            @Override
            public void onClick(View arg0) {
                
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
    }
    
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
            Uri selectedImage = data.getData();
            String[] filePathColumn = { MediaStore.Images.Media.DATA };
            Cursor cursor = getContentResolver().query(selectedImage,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            String picturePath = cursor.getString(columnIndex);
            cursor.close();
            
            ImageView imageView = (ImageView) findViewById(R.id.imgView);
            imageView.setImageBitmap(BitmapFactory.decodeFile(picturePath));
        
        }
    
    
    }
}

Screen shots of Android app

First screen: Lets user to trigger Image Gallery
android-gallery-intent-example

User can select an image from Image Gallery
android-gallery-intent-select-image

Once user selects an image, the same will be displayed on our main activity
android-gallery-intent-example-demo

Download Source Code

ImageGalleryDemo.zip (46 KB)

Screenshot of Android Emulator for SDK version...

By default when you create an Android Virtual Devices (AVD) in Android, the Camera is disabled. So if your application uses Camera API, it might not work properly in Android Emulator. Also SDCard must be defined in emulator in order to use Camera.

To enable Camera in your Android Emulator, just add following highlighted code in your AVD’s config.ini file. You can find the config.ini file under your user directory/.android folder.

File: ~/.android/config.ini

hw.lcd.density=160
skin.name=HVGA
skin.path=platforms\android-9\skins\HVGA
hw.cpu.arch=arm
abi.type=armeabi
vm.heapSize=24
image.sysdir.1=platforms\android-9\images\
hw.camera=yes
sdcard.size=64M
...
...

In case you don’t find the config.ini file or want to enable Camera support through Android SDK and AVD Manager, follow below simple steps.

Open Android SDK and AVD Manager:

Step 1: Add SD Card in AVD

In the SD Card setting, set the value for Size. To enable camera, the SD Card must be enabled in Emulator.
android-emulator-sdcard-size

Step 2: Add Camera Support in Hardware under AVD

Now under Hardware section, click New button to add Camera hardware. It will open following Dialog box. Select Camera support from the Property dropdown and click Ok.
android-emulator-hardware-camera-support

Step 3: Enable Camera Support in Hardware

The new hardware: Camera support is visible under Hardware section. Set its value to yes and save changes by pressing Edit AVD.
android-emulator-camera-enable-yes

And that’s all. Just save the changes and launch the emulator. You’ll be able to start Camera application and take snaps (Default android pic) through it.

 

Android has a very cool feature that still many developers dont know. Apps like Any.DO uses speech to text conversion feature quite creatively. In today’s world of Siri, voice commands are of utmost importance. Android natively provides feature of Speech to Text so why not to use it in our app!

I will show you how to use Android’s Speech to Text API in an application.

Let’s make our demo application.

Demo App

The App will be very simple. It will have a button with Mic symbol. On click of which we trigger Android’s Speech to Text Intent which shows a dialog to take speech input. The speech input is then converted into text. The text is then displayed in a text view.

Step 1: Create Basic Android Project in Eclipse

Create a Hello World Android project in Eclipse. Go to New > Project > Android Project. Give the project name as SpeechToTextDemo and select Android Runtime 2.1 or sdk 7. I have given package name net.viralpatel.android.speechtotextdemo.

Once you are done with above steps, you will have a basic hello world Android App.

Step 2: Change the Layout

For our demo, we need simple layout. Just one Image Button to trigger Speech to Text API and one TextView to display result text that is converted from speech.

Open layout/main.xml in your android project and replace its content with following:

File: res/layout/main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_toLeftOf="@+id/textView1"
    android:gravity="center"
    android:orientation="vertical" >
    <ImageButton
        android:id="@+id/btnSpeak"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:contentDescription="@string/speak"
        android:src="@android:drawable/ic_btn_speak_now" />
    <TextView
        android:id="@+id/txtText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginTop="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />
</LinearLayout>

The UI is very simply. One LinearLayout to organize the button and text view. Note the id for button: btnSpeak and text view: txtText which we will use in our Java code.

Step 3: Android Java Code to trigger Speech to Text API

Open SpeechToTextDemoActivity class and replace the code with following.

File: SpeechToTextDemoActivity.java

package net.viralpatel.android.speechtotextdemo;
import java.util.ArrayList;
import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
    protected static final int RESULT_SPEECH = 1;
    private ImageButton btnSpeak;
    private TextView txtText;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        txtText = (TextView) findViewById(R.id.txtText);
        btnSpeak = (ImageButton) findViewById(R.id.btnSpeak);
        btnSpeak.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(
                        RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL, "en-US");
                try {
                    startActivityForResult(intent, RESULT_SPEECH);
                    txtText.setText("");
                } catch (ActivityNotFoundException a) {
                    Toast t = Toast.makeText(getApplicationContext(),
                            "Opps! Your device doesn't support Speech to Text",
                            Toast.LENGTH_SHORT);
                    t.show();
                }
            }
        });
    }
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.activity_main, menu);
        return true;
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
        case RESULT_SPEECH: {
            if (resultCode == RESULT_OK && null != data) {
                ArrayList<String> text = data
                        .getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
                txtText.setText(text.get(0));
            }
            break;
        }
        }
    }
}

The heart of Speech to text Android API is package android.speech and specifically class android.speech.RecognizerIntent. Basically we trigger an Intent (android.speech.RecognizerIntent) which shows dialog box to recognize speech input. This Activity then converts the speech into text and send backs the result to our calling Activity. When we invoke android.speech.RecognizerIntent intent, we must use startActivityForResult() as we must listen back for result text.

Note how in above code we crate intent android.speech.RecognizerIntent and trigger it. Also we add one extra parameter using .putExtra() method. When invoking RecognizerIntent, we must provide extra RecognizerIntent.EXTRA_LANGUAGE_MODE. Here we are setting its value to en-US.

Since we triggered the RecognizerIntent via startActivityForResult(), we override method onActivityResult(int requestCode, int resultCode, Intent data) to handle the result data. The
RecognizerIntent will convert the speech input to text and send back the result as ArraList with key RecognizerIntent.EXTRA_RESULTS. Generally this list should be ordered in descending order of speech recognizer confidence. Only present when RESULT_OK is returned in an activity result. We just set the text that we got in result in text view txtText using txtText.setText().

One thing worth noting here is how to handle devices/android version that doesn’t support speech to text API. In such case, exception ActivityNotFoundException will be thrown when we try to start activity. In above example, we have catched this exception and displayed a message “Opps! Your device doesn’t support Speech to Text” using Toast.

Screen shots of Android App

And that’s all! Just execute the app in Android emulator or real device and see following output.

android-speech-to-text-api-demo

android-speech-to-text-activity

android-speech-to-text-conversion

android-speech-text

Download Source Code

Android_SpeechToTextDemo.zip (350 KB)

 

Image representing HTC as depicted in CrunchBase

One of the biggest complaints levelled at the HTC  is the severe lack of internal memory. There are ways around this, one of which is forcing downloaded apps to install to the SD Card. There are a couple of pre-requisites, but the process itself is relatively straight forward.

You’ll need HTC Sync installed (or at least the drivers that come with HTC Sync) and ADB (Android Debug Bridge) or the Android SDK. The SDK itself is a >100MB download and can be relatively difficult to install, however if you head here, look under the section entitled Mini SDK, click show, you can download a zip file called SDK-Tools.zip. Once downloaded, extract the contents of that folder to a folder of your choosing. I recommend somewhere easy, like C:\SDK-Tools as you’ll need to navigate to it via a command prompt later.

You’ll also need to enable USB Debugging on your phone, that’s easily enough done by heading to Settings -> Applications -> Development -> USB Debugging. You’ll get a warning message, but just ok that you’ll be fine.

Once you’ve done all the above, the process is as follows:

1. Connect the Phone to the PC in Charge Only mode
2. Open a command prompt (Start -> Run -> CMD, you’ll need to run as Administrator)

Pics for the ADB stuff below:

3. Navigate to the folder you extracted ADB to. In my case, the command would be “cd\SDK-Tools” (minus the quotes).

4. Type adb devices and press enter. You should then see the serial number of your phone displayed on screen. If you don’t check, that USB Debugging is enabled and you’re connected in Charge Only Mode.

5. Type adb shell, press enter.

6. Type pm setInstallLocation 2 press enter (it’s important you enter this exactly as written as it’s case sensitive)

7. Type Exit, then disconnect your phone.

8. PROFIT!

You can now move apps that are already on the handset to the SD Card. Head to Settings -> Applications -> Manage Applications -> All -> Click an app -> Move to SD Card. All new apps will install to the SD Card.

It’s worth mentioning that apps with active widgets cannot be moved and a certain portion app will remain on the phones data partition, but this goes a long way to assist with the lack of internal memory!

Image representing PayPal as depicted in Crunc...

Reference PayPal site.
This chapters describes how to cancel one, some, or all of your customers’ subscriptions.
Cancelling Individual Subscriptions
You can cancel a subscription by going to the Subscription Details page.
Go to the History subtab of the My Account tab, choose the Subscriptions field from the Show drop-down menu, and click the Submit button. Click on the link in the Status column to view the Subscription Details, and click the Cancel button on the Subscription Details page.
1.
Alice logs in to her PayPal account, and clicks on the Active link in the Status column for the subscription she wishes to cancel.
You can also get to the Subscription Details page by clicking on the In reference to link in the Transaction Details for any subscription payments you receive.
2.
To cancel this subscription, Alice can click the Cancel Subscription button and follow the on-screen instructions.
3.
The Subscription is now listed as Cancelled in Alice’s transaction history
Your subscribers can cancel their subscriptions by following the same steps. In addition, if you choose to add a Cancel Subscription button to your website, your subscribers may press it to cancel their subscriptions. A subscription may be cancelled up until the day of the next scheduled payment. If a subscriber attempts to cancel before payment is sent on the day of a scheduled payment, the payment will not be made.
Cancelling Multiple Subscriptions At Once
If you cancel an email address which has several subscriptions, all of the subscriptions will be cancelled.
To cancel a group of subscribers, go to the History subtab of the My Account tab, choose the Subscriptions field from the Show drop-down menu, and click the Submit button. Click on the link in the Status column to view the Subscription Details of one of your active subscribers. Click the Cancel Several Subscribers link at the bottom of the Subscription Details page to open the Mass Subscription Cancellation page.
To cancel several subscribers, you will need to upload a simple text file containing your subscribers’ email addresses (one email per line). Once your file has been read, confirm that we found the correct number of email addresses, and click the Cancel Subscriptions button.
To view the details of your Mass Subscription Cancellation, go to your history and click on the Status of the Mass Subscription Cancellation entry.
Note:
It may take up to one hour to process your cancellation.
Your mass subscription cancellation log may contain the following terms:
l
Total Emails: Number of email addresses uploaded from your file.
l
Emails Matched: Number of email addresses that matched an active subscription. These active subscriptions were then cancelled. Please note that if any email address had more than one active subscription, all of the subscriptions were cancelled.
l
Emails Not Matched: Number of email addresses that did not match with an active subscription. If the subscription was already completed or cancelled, it will be counted as “Not Matched.”
l
Successful Cancellations: Total number of subscriptions cancelled. Please note that this number may be higher than the number of emails matched if any email address had more than one active subscription.
For more details about your Mass Subscription Cancellation, click the View Details button on the Transaction Details page. You will be prompted to download a file containing more information.
Your downloaded mass subscription cancellation log may contain the following terms:
l
Email Address: Email of subscriber
l
Success: The subscription was successfully cancelled
l
Failed: The subscription was not cancelled. Failure reasons include:
l
Already cancelled
l
Already completed: The subscription was completed prior to the cancellation
l
Failed: General failure code
l
No Match: The email address did not match any of your subscriptions
l
Subscription ID: Unique ID for the subscription
l
Date Processed: Cancellation date