Showing posts with label Activity. Show all posts
Showing posts with label Activity. Show all posts

Thursday, May 3, 2012

Calculate Device Moving Speed Programmatically

so this evening i would like to share with you new thing what i have learn..

some time we need to calculate moving speed of our android mobile device.

this example will calculate the location coordinates latitude-longitude after every 5 seconds gap.
and then calculate the speed of device in m/s.
all work done in background by the service.

so i we need to do is install this app into mobile and close now it started a background service
and calculate the speed forever..
[you can create without any activity also, but i have created an activity ans started the service from activity]

let's begin the coding, first of all we need to create a simple project having single activity like this
DeviceMovingSpeed.java
  
package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class DeviceMovingSpeed extends Activity// implements Runnable
{
    /** Called when the activity is first created. */
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v("Debug", "Activity started..");
        Intent myIntent=new Intent(this,MyService.class);  
  startService(myIntent);  
    } 
}

Now we need to create a service where we will handle all the stuff creating a thread Getting current location calculating coordinates latitude-longitude calculating distance and device moving speed
MyService.java
  
package com.rdc;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service
{ 
 private LocationManager locManager;
 private LocationListener locListener = new myLocationListener();
 static final Double EARTH_RADIUS = 6371.00;
 
 private boolean gps_enabled = false;
 private boolean network_enabled = false;
 
 private Handler handler = new Handler();
 Thread t;
 
   @Override
   public IBinder onBind(Intent intent) {return null;}
   @Override
   public void onCreate() {}
   @Override
   public void onDestroy() {}
   @Override
   public void onStart(Intent intent, int startid) {}   
   @Override
 public int onStartCommand(Intent intent, int flags, int startId){
 
 Toast.makeText(getBaseContext(), "Service Started", Toast.LENGTH_SHORT).show();
   
 final Runnable r = new Runnable()
 {   public void run() 
     {
   Log.v("Debug", "Hello");
   location();
   handler.postDelayed(this, 5000);
     }
 };
  handler.postDelayed(r, 5000);  
       return START_STICKY; 
 }
   
   public void location(){
 locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
  
 try{
 gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
 }
 catch(Exception ex){}
 try{
 network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);    
 }
 catch(Exception ex){}
 Log.v("Debug", "in on create.. 2");   
 if (gps_enabled) {
 locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locListener);
 Log.v("Debug", "Enabled..");
 }
 if (network_enabled) {
 locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locListener);
 Log.v("Debug", "Disabled..");
 }
 Log.v("Debug", "in on create..3");
 }   
 
   private class myLocationListener implements LocationListener
   {
      double lat_old=0.0;
      double lon_old=0.0;
      double lat_new;
      double lon_new;
      double time=10;
      double speed=0.0;
      @Override
 public void onLocationChanged(Location location) {   
 Log.v("Debug", "in onLocation changed..");   
 if(location!=null){    
 locManager.removeUpdates(locListener);    
 //String Speed = "Device Speed: " +location.getSpeed();
 lat_new=location.getLongitude();
 lon_new =location.getLatitude();
 String longitude = "Longitude: " +location.getLongitude();
 String latitude = "Latitude: " +location.getLatitude();    
 double distance =CalculationByDistance(lat_new, lon_new, lat_old, lon_old);    
 speed = distance/time;     
 Toast.makeText(getApplicationContext(), longitude+"\n"+latitude+"\nDistance is: "
   +distance+"\nSpeed is: "+speed , Toast.LENGTH_SHORT).show();
 lat_old=lat_new;
 lon_old=lon_new;
 }
 }
 @Override
 public void onProviderDisabled(String provider) {}
 @Override
 public void onProviderEnabled(String provider) {}
 @Override
 public void onStatusChanged(String provider, int status, Bundle extras) {}    
   }   
   
   public double CalculationByDistance(double lat1, double lon1, double lat2, double lon2) {
  double Radius = EARTH_RADIUS;
  double dLat = Math.toRadians(lat2-lat1);  
  double dLon = Math.toRadians(lon2-lon1);  
  double a = Math.sin(dLat/2) * Math.sin(dLat/2) +  
  Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *  
  Math.sin(dLon/2) * Math.sin(dLon/2);  
  double c = 2 * Math.asin(Math.sqrt(a));  
  return Radius * c;
   }   
}

now come to AndroidManifest.xml
  


    


    
        
            
                
                
            
                
        
   
           
              
              
           
      
    


okay!! that's it.. now run the application toast will appear to say :-
"current coordinates"
"distance if device is moving"
"and speed of device in m/s (meter/seconds)"

 cheers!!

 I'd love to hear your thoughts!

Sunday, April 15, 2012

Start Service from Activity


Some time we need to start a service from Android Activity..
how can we achieve this i am going to write step by step.

First of all we need to Create a simple application with an Activity

-------------------------------------------
App Name: Activity2Service
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: MyActivity
-------------------------------------------


"MyActivity.java"
 
package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MyActivity extends Activity {

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

  Log.v("Debug", "Activity has been Started..");
  Toast.makeText(getBaseContext(), 
                      "Activity Started", Toast.LENGTH_SHORT)
    .show();
  Intent myIntent = new Intent(getBaseContext(), MyService.class);
  startService(myIntent);
 }
}

Then Create a Service
  
package com.rdc;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

 @Override
 public IBinder onBind(Intent intent) {
  return null;
 }

 @Override
 public void onCreate() {
  Log.v("Debug", "Service has been Created..");
  // code to execute when the service is first created
 }

 @Override
 public void onDestroy() {
  // code to execute when the service is shutting down
 }

 // This method has been deprecated since API 5
 /*
   @Override public void onStart(Intent intent, int startid) { 
          code to execute when the service is starting up
    }*/
  

 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  Log.v("Debug", "Service has been Started..");
  Toast.makeText(getBaseContext(), "Service has been Started..",
    Toast.LENGTH_SHORT).show();
  // We want this service to continue running until it's explicitly
  // stopped, so return sticky.
  return START_STICKY;
 }
}

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"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>


