Reading Inbox SMS Android

In this blog post you can learn on how to read an sms from inbox using android source code below.

1. Create the following java class for reading the inbox sms.

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;
public class SMSRead extends Activity {
  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      TextView view = new TextView(this);
      Uri uriSMSURI = Uri.parse("content://sms/inbox");
      Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
      String sms = "";
      while (cur.moveToNext()) {
          sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";         
      }
      view.setText(sms);
      setContentView(view);
  }
}

2. Add Uses Permission to the android manifest xml file.

<uses-permission name="android.permission.READ_SMS" />

Blocking Incoming Call Android

In this post, you can learn on how to block an incoming call through android programming examples. There are few android applications in the market what you can make use of it to block the unwanted incoming calls. You can learn on the functionality behind. After getting good ideas on this you can really start building your own app. Let us see the example below.

1. First of all create a broadcast receiver java class for the incoming call.

Receiver.java

package com.udhaya;

import java.lang.reflect.Method;
import com.android.internal.telephony.ITelephony;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent
import android.telephony.TelephonyManager;
import android.util.Log;
public class PhoneCallReceiver extends BroadcastReceiver {
 Context context = null;
 private static final String TAG = "Call";
 private ITelephony telephonyService;
 @Override
 public void onReceive(Context context, Intent intent) {
  Log.v(TAG, "Receving SMS....");
  TelephonyManager telephony = (TelephonyManager) 
  context.getSystemService(Context.TELEPHONY_SERVICE);  
  try {
   Class c = Class.forName(telephony.getClass().getName());
   Method m = c.getDeclaredMethod("getITelephony");
   m.setAccessible(true);
   telephonyService = (ITelephony) m.invoke(telephony);
   //telephonyService.silenceRinger();
   telephonyService.endCall();
  } catch (Exception e) {
   e.printStackTrace();
  }  
 }}

2. Create an IDL interface in java for getting a core Telephony Service. Create a package named as com.android.internal.telephony

ITelephony.aidl

package com.android.internal.telephony;


  interface ITelephony {   
    boolean endCall();  
    void answerRingingCall();   
    void silenceRinger();
  }

3. Now configure the android manifest file and add the Uses permissions in it as illustrated below.


AndroidManifest.xml

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.udhaya"
      android:versionCode="1"
      android:versionName="1.0">  
    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <receiver  android:name=".PhoneCallReceiver">
            <intent-filter  android:priority="100" >
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>
    </application>
    <uses-sdk android:minSdkVersion="5" />
    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />
    <uses-sdk android:minSdkVersion="8" />
</manifest>

Receiving SMS BroadcastReceiver Intent Android

In this blog post, you can learn how to receive an sms using a Broadcast Receiver with Intent in android programming. By learning this basic sample you can develop complex android based sms applications.

1. Create a broadcast receiver class for receiving the sms.

Receiver.java

package com.udhaya.sms;
import android.content.*;
import android.os.Bundle;
import android.telephony.*;
import android.util.Log;
import android.widget.Toast;
public class SimpleSmsReciever extends BroadcastReceiver {
 private static final String TAG = "SMS Recieved";
 @Override
 public void onReceive(Context context, Intent intent) {    
     Bundle pudsBundle = intent.getExtras();
     Object[] pdus = (Object[]) pudsBundle.get("pdus");
     SmsMessage messages =SmsMessage.createFromPdu((byte[]) pdus[0]);    
     Log.i(TAG,  messages.getMessageBody());
     Toast.makeText(context, "SMS Received : "+messages.getMessageBody(),
     Toast.LENGTH_LONG).show();
 }
}

2. Configure and use the below android manifest file. Give Uses permission as highlighted below.

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest android="http://schemas.android.com/apk/res/android" 
package="com.javaorigin.android.sample" versioncode="1" versionname="1.0">
 <application icon="@drawable/icon" label="@string/app_name">
     <receiver name=".SimpleSmsReciever">
         <intent-filter>
             <action name="android.provider.Telephony.SMS_RECEIVED">
            </action>
         </intent-filter>
     </receiver>
</application>
 <uses-sdk minsdkversion="6">
 <uses-permission name="android.permission.INTERNET">

Custom Toast in Android Example

