Wednesday, June 6, 2012

Android Advance Training: Autoreply sender via BoardcastReceiver




Complete Code
package com.k;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.widget.Toast;

public class SMSReceiver2 extends BroadcastReceiver{

       @Override
       public void onReceive(Context context, Intent intent) {
             
              // Get the SMS message pass in
              Bundle bundle = intent.getExtras();
              String sOutput = "";
             
              if (bundle != null) {
                    
                     // Retrieve the SMS message received
                     Object[] pdus = (Object[]) bundle.get("pdus");
                    
                     SmsMessage[] smsMessage = new SmsMessage[pdus.length];
                    
                     for (int n = 0; n < smsMessage.length; n++) {
                          
                           smsMessage[n] = SmsMessage.createFromPdu((byte[]) pdus[n]);
                          
                           sOutput += "SMS from " + smsMessage[n].getOriginatingAddress();
                           sOutput += " : ";
                           sOutput += smsMessage[n].getMessageBody().toString();
                           sOutput += "\n";
                     }
                    
                     // Show the new SMS message
                     Toast.makeText(context, sOutput, Toast.LENGTH_SHORT).show();
                    
                     // Send a broadcast intent to tell the activity about the new SMS received
                     Intent broadcastIntent = new Intent();
                     broadcastIntent.setAction("SMS_RECEIVED_ACTION");
                     broadcastIntent.putExtra("sms", sOutput);
                     context.sendBroadcast(broadcastIntent);
                    
              }

       }

}

package com.k;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class SMSReceiveAppActivity extends Activity {
      
       Button btnSendSMS;
       IntentFilter intentFilter;
      
       private BroadcastReceiver intentReceiver = new BroadcastReceiver() {
             
       @Override
       public void onReceive(Context context, Intent intent) {
             
              // display the SMS received in the TextView
              TextView SMSes = (TextView) findViewById(R.id.textView1);
              SMSes.setText(intent.getExtras().getString("sms"));

                try {
                      
                     String sms = "Testing by Kent";
                      
                     SmsManager smsManager = SmsManager.getDefault();
                     smsManager.sendTextMessage("5554", null, sms, null, null);
                    
                     Toast.makeText(getApplicationContext(), "Your SMS is sent successfully!",
                                         Toast.LENGTH_LONG).show();
                    
                } catch (Exception e) {
                      
                     Toast.makeText(getApplicationContext(),
                           "Sending SMS faild!",
                           Toast.LENGTH_LONG).show();
                    
                }
      
       }
      
       };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        //---intent to filter for SMS messages received---
        intentFilter = new IntentFilter();
        intentFilter.addAction("SMS_RECEIVED_ACTION");


       
       
        btnSendSMS = (Button) findViewById(R.id.btnSendSMS);
        btnSendSMS.setOnClickListener( new View.OnClickListener() {
             
        public void onClick(View v)
        {
             
        //sendSMS(“5554”, “Hello my friends!”);
        Intent i = new Intent(android.content.Intent.ACTION_VIEW);
        i.putExtra("address", "5554");
        i.putExtra("sms_body", "Hello my friends!");
        i.setType("vnd.android-dir/mms-sms");
       
        startActivity(i);
        }
        });
       
    }

    @Override
    protected void onResume() {
    //---register the receiver---
    registerReceiver(intentReceiver, intentFilter);
    super.onResume();
    }
   
    @Override
    protected void onPause() {
    //---unregister the receiver---
    unregisterReceiver(intentReceiver);
    super.onPause();
    }
   
    //---sends an SMS message to another device---
    private void sendSMS(String phoneNumber, String message)
    {
    //...
    }
   
}

<?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" >

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />

    <Button
        android:id="@+id/btnSendSMS"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Button" />

</LinearLayout>

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.k"
    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=".SMSReceiveAppActivity"
            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" android:enabled="true">
                     <intent-filter>
                           <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                     </intent-filter>
              </receiver>
             
                     <receiver android:name=".SMSReceiver2">
                           <intent-filter>
                           <action android:name="android.provider.Telephony.SMS_RECEIVED" />
                           </intent-filter>
                     </receiver>
                          
       
    </application>
    <uses-permission android:name="android.permission.SEND_SMS" />
       <uses-permission android:name="android.permission.RECEIVE_SMS"></uses-permission>
   
</manifest>

Monday, June 4, 2012

Sunday, June 3, 2012

Using HTTP Post Method in Android


Source from
http://android-er.blogspot.com/2011/09/example-of-httppost-on-android.html


package com.kent;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
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.widget.TextView;
import android.widget.Toast;

public class HTTPPostDemoActivity extends Activity {
   

    @Override
    public void onCreate(Bundle savedInstanceState) {
      
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        TextView result = (TextView)findViewById(R.id.result);
       
        BufferedReader bufferedReader = null;
        HttpClient httpClient = new DefaultHttpClient();
        HttpPost request = new HttpPost("http://www.ugrowit.net/welcome-post.php");
        List<NameValuePair> postParameters = new ArrayList<NameValuePair>();
        postParameters.add(new BasicNameValuePair("password", "1234"));
       
       
  try {
        
         UrlEncodedFormEntity entity =
                       new UrlEncodedFormEntity(postParameters);
      request.setEntity(entity);
          
      HttpResponse response= httpClient.execute(request);

     
      bufferedReader = new BufferedReader(
           new InputStreamReader(response.getEntity().getContent()));
  
      StringBuffer stringBuffer = new StringBuffer("");
      String line = "";
      String LineSeparator = System.getProperty("line.separator");
      while ((line = bufferedReader.readLine()) != null) {
         stringBuffer.append(line + LineSeparator);
      }
      bufferedReader.close();
  
      result.setText(stringBuffer.toString());
  
      Toast.makeText(HTTPPostDemoActivity.this,
                "Finished",
                Toast.LENGTH_LONG).show();
  
  } catch (ClientProtocolException e) {
  
         Toast.makeText(HTTPPostDemoActivity.this,
                       e.toString(),
                       Toast.LENGTH_LONG).show();
        
  } catch (IOException e) {
  
         Toast.makeText(HTTPPostDemoActivity.this,
                       e.toString(),
                       Toast.LENGTH_LONG).show();
  }finally{
        
   if (bufferedReader != null){
   try {
       bufferedReader.close();
   } catch (IOException e) {
  
   }
  
   }
  }       
    }
}