Don't forget to make entry in "Manifest" file for Service
  
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="8" />

 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
  <activity
   android:name=".MyActivity"
   android:label="@string/app_name">
   <intent-filter>
   <action android:name="android.intent.action.MAIN" />
   <category android:name="android.intent.category.LAUNCHER" />
   </intent-filter>
  </activity>
  <service
   android:enabled="true"
   android:name=".MyService">
   <intent-filter>
    <action android:name="com.rdc.MyService">
    </action>
   </intent-filter>
  </service>

 </application>

</manifest>

Now Run Application, Toast will appear..  :)

You can download the complete source code zip file here : Activity2Service

cheers!!

I'd love to hear your thoughts!

Saturday, April 7, 2012

Start Activity from Activity


Some time we need to start an Activity from Activity..
how can we achieve this i am going to write step by step.

We will create very simple app to do this work
 -------------------------------------------
App Name: Activity2Activity
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: FirstActivity
-------------------------------------------


FirstActivity.java

package com.rdc;

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 FirstActivity extends Activity implements OnClickListener {
 
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.first);

  Button btnload = (Button) findViewById(R.id.btnfirst);
  btnload.setOnClickListener(this);

 }

 @Override
 public void onClick(View v) {
  Intent i = new Intent(FirstActivity.this, SecondActivity.class);
  startActivity(i);
 }
}

SecondActivity.java
package com.rdc;

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 SecondActivity extends Activity implements OnClickListener {
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.second);

  Button btnload = (Button) findViewById(R.id.btnsecond);
  btnload.setOnClickListener(this);

 }

 @Override
 public void onClick(View v) {
  Intent i = new Intent(SecondActivity.this, FirstActivity.class);
  startActivity(i);
 }
}

first.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">
 <TextView
  android:layout_width="fill_parent"
  android:text="I am first activity.."
  android:gravity="center"
  android:layout_height="62dp" />
 <LinearLayout
  android:id="@+id/layV"
  android:orientation="vertical"
  android:gravity="center"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
   android:text="Load Second Activity"
   android:layout_height="wrap_content"
   android:layout_width="wrap_content"
   android:id="@+id/btnfirst"></Button>
 </LinearLayout>

</LinearLayout>



second.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">
 <TextView
  android:layout_width="fill_parent"
  android:text="I am Second activity.."
  android:gravity="center"
  android:layout_height="62dp" />
 <LinearLayout
  android:id="@+id/layV"
  android:orientation="vertical"
  android:gravity="center"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">
  <Button
   android:text="Load First Activity"
   android:layout_height="wrap_content"
   android:layout_width="wrap_content"
   android:id="@+id/btnsecond"></Button>
 </LinearLayout>

</LinearLayout>

AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />

 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
 <activity
   android:name=".FirstActivity"
   android:label="@string/app_name">
 <intent-filter>
 <action android:name="android.intent.action.MAIN" />
 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>

 <activity
   android:name=".SecondActivity"
   android:label="@string/app_name">
 <intent-filter>
 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
 </activity>

 </application>
</manifest>

The output Screen will be like this..


You can download the complete source code zip file here : Activity2Activity

 cheers!!

 I'd love to hear your thoughts!

Sunday, April 1, 2012

Start BroadcastReceiver from Activity

Some time we need to start a service from Android Activity..
how can we achieve this i am going to write step by step.

We will create very simple app to do this work
 -------------------------------------------
App Name: Activity2BReceiver
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: MyActivity
-------------------------------------------


MyActivity.java
  
package com.rdc;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MyActivity extends Activity {   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v("Debug", "Activity has been started..");
    }
}

Then Create a Broadcast Receiver

MyReceiver.java
  
package com.rdc;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
  Log.v("Debug", "SMS Broadcast Receiver has been started..");
  Toast.makeText(context, "BReceiver is watching ur message..", 
    Toast.LENGTH_SHORT).show();

 }

}

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"
    >
<TextView  
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
    />
</LinearLayout>


Don't forget to make entry in "Manifest" file for Receiver
  
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />
 <uses-permission android:name="android.permission.RECEIVE_SMS">
 </uses-permission>
 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
  <activity
   android:name=".MyActivity"
   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="com.rdc.MyReceiver">

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

 </application>
</manifest>

Run this app and send message from another mobile/emulator, Receiver will notify you about new sms
See below output screens tensted on Emulator and Real Device


You can download the complete source code zip file here : Activity2BReceiver


I'd love to hear your thoughts!

Saturday, March 31, 2012

How to Get Own Mobile Number Programmatically

sometime you have multiple SIM cards and you don't know which one Number you are using.Then you may be want to "Get Own Mobile Number" ?
How I am going to write a small android application which will solve our puzzle.

So here we go.. we need to create a Basic Android App having an Activity like this
GetMyPhoneNoActivity.java
  
package com.kns;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;

public class GetMyPhoneNoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);        
    
        String number =getMyPhoneNO();
        Toast.makeText(getApplicationContext(), "My Phone No is: "
        +number, Toast.LENGTH_SHORT).show();
        Log.v("Debug", number);        
    }
    
    private String getMyPhoneNO(){
     TelephonyManager mTelephonyMgr;  
     mTelephonyMgr = (TelephonyManager) getSystemService
       (Context.TELEPHONY_SERVICE);   

     String yourNumber = mTelephonyMgr.getLine1Number();
  return yourNumber; 
    }     
}

Then we need to add user permission into manifest file
  

so it will be look like this..
AndroidManifest.xml
  


    

 

    
        
            
                
                
            
        

    


Now if will check this code on Emulator device, The output will be..