Toast is nothing but a small pop up or a feedback after an operation has performed in the android device. Say for example, if you perform a navigate from an email before you send it, it will trigger a "Draft Saved" toast message to know you that you can continue to edit later. Toast message will disappear after a few timeout seconds. This is a toast. It fills only the space which is required for that particular message and the current operation in the screen remains interactive and visible.

1. First create a Layout File named toast.xml

toast.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    <TextView android:id="@+id/text"

    android:id="@+id/toast_layout_root"
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp"
    android:background="#ffffff" >        
    <ImageView android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_marginRight="10dp" />
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:textColor="#FFF" />    
</LinearLayout>

2. Add the below code to the main activity file of your project.

MainActivity.java

package com.udhaya.android; 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast; 
public class MainActivity extends Activity { 
private Button button; 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState);
setContentView(R.layout.main); 
button = (Button) findViewById(R.id.buttonToast); 
button.setOnClickListener(new OnClickListener() { 
 @Override
 public void onClick(View arg0) { 
    Toast.makeText(getApplicationContext(), 
                               "Button clicked", Toast.LENGTH_LONG).show(); 
 }
});
}
}

And that's it. Now play with toast messages in your android development projects.

Pie Chart in Android Example

In this post, you can learn how to design a Pie chart for android applications. Using an external jar file named as "aChartEngine", we can develop a pie chart for android apps. First download "achartengine.jar" from code.google.com/p/achartengine/downloads/list and paste it in the "lib" folder of your android structure. Now follow the below steps and do complete your pie chart for android apps.

1.  Just add the following activity code in the android manifest XML file.
<activity android:name="org.achartengine.GraphicalActivity"/> 

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
    package="com.udhaya.graphchart"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />
    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
         >
        <activity
            android:name="com.udhaya.graphchart.Graph"
            android:label="@string/app_name"
          >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
  </activity>
<!—Add this activity in your AndroidManifest file -->
  <activity android:name="org.achartengine.GraphicalActivity"/>    
  </application>
</manifest>

2.  Place the "activity_graph.xml" in the "res" folder.



activity_graph.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    >
    <Button
        android:id="@+id/Efforts_bt_Graph"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Efforts" />
</LinearLayout>

3. Now write the Java code units for "Graph Activity".



GraphActivity.java 

package com.udhaya.graphchart;
import com.graphchart.R;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class Graph extends Activity implements OnClickListener {
    Button efforts;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_graph);
        efforts = (Button) findViewById(R.id.Efforts_bt_Graph);
        efforts.setOnClickListener(this);
    }
    @Override
    public void onClick(View v) {
        switch(v.getId()){
        case R.id.Efforts_bt_Graph:
            EffortChart effort = new EffortChart();
            Intent effortIntent = effort.getIntent(this);
            startActivity(effortIntent);
            break;
        }
    }
    }

4. Create a class "PieGraph.java".

PieGraph is a class in which the graph is actually created by using the methods of "achartengine" library.
Here we are using static values inside the code units for generating the chart. It can be modified dynamically by using corresponding code units as per your requirements and the values can be fetched from static device memory (SQLite Database) or even from the server database.

PieGraph.java 

package com.udhaya.graphchart;
import org.achartengine.ChartFactory;
import org.achartengine.model.CategorySeries;
import org.achartengine.renderer.DefaultRenderer;
import org.achartengine.renderer.SimpleSeriesRenderer;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
public class EffortChart {
    public Intent getIntent(Context context){
      // this is my data of performance; data is collected in array.
       int []Performance = {42, 15, 19};  // [0] for Call, [1] for Meeting, [2] for Email
        CategorySeries series = new CategorySeries("pie"); // adding series to charts. //collect 3 value in array. therefore add three series.
            series.add("Call",Performance[0]);            
            series.add("Meeting",Performance[1]);
            series.add("Email",Performance[2]);
// add three colors for three series respectively            int []colors = new int[]{Color.MAGENTA, Color.WHITE, Color.GREEN};
// set style for series
            DefaultRenderer renderer = new DefaultRenderer();
            for(int color : colors){
                SimpleSeriesRenderer r = new SimpleSeriesRenderer();
                r.setColor(color);
                r.setDisplayBoundingPoints(true);
                r.setDisplayChartValuesDistance(5);
                r.setDisplayChartValues(true);
                r.setChartValuesTextSize(15);
                renderer.addSeriesRenderer(r);
            }
            renderer.isInScroll();
            renderer.setZoomButtonsVisible(true);   //set zoom button in Graph
            renderer.setApplyBackgroundColor(true);
            renderer.setBackgroundColor(Color.BLACK); //set background color
            renderer.setChartTitle("Efforts");
            renderer.setChartTitleTextSize((float) 30);
            renderer.setShowLabels(true);  
            renderer.setLabelsTextSize(20);
            renderer.setLegendTextSize(25);
            renderer.setDisplayValues(true);
            return ChartFactory.getPieChartIntent(context, series, renderer, "PieChart");
        }
    }