Note: As i have read, so far some people have conflict about different behavior of  output.
there are reports that some SIMs cause this method to return null.

Because --? I think there are cases where the phone does not know its own number - it somehow depends on the network provider / SIM card.

So, There is no guaranteed solution to this problem because the phone number is not physically stored on all SIM-cards, or broadcasted from the network to the phone. This is especially true in some countries which requires physical address verification, with number assignment only happening afterwards. Phone number assignment happens on the network - and can be changed without changing the SIM card or device (e.g. this is how porting is supported).

I'd like to know your suggestions!!

Thanks!

Friday, March 2, 2012

Lock Phone Screen Programmtically

How to lock Mobile Phone Screen ...
first of all we need to get permission from Admin
create app with default activity

Project Name : LockScreen
Package Name: com.kns
Android SDK: 2.2 API 8

the project structure is look like this


LockScreenActivity.java
  
package com.kns;


import android.app.Activity;
import android.app.ActivityManager;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class LockScreenActivity extends Activity implements OnClickListener {
 private Button lock;
 private Button disable;
 private Button enable;
 static final int RESULT_ENABLE = 1;

     DevicePolicyManager deviceManger;
     ActivityManager activityManager;
     ComponentName compName;
     
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        deviceManger = (DevicePolicyManager)getSystemService(
          Context.DEVICE_POLICY_SERVICE);
        activityManager = (ActivityManager)getSystemService(
          Context.ACTIVITY_SERVICE);
        compName = new ComponentName(this, MyAdmin.class);

        setContentView(R.layout.main);
        
        lock =(Button)findViewById(R.id.lock);
        lock.setOnClickListener(this);
        
        disable = (Button)findViewById(R.id.btnDisable);
        enable =(Button)findViewById(R.id.btnEnable);
        disable.setOnClickListener(this);
        enable.setOnClickListener(this);
    }

 @Override
 public void onClick(View v) {
  
  if(v == lock){
    boolean active = deviceManger.isAdminActive(compName);
             if (active) {
                 deviceManger.lockNow();
             }
  }
  
  if(v == enable){
   Intent intent = new Intent(DevicePolicyManager
     .ACTION_ADD_DEVICE_ADMIN);
            intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN,
                    compName);
            intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,
                    "Additional text explaining why this needs to be added.");
            startActivityForResult(intent, RESULT_ENABLE);
  }
  
  if(v == disable){
     deviceManger.removeActiveAdmin(compName);
              updateButtonStates();
  }  
 }

 private void updateButtonStates() {
  
        boolean active = deviceManger.isAdminActive(compName);
        if (active) {
            enable.setEnabled(false);
            disable.setEnabled(true);
            
        } else {
            enable.setEnabled(true);
            disable.setEnabled(false);
        }    
 }
 
  protected void onActivityResult(int requestCode, int resultCode, Intent data) {
         switch (requestCode) {
             case RESULT_ENABLE:
                 if (resultCode == Activity.RESULT_OK) {
                     Log.i("DeviceAdminSample", "Admin enabled!");
                 } else {
                     Log.i("DeviceAdminSample", "Admin enable FAILED!");
                 }
                 return;
         }
         super.onActivityResult(requestCode, resultCode, data);
     }
}

MyAdmin.java
  
package com.kns;

import android.app.admin.DeviceAdminReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.widget.Toast;

public class MyAdmin extends DeviceAdminReceiver{


    static SharedPreferences getSamplePreferences(Context context) {
        return context.getSharedPreferences(
          DeviceAdminReceiver.class.getName(), 0);
    }

    static String PREF_PASSWORD_QUALITY = "password_quality";
    static String PREF_PASSWORD_LENGTH = "password_length";
    static String PREF_MAX_FAILED_PW = "max_failed_pw";

    void showToast(Context context, CharSequence msg) {
        Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onEnabled(Context context, Intent intent) {
        showToast(context, "Sample Device Admin: enabled");
    }

    @Override
    public CharSequence onDisableRequested(Context context, Intent intent) {
        return "This is an optional message to warn the user about disabling.";
    }

    @Override
    public void onDisabled(Context context, Intent intent) {
        showToast(context, "Sample Device Admin: disabled");
    }

    @Override
    public void onPasswordChanged(Context context, Intent intent) {
        showToast(context, "Sample Device Admin: pw changed");
    }

    @Override
    public void onPasswordFailed(Context context, Intent intent) {
        showToast(context, "Sample Device Admin: pw failed");
    }

    @Override
    public void onPasswordSucceeded(Context context, Intent intent) {
        showToast(context, "Sample Device Admin: pw succeeded");
    } 

} 


main.xml
  


    
    
        
    
        
    
        
    
        


policies.xml
  


    
        
        
        
        
        
    


AndroidManifest.xml
  


    

    
        
            
                
                
            
        
        
        
            
            
                
            
        

    


Before Lock the screen you need to Enable Admin Permission

Then you will get this..
 After Enable you will lock screen..like this

we have done it!!

I'd love to hear your thoughts!!

Monday, February 6, 2012

Start Activity from Broadcast Recevier


Some time we need to start an Activity from Broadcast Receiver..
how can we achieve this i am going to write step by step.

So lets create a small App to do this things 

-------------------------------------------
App Name: BReceiver2Activity
Package Name: com.rdc
Android SDK: Android SDK 2.2 / API 8
-------------------------------------------

MyReceiver.java
package com.rdc;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

public class MyReceiver extends BroadcastReceiver {

 @Override
 public void onReceive(Context context, Intent intent) {
  
  Toast.makeText(context, "MyReceiver Started", 
    Toast.LENGTH_SHORT).show();
  Log.v("Info Message", "in Broadcast receiver");
  Intent myIntent=new Intent(context,MyActivity.class); 
  myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
  context.startActivity(myIntent);
 }

}



MyActivity.java
package com.rdc;

import android.app.Activity;
import android.os.Bundle;

public class MyActivity extends Activity {

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

 }
}


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:weightSum="1">
 <TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="@string/hello"
  android:layout_weight="0.14" />
</LinearLayout>


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="8" />

 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">

  <activity
   android:enabled="true"
   android:name=".MyActivity">
   <intent-filter>
    <action android:name="com.rdc.MyActivity">
    </action>
   </intent-filter>
  </activity>

  <receiver
    android:enabled="true"
    android:name=".MyReceiver">
    <intent-filter>
    <action android:name="android.intent.action.BOOT_COMPLETED" />
    </intent-filter>
  </receiver>

 </application>
</manifest>

Now Reboot Emulator, Activity will appear on start-up.

You can download source code here: BReceiver2Activity

cheers!!

I'd love to hear your thoughts!!

Friday, January 13, 2012

Get Current Location coordinates , City name

Sometime we need to get  GPS  coordinates in android. so today i am going to write step by step simple tutorial How can we get location coordinates using GPS in android mobile.

also through coordinate we can calculate current location more details like City Name.

Note: I have tested this app on My Android Mobile and its working fine.
But when you test this app, enable your gps settings in mobile, you need to change current location like 10-20 meter so you will get the coordinates, so need to move with the installed app mobile device.

What this app does?
  • Check gps is enable or disable.
  • Get gps coordinates.
  • Get the current city name.
okay! so let's try this small app

 -------------------------------------------
App Name: GetCurrentLocation
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: GetCurrentLocation
-------------------------------------------


GetCurrentLocation.java


package com.rdc;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

public class GetCurrentLocation extends Activity 
implements OnClickListener {
 
 private LocationManager locationMangaer=null;
 private LocationListener locationListener=null; 
 
 private Button btnGetLocation = null;
 private EditText editLocation = null; 
 private ProgressBar pb =null;
 
 private static final String TAG = "Debug";
 private Boolean flag = false;

 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  
  
  //if you want to lock screen for always Portrait mode  
  setRequestedOrientation(ActivityInfo
  .SCREEN_ORIENTATION_PORTRAIT);

  pb = (ProgressBar) findViewById(R.id.progressBar1);
  pb.setVisibility(View.INVISIBLE);
  
  editLocation = (EditText) findViewById(R.id.editTextLocation); 

  btnGetLocation = (Button) findViewById(R.id.btnLocation);
  btnGetLocation.setOnClickListener(this);
  
  locationMangaer = (LocationManager) 
  getSystemService(Context.LOCATION_SERVICE);

 }

 @Override
 public void onClick(View v) {
  flag = displayGpsStatus();
  if (flag) {
   
   Log.v(TAG, "onClick");  
   
   editLocation.setText("Please!! move your device to"+
   " see the changes in coordinates."+"\nWait..");
   
   pb.setVisibility(View.VISIBLE);
   locationListener = new MyLocationListener();

   locationMangaer.requestLocationUpdates(LocationManager
   .GPS_PROVIDER, 5000, 10,locationListener);
   
   } else {
   alertbox("Gps Status!!", "Your GPS is: OFF");
  }

 }

 /*----Method to Check GPS is enable or disable ----- */
 private Boolean displayGpsStatus() {
  ContentResolver contentResolver = getBaseContext()
  .getContentResolver();
  boolean gpsStatus = Settings.Secure
  .isLocationProviderEnabled(contentResolver, 
  LocationManager.GPS_PROVIDER);
  if (gpsStatus) {
   return true;

  } else {
   return false;
  }
 }

 /*----------Method to create an AlertBox ------------- */
 protected void alertbox(String title, String mymessage) {
  AlertDialog.Builder builder = new AlertDialog.Builder(this);
  builder.setMessage("Your Device's GPS is Disable")
  .setCancelable(false)
  .setTitle("** Gps Status **")
  .setPositiveButton("Gps On",
   new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int id) {
   // finish the current activity
   // AlertBoxAdvance.this.finish();
   Intent myIntent = new Intent(
   Settings.ACTION_SECURITY_SETTINGS);
   startActivity(myIntent);
      dialog.cancel();
   }
   })
   .setNegativeButton("Cancel",
   new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int id) {
    // cancel the dialog box
    dialog.cancel();
    }
   });
  AlertDialog alert = builder.create();
  alert.show();
 }
 
 /*----------Listener class to get coordinates ------------- */
 private class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location loc) {
          
            editLocation.setText("");
            pb.setVisibility(View.INVISIBLE);
            Toast.makeText(getBaseContext(),"Location changed : Lat: " +
   loc.getLatitude()+ " Lng: " + loc.getLongitude(),
   Toast.LENGTH_SHORT).show();
            String longitude = "Longitude: " +loc.getLongitude();  
      Log.v(TAG, longitude);
      String latitude = "Latitude: " +loc.getLatitude();
      Log.v(TAG, latitude);
          
    /*----------to get City-Name from coordinates ------------- */
      String cityName=null;              
      Geocoder gcd = new Geocoder(getBaseContext(), 
   Locale.getDefault());             
      List<Address>  addresses;  
      try {  
      addresses = gcd.getFromLocation(loc.getLatitude(), loc
   .getLongitude(), 1);  
      if (addresses.size() > 0)  
         System.out.println(addresses.get(0).getLocality());  
         cityName=addresses.get(0).getLocality();  
        } catch (IOException e) {            
        e.printStackTrace();  
      } 
          
      String s = longitude+"\n"+latitude +
   "\n\nMy Currrent City is: "+cityName;
           editLocation.setText(s);
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub         
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub         
        }

        @Override
        public void onStatusChanged(String provider, 
  int status, Bundle extras) {
            // TODO Auto-generated method stub         
        }
    }
}

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:weightSum="1">
 <TextView
  android:layout_width="fill_parent"
  android:layout_height="wrap_content"
  android:text="Get Current Location and City Name"
  android:layout_weight="0.20"
  android:gravity="center"
  android:textSize="20sp" />
 <EditText
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:layout_weight="0.33"
  android:id="@+id/editTextLocation"
  android:editable="false">
  <requestFocus></requestFocus>
 </EditText>
 <LinearLayout
  android:id="@+id/layButtonH"
  android:layout_height="wrap_content"
  android:layout_width="fill_parent"
  android:gravity="center"
  android:layout_weight="0.15">
  <Button
   android:layout_width="wrap_content"
   android:layout_height="wrap_content"
   android:text="Get Location"
   android:id="@+id/btnLocation"></Button>
 </LinearLayout>
 <LinearLayout
  android:id="@+id/layloadingH"
  android:layout_height="wrap_content"
  android:layout_weight="0.20"
  android:layout_width="fill_parent"
  android:gravity="center">
  <ProgressBar
   android:layout_width="wrap_content"
   android:id="@+id/progressBar1"
   android:layout_height="wrap_content"></ProgressBar>
 </LinearLayout>