HTTP Get Request

In this post, you can learn how to make a httpclient for HTTP Get Request to retrieve contents of a stream. Please find below the android source code example.

public static InputStream getInputStreamFromUrl(String url) {
  InputStream content = null;
  try {
    HttpClient httpclient = new DefaultHttpClient();
    HttpResponse response = httpclient.execute(new HttpGet(url));
    content = response.getEntity().getContent();
  } catch (Exception e) {
    Log.e("[GET REQUEST]", "Network exception");
  }
    return content;
}


Android HttpClient

In this blog post, you can learn android source code on how to post data to a url by using a httpclient post method.

Please find below the very simple android source code example for dealing with httpclient post. This simple code executes a http post request with org.apache.http.client.HttpClient and can be used in the combination with Non-Blocking Web Requests.


public void postData() {
    // Create a new HttpClient and Post Header
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new HttpPost("http://www.website.com/phpscript.php");

    try {
        // Add your data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
        nameValuePairs.add(new BasicNameValuePair("id", "9449"));
        nameValuePairs.add(new BasicNameValuePair("stringdata", "android"));
        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));

        // Execute HTTP Post Request
        HttpResponse response = httpclient.execute(httppost);
        
    } catch (ClientProtocolException e) {
        // TODO Auto-generated catch block
    } catch (IOException e) {
        // TODO Auto-generated catch block
    }

Creating HTTP Client and HTTP Post

// Creating a HTTP client
HttpClient httpClient = new DefaultHttpClient();

// Creating a HTTP Post
HttpPost httpPost = new HttpPost("http://www.androidsourcecodeexamples.com/index");


Create post parameters with key and value.

List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
nameValuePair.add(new BasicNameValuePair("email", "xxx@gmail.com"));
nameValuePair.add(new BasicNameValuePair("password", "xxx_password"));


At last we should execute the httpPost using httpClient which is created previously.

// Making HTTP Request
try {
    HttpResponse response = httpClient.execute(httpPost);

    // writing response to log
    Log.d("Http Response:", response.toString());

} catch (ClientProtocolException e) {
    // writing exception to log
    e.printStackTrace();
         
} catch (IOException e) {
    // writing exception to log
    e.printStackTrace();
}


Please find below the full android code units to make a http Request. This example is for response to the log. For http response see your eclipse log report.


package com.udhaya.httprequests;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List; 
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair; 
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;


public class AndroidHTTPRequestsActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        // Creating HTTP client

        HttpClient httpClient = new DefaultHttpClient();
        // Creating HTTP Post
        HttpPost httpPost = new HttpPost("http://www.example.com/login");


        // Building post parameters

        // key and value pair
        List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(2);
        nameValuePair.add(new BasicNameValuePair("email", "xxx@gmail.com"));
        nameValuePair.add(new BasicNameValuePair("sms",android http post"));


        // Url Encoding the POST parameters

        try {
            httpPost.setEntity(new UrlEncodedFormEntity(nameValuePair));
        } catch (UnsupportedEncodingException e) {
            // writing error to Log
            e.printStackTrace();
        }


        // Making HTTP Request

        try {
            HttpResponse response = httpClient.execute(httpPost);


            // writing response to log

            Log.d("Http Response:", response.toString());
        } catch (ClientProtocolException e) {
            // writing exception to log
            e.printStackTrace();
        } catch (IOException e) {
            // writing exception to log
            e.printStackTrace();


        }

    }
}
My Profile