</LinearLayout>


AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest
 xmlns:android="http://schemas.android.com/apk/res/android"
 package="com.rdc"
 android:versionCode="1"
 android:versionName="1.0">
 <uses-sdk android:minSdkVersion="10" />

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION">
</uses-permission>

 <application
  android:icon="@drawable/icon"
  android:label="@string/app_name">
  <activity
   android:name=".GetCurrentLocation"
   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>
</manifest>

The output Screen will be like this..


You can download the complete source code zip file here : GetCurrentLocation

 cheers!!

I'd love to hear your thoughts!

Saturday, October 22, 2011

Listen SMS-MMS Programmatically Android (Store SMS-MMS Data)

after many hours overtime i got solve this puzzle.. how can we store the incoming (sms/mms) and outgoing (sms/mms) data programmatically?.

MainActivity.java

  
package Com.rdc.listenSmsMms;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v("In on create", "activty started..");
        
        //start the service to listen 
        startService(new Intent(getBaseContext(),ListenSmsMmsService.class));
    }
}

ListenSmsMmsService.java
  
package Com.rdc.listenSmsMms;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.Date;

import android.app.Service;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.ContentObserver;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class ListenSmsMmsService extends Service {

 private ContentResolver contentResolver;
 
  
 String substr;
 int k;
 
 @Override
 public IBinder onBind(Intent intent) {  
  return null;
 }
 
 @Override
 public void onCreate() { 
  Log.v("Debug", " service creatd.........");
 }
 
 public void registerObserver() {    
  
  contentResolver = getContentResolver();            
  contentResolver.registerContentObserver(
    Uri.parse("content://mms-sms/conversations/"),
      true, new SMSObserver(new Handler()));          
  Log.v("Debug", " in registerObserver method.........");
 }
 
 //start the service and register observer for lifetime
 @Override
 public int onStartCommand(Intent intent, int flags, int startId) {
  Log.v("Debug", "Service has been started..");  
  Toast.makeText(getApplicationContext(),
    "Service has been started.. ", 
    Toast.LENGTH_SHORT).show();  
  registerObserver(); 
  
  return START_STICKY;  
 }
 
 class SMSObserver extends ContentObserver{

  public SMSObserver(Handler handler) {
   super(handler);   
  }
  
  //will be called when database get change
  @Override
  public void onChange(boolean selfChange) {
   super.onChange(selfChange);
   Log.v("Debug", "Observer has been started..");
   
  /*first of all we need to decide message is Text or MMS type.*/
   final String[] projection = new String[]{
     "_id", "ct_t"};
   Uri mainUri = Uri.parse(
     "content://mms-sms/conversations/");
   Cursor mainCursor = contentResolver.
     query(mainUri, projection, 
     null, null, null);
   mainCursor.moveToFirst();
   
   String msgContentType = mainCursor.getString(mainCursor.
     getColumnIndex("ct_t"));
   if ("application/vnd.wap.multipart.related".
     equals(msgContentType)) {
    // it's MMS
          Log.v("Debug", "it's MMS");
          
          //now we need to decide MMS message is sent or received
          Uri mUri = Uri.parse("content://mms");          
          Cursor mCursor = contentResolver.query(mUri, null, null, 
            null, null);
          mCursor.moveToNext();
    int type = mCursor.getInt(mCursor.getColumnIndex("type"));
    
    if(type==1){
     //it's received MMS
     Log.v("Debug", "it's received MMS");
     getReceivedMMSinfo();
    }
    else if(type==2)
    {
     //it's sent MMS
     Log.v("Debug", "it's Sent MMS");
     getSentMMSinfo();
    }    
          
   }
   else{
    // it's SMS
          Log.v("Debug", "it's SMS"); 
          
          //now we need to decide SMS message is sent or received
          Uri mUri = Uri.parse("content://sms");          
          Cursor mCursor = contentResolver.query(mUri, null, null, 
            null, null);
          mCursor.moveToNext();
    int type = mCursor.getInt(mCursor.getColumnIndex("type"));
    
    if(type==1){
     //it's received SMS
     Log.v("Debug", "it's received SMS");
     getReceivedSMSinfo();
    }
    else if(type==2)
    {
     //it's sent SMS
     Log.v("Debug", "it's sent SMS");     
     getSentSMSinfo();
    }
   }//message content type block closed
   
  
  }//on changed closed
  
  
 /*now Methods start to getting details for sent-received SMS*/

  

  //method to get details about received SMS..........
  private void getReceivedSMSinfo() {
   Uri uri = Uri.parse("content://sms/inbox");
   String str = "";
   Cursor cursor = contentResolver.query(uri, null,
     null,null, null);
   cursor.moveToNext();     
   
   // 1 = Received, etc.
   int type = cursor.getInt(cursor.
     getColumnIndex("type"));
   String msg_id= cursor.getString(cursor.
     getColumnIndex("_id"));
   String phone = cursor.getString(cursor.
     getColumnIndex("address"));
   String dateVal = cursor.getString(cursor.
     getColumnIndex("date"));   
   String body = cursor.getString(cursor.
     getColumnIndex("body"));
   Date date = new Date(Long.valueOf(dateVal));
    
      str = "Received SMS: \n phone is: " + phone;
      str +="\n SMS type is: "+type;
   str +="\n SMS time stamp is:"+date;
   str +="\n SMS body is: "+body;
   str +="\n id is : "+msg_id;
    
   
   Log.v("Debug","Received SMS phone is: "+phone);
   Log.v("Debug","SMS type is: "+type);
   Log.v("Debug","SMS time stamp is:"+date);
   Log.v("Debug","SMS body is: "+body);
   Log.v("Debug","SMS id is: "+msg_id);
   
   Toast.makeText(getBaseContext(), str, 
     Toast.LENGTH_SHORT).show();
   Log.v("Debug", "RDC : So we got all informaion " +
     "about SMS Received Message :) ");
   
  }

  //method to get details about Sent SMS...........
  private void getSentSMSinfo() {
   Uri uri = Uri.parse("content://sms/sent");
   String str = "";
   Cursor cursor = contentResolver.query(uri, null, 
     null, null, null);
   cursor.moveToNext();     
   
   // 2 = sent, etc.
   int type = cursor.getInt(cursor.
     getColumnIndex("type"));
   String msg_id= cursor.getString(cursor.
     getColumnIndex("_id"));
   String phone = cursor.getString(cursor.
     getColumnIndex("address"));
   String dateVal = cursor.getString(cursor.
     getColumnIndex("date"));   
   String body = cursor.getString(cursor.
     getColumnIndex("body"));
   Date date = new Date(Long.valueOf(dateVal));
    
      str = "Sent SMS: \n phone is: " + phone;
      str +="\n SMS type is: "+type;
   str +="\n SMS time stamp is:"+date;
   str +="\n SMS body is: "+body;
   str +="\n id is : "+msg_id;
    
   
   Log.v("Debug","sent SMS phone is: "+phone);
   Log.v("Debug","SMS type is: "+type);
   Log.v("Debug","SMS time stamp is:"+date);
   Log.v("Debug","SMS body is: "+body);
   Log.v("Debug","SMS id is: "+msg_id);
   
   Toast.makeText(getBaseContext(), str, 
     Toast.LENGTH_SHORT).show();
   Log.v("Debug", "RDC : So we got all informaion " +
     "about Sent SMS Message :) ");
  }
  
  
  /*now Methods start to getting details for sent-received MMS.*/
  
  // 1. method to get details about Received (inbox)  MMS...
  private void getReceivedMMSinfo() {
   Uri uri = Uri.parse("content://mms/inbox");
   String str = "";
   Cursor cursor = getContentResolver().query(uri, null,null, 
     null, null);
   cursor.moveToNext(); 
   
   String mms_id= cursor.getString(cursor.
     getColumnIndex("_id"));
   String phone = cursor.getString(cursor.
     getColumnIndex("address"));
   String dateVal = cursor.getString(cursor.
     getColumnIndex("date"));
   Date date = new Date(Long.valueOf(dateVal));
   
   // 2 = sent, etc.
   int mtype = cursor.getInt(cursor.
     getColumnIndex("type"));
   String body="";
   
   Bitmap bitmap;
   
   String type = cursor.getString(cursor.
     getColumnIndex("ct"));
   if ("text/plain".equals(type)){
    String data = cursor.getString(cursor.
      getColumnIndex("body"));
    if(data != null){
      body = getReceivedMmsText(mms_id);
    }
    else {
                 body = cursor.getString(cursor.
                   getColumnIndex("text"));
                 //body text is stored here
             }
    }
   else if("image/jpeg".equals(type) ||
     "image/bmp".equals(type) ||
                 "image/gif".equals(type) || 
                 "image/jpg".equals(type) ||
                 "image/png".equals(type)){
     bitmap = getReceivedMmsImage(mms_id);
     //image is stored here
     //now we are storing on SDcard
     storeMmsImageOnSDcard(bitmap);
   }
   
      str = "Sent MMS: \n phone is: " + phone;
      str +="\n MMS type is: "+mtype;
   str +="\n MMS time stamp is:"+date;
   str +="\n MMS body is: "+body;
   str +="\n id is : "+mms_id;
    
   
   Log.v("Debug","sent MMS phone is: "+phone);
   Log.v("Debug","MMS type is: "+mtype);
   Log.v("Debug","MMS time stamp is:"+date);
   Log.v("Debug","MMS body is: "+body);
   Log.v("Debug","MMS id is: "+mms_id);
   
   Toast.makeText(getBaseContext(), str, 
     Toast.LENGTH_SHORT).show();
   Log.v("Debug", "RDC : So we got all informaion " +
     "about Received MMS Message :) ");
  }
  
  
  

  //method to get Text body from Received MMS.........
  private String getReceivedMmsText(String id) {
      Uri partURI = Uri.parse("content://mms/inbox" + id);
      InputStream is = null;
      StringBuilder sb = new StringBuilder();
      try {
          is = getContentResolver().openInputStream(partURI);
          if (is != null) {
              InputStreamReader isr = new InputStreamReader(is,
                "UTF-8");
              BufferedReader reader = new BufferedReader(isr);
              String temp = reader.readLine();
              while (temp != null) {
                  sb.append(temp);
                  temp = reader.readLine();
              }
          }
      } catch (IOException e) {}
      finally {
          if (is != null) {
              try {
                  is.close();
              } catch (IOException e) {}
          }
      }
      return sb.toString();
  }
  
  //method to get image from Received MMS..............
  private Bitmap getReceivedMmsImage(String id) {
   

      Uri partURI = Uri.parse("content://mms/inbox" + id);
      InputStream is = null;
      Bitmap bitmap = null;
      try {
          is = getContentResolver().
            openInputStream(partURI);
          bitmap = BitmapFactory.decodeStream(is);
      } catch (IOException e) {}
      finally {
          if (is != null) {
              try {
                  is.close();
              } catch (IOException e) {}
          }
      }
      return bitmap;
  
  }
  
  //Storing image on SD Card
  private void storeMmsImageOnSDcard(Bitmap bitmap) {
   try {
    
    substr = "A " +k +".PNG";
    String extStorageDirectory = Environment.
      getExternalStorageDirectory().toString();
    File file = new File(extStorageDirectory, substr);
    OutputStream outStream = new FileOutputStream(file);
    bitmap.compress(Bitmap.CompressFormat.PNG, 
      100,outStream);
    outStream.flush();
    outStream.close();

    Toast.makeText(getApplicationContext(), "Image Saved", 
      Toast.LENGTH_LONG).show();
    Log.v("Debug", "Image seved sucessfully");
   }
   catch (FileNotFoundException e) {
    
    e.printStackTrace();
    Toast.makeText(getApplicationContext(), 
      e.toString(),
      Toast.LENGTH_LONG).show();
   } catch (IOException e) {
    
    e.printStackTrace();
    Toast.makeText(getApplicationContext(), 
      e.toString(),
      Toast.LENGTH_LONG).show();
   }
   k++;   
  }
  
  

  /* .......methods to get details about Sent MMS.... */
  private void getSentMMSinfo() {
   

   Uri uri = Uri.parse("content://mms/sent");
   String str = "";
   Cursor cursor = getContentResolver().query(uri, 
     null,null,
     null, null);
   cursor.moveToNext(); 
   
   String mms_id= cursor.getString(cursor.
     getColumnIndex("_id"));
   String phone = cursor.getString(cursor.
     getColumnIndex("address"));
   String dateVal = cursor.getString(cursor.
     getColumnIndex("date"));
   Date date = new Date(Long.valueOf(dateVal));
   // 2 = sent, etc.
   int mtype = cursor.getInt(cursor.
     getColumnIndex("type"));
   String body="";
   
   Bitmap bitmap;
   
   String type = cursor.getString(cursor.
     getColumnIndex("ct"));
   if ("text/plain".equals(type)){
    String data = cursor.getString(cursor.
      getColumnIndex("body"));
    if(data != null){
      body = getSentMmsText(mms_id);
    }
    else {
                 body = cursor.getString(cursor.
                   getColumnIndex("text"));
                 //body text is stored here
             }
    }
   else if("image/jpeg".equals(type) || 
     "image/bmp".equals(type) ||
                 "image/gif".equals(type) || 
                 "image/jpg".equals(type) ||
                 "image/png".equals(type)){
     bitmap = getSentMmsImage(mms_id);
     //image is stored here
     //now we are storing on SDcard
     storeMmsImageOnSDcard(bitmap);
   }
   
      str = "Sent MMS: \n phone is: " + phone;
      str +="\n MMS type is: "+mtype;
   str +="\n MMS time stamp is:"+date;
   str +="\n MMS body is: "+body;
   str +="\n id is : "+mms_id;
    
   
   Log.v("Debug","sent MMS phone is: "+phone);
   Log.v("Debug","MMS type is: "+mtype);
   Log.v("Debug","MMS time stamp is:"+date);
   Log.v("Debug","MMS body is: "+body);
   Log.v("Debug","MMS id is: "+mms_id);
   
   Toast.makeText(getBaseContext(), str, 
     Toast.LENGTH_SHORT).show();
   Log.v("Debug", "RDC : So we got all informaion " +
     "about Sent MMS Message :) ");
  
  }

  
  //method to get Text body from Sent MMS............
  private String getSentMmsText(String id) {   

      Uri partURI = Uri.parse("content://mms/sent" + id);
      InputStream is = null;
      StringBuilder sb = new StringBuilder();
      try {
          is = getContentResolver().openInputStream(partURI);
          if (is != null) {
              InputStreamReader isr = new InputStreamReader(is,
                "UTF-8");
              BufferedReader reader = new BufferedReader(isr);
              String temp = reader.readLine();
              while (temp != null) {
                  sb.append(temp);
                  temp = reader.readLine();
              }
          }
      } catch (IOException e) {}
      finally {
          if (is != null) {
              try {
                  is.close();
              } catch (IOException e) {}
          }
      }
      return sb.toString();
  
  }
  
  //method to get image from sent MMS............
  private Bitmap getSentMmsImage(String id) {
   
      Uri partURI = Uri.parse("content://mms/sent" + id);
      InputStream is = null;
      Bitmap bitmap = null;
      try {
          is = getContentResolver().
            openInputStream(partURI);
          bitmap = BitmapFactory.decodeStream(is);
      } catch (IOException e) {}
      finally {
          if (is != null) {
              try {
                  is.close();
              } catch (IOException e) {}
          }
      }
      return bitmap; 
  
  }
  
 }//smsObserver class closed
}


dont forget to write entries for permissions and service

AndroidManifest.xml
  


    
    
     
 
 
 
 
 
 
  

    
        
            
                
                
            
        
        
          
          
              
              
        
      

    


This code is tested on Emulator for SMS and output will be like this..
For Receiving Text SMS:

For Sending Text SMS:

Thanks!!

any suggestions will be appreciated :)

Wednesday, October 5, 2011

How to call Activity's Method from Service/Adapter or any java class

Some time we need to call the Activity's method from outside the Activity like any Service/Adapter or any java class. So for that i have created this very simple example.

we need to do two steps.
  1. get the instance of Activity in Service.
  2. call Activity class method from Service
so lets try this small app..

-------------------------------------------
App Name: CallActivityMthodFromService
Package Name: com.rdc
Android SDK: Android SDK 2.3.3 / API 10
Default Activity Name: MyActivity
-------------------------------------------

 MyActivity.java
package com.rdc;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;

public class MyActivity extends Activity {

	static MyActivity instance;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		instance = this;
		Intent myIntent = new Intent(getBaseContext(), MyService.class);
		startService(myIntent);
	}

	public void showToast() {
		Toast.makeText(getBaseContext(), "called from ervice", 1).show();

	}
}

MyService.java
package com.rdc;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;

public class MyService extends Service {

	@Override
	public IBinder onBind(Intent i) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public void onCreate() {
		Log.v("Debug", "Service has been Created..");
		// code to execute when the service is first created
	}

	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.v("Debug", "Service has been Started..");
		Toast.makeText(getBaseContext(), "Service has been Started..",
				Toast.LENGTH_SHORT).show();

		// getting the static instance of activity
		MyActivity activity = MyActivity.instance;

		if (activity != null) {
			// we are calling here activity's method
			activity.showToast();
		}

		return START_STICKY;
	}

}


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">
	<TextView
		android:layout_width="fill_parent"
		android:layout_height="wrap_content"
		android:text="@string/hello" />
</LinearLayout>


and Manifest file will be
<?xml version="1.0" encoding="utf-8"?>
<manifest
	xmlns:android="http://schemas.android.com/apk/res/android"
	package="com.rdc"
	android:versionCode="1"
	android:versionName="1.0">
	<uses-sdk android:minSdkVersion="10" />

	<application
		android:icon="@drawable/icon"
		android:label="@string/app_name">
		<activity
			android:name=".MyActivity"
			android:label="@string/app_name">
			<intent-filter>
			<action android:name="android.intent.action.MAIN" />
			<category android:name="android.intent.category.LAUNCHER" />
			</intent-filter>
		</activity>
		<service
			android:enabled="true"
			android:name=".MyService" />

	</application>
</manifest>


The output Screen will be like this..


You can download the complete source code zip file here : CallActivityMthodFromService 

 cheers!!

 I'd love to hear your thoughts!

Thursday, July 28, 2011

Activity Lifecycle

I’m just starting with Android App Development, and if you are a beginner like me, you probably want to understand two of main concepts of Android: Activities and Intents.
After Hello World Example i wanted to know Activity Life-cycle so i learn this and sharing with you..
This is the Android Activity Life Cycle Diagram described by Google

 As you can see in diagram there 7 method in activity base class for life cycle :
onCreate(Bundle savedInstanceState)
This method is Called when the activity is first created.

onStart()
This method is Called when activity is becoming visible to the user.

onResume()
This method is Called when the activity will start interacting with the user.

onPause()
This method is Called when the system is about to start resuming a previous activity.

onStop()
This method is Called when the activity is no longer visible to the user, because another activity has been resumed and is covering this one.
    
onRestart()
This method is Called after your activity has been stopped, prior to it being started again.

onDestroy()
This method is The final call you receive before your activity is destroyed.

Other Methods:
onSaveInstanceState(Bundle outState)
This method is called before an activity may be killed so that when
it comes back some time in the future it can restore its state.

onRestoreInstanceState(Bundle savedInstanceState)
This method is called after onStart() when the activity is being
re-initialised from a previously saved state.
The default implementation of this method performs a restore of any
view state that had previously been frozen by onSaveInstanceState(Bundle).

Create a simple android app with default activity "MyActivity" then put the code like this
  
package com.rdc;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;

public class MyActivity extends Activity {
 private final static String TAG="In this method: ";
    
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Toast.makeText(this, "onCreate", Toast.LENGTH_SHORT).show();
        Log.i(TAG,"Activity created");
    }
 
 @Override
    protected void onStart() {    
    super.onStart();    
    Toast.makeText(this, "onStart",Toast.LENGTH_SHORT).show();
    Log.i(TAG,"Activity started and visible to user");
    }
 
 @Override
    protected void onResume() {
    super.onResume();
    Toast.makeText(this, "onResume", Toast.LENGTH_SHORT).show();
    Log.i(TAG,"Activity interacting with user");
 }

    @Override
    protected void onPause() {
    super.onPause();     
     Toast.makeText(this, "onPause", Toast.LENGTH_SHORT).show();
     Log.i(TAG,"current activity got paused");
    }
    
    @Override
    protected void onStop() {    
    super.onStop();
    Toast.makeText(this, "onStop", Toast.LENGTH_SHORT).show();
    Log.i(TAG," current activity got stopped");
    }
    
    @Override
    protected void onRestart() {
    super.onRestart();
    Toast.makeText(this, "onRestart", Toast.LENGTH_SHORT).show();
    Log.i(TAG,"activity again restarted");
    } 
    
    @Override
    protected void onDestroy() {    
    super.onDestroy();
    Toast.makeText(this, "onDestroy", Toast.LENGTH_SHORT).show();
    Log.i(TAG,"activity destored");
    } 
   
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    Toast.makeText(getBaseContext(),"onSaveInstanceState..BUNDLING", 
      Toast.LENGTH_SHORT).show();
    Log.i(TAG,"activity data saved");
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState(savedInstanceState);
    Toast.makeText(getBaseContext(), "onRestoreInstanceState ..BUNDLING", 
      Toast.LENGTH_SHORT).show();
    Log.i(TAG,"activity previous saved data restored");
    }   
    
}

and main.xml is
  


    



the most important is AndroidManifest.xml
  


    

    
        
            
                
                
            
        

    


you can find the example zip file is here

cheers!!

I'd love to hear your thoughts!