Wednesday, May 30, 2012

Pass Data Between Activities in Android?: Part 4


In Android, we can inherit the Application class to achieve application-level global variables, this method of global variables is relatively static class more secure, and will be released until after the application's All Activities destroy out.

In the Activity, we can use getApplication() method to obtain the Application, it is representative of the class of our application, it can get the theme of the current application, the content in the resource file, this class is more flexible a feature can we have inherited, to add our own global properties.

All the Activity of the same application can take the value of these global variables, in other words, we change the value of these global variables in an Activity, then in the same value will change in an application Activity. The following example details the application steps:

STEP 1:: Write Application Subclass


public class MyApplication extends Application { //Variable we want to share to All Activities in Appliction private static final String NAME = "MyApplication"; private String name; @Override public void onCreate() { super.onCreate(); setName(NAME); //Initialize global variables } //Getter Method public String getName() { return name; } //Setter Method public void setName(String name) { this.name = name; } }


STEP 2: In the Manifest.xml Register MyApplication as:


<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.hisoft.app" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:name=".MyApplication"> <activity android:name=".MyFirstActivity" android:label="@string/app_name">


STEP 3: In the MyFirstActivity :


public class MyFirstActivity extends Activity { private MyApplication app; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); app = (MyApplication)getApplication(); //Get Application //Access global value Log.e("MyFirstActivityOriginal", app.getName()); app.setName("Android Android"); //Set global value Log.e("MyFirstActivityChanged", app.getName()); Intent intent = new Intent(); intent.setClass(this, MySecondActivity.class); startActivity(intent); } }


STEP 4: In the MySecondActivity :


public class MySecondActivity extends Activity { private MyApplication app; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //Get Application app = (MyApplication)getApplication(); //Access global value Log.e("MySecondActivity", app.getName()); } }




Download Source Code: Applicationclass









Tuesday, May 29, 2012

Pass Data Between Activities in Android?: Part 3

 You can Pass Data Between Activities using android.os.Bundle object which encapsulates data as key-value pairs.

   In SenderActivity.java Activtiy :



//Create new Intent Object, and specify class Intent intent = new Intent(); intent.setClass(SenderActivity.this,Receiveractivity.class); //new Bundle Object, and put data in bundle object Bundle bundle = new Bundle(); bundle.putString("senddata","This is From SenderActivity.class"); //Put Bundle object i.e bundle in intent intent.putExtras(bundle); //Call startActivity to start new Activity SenderActivity.this.startActivity(intent);


   In SenderActivity.java Activtiy :



//Intent To obtain the bundle object from SenderActivity Bundle bundle = this.getIntent().getExtras(); if(bundle !=null) { //ObtainBundleData in the object String strdata = bundle.getString("senddata"); //Do something here if data received } else { //Do something here if data not received }



Download Source Code: Intentpassdata_using_bundle








Monday, May 28, 2012

Pass Data Between Activities in Android?: Part 2

 You can pass data between to Activities using Intent.Example:

   In Activtiy SenderActivity.java:



//Create new Intent Object, and specify class Intent intent = new Intent(); intent.setClass(SenderActivity.this,Receiveractivity.class); //Set your data using putExtra method which take //any key and value which we want to send intent.putExtra("senddata","This is From SenderActivity.class"); //Use startActivity or startActivityForResult for Starting New Activity SenderActivity.this.startActivity(intent);


   In Activtiy SenderActivity.java :



//obtain Intent Object send from SenderActivity Intent intent = this.getIntent(); /* Obtain String from Intent */ if(intent !=null) { String strdata = intent.getExtras().getString("senddata"); // DO SOMETHING HERE } else { // DO SOMETHING HERE }



Download Source Code: Intentpassdata








Sunday, May 27, 2012

Pass Data Between Activities in Android? : Part 1


 There are two data types available in Java/Android:
  Primitive Data Types :
      byte, int, long, float, boolean...
  Reference/Object Data Types :
      String,Class objects, and various type of array variables come under reference data type.


Way of passing data Between Application's Components :
  1. By Using Intent
  2. By Using Bundle and Intent
  3. By Using Appliction Class
  4. By Using Static Class

Saturday, May 26, 2012

Pass Custom Object Using Parcelable: Android


Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient that Serializable, and to get around some problems with the default Java serialization scheme.
Serialization in Java is far too slow to satisfy Android’s interprocess-communication requirements. The Parcelable approach requires that you explicitly serialize the members of your class, but in the end, you get a much faster serialization of your objects.
The writeToParcel Method:
The writeToParcel method is implemented quite easy as well. The Parcel interface contains methods to write primitve java types such as string, int, etc. We can use these methods to store the object state within the parcel.
public void writeToParcel(Parcel outParcel, int flags) {
//Write data to Parcel
outParcel.writeString(message);
.....
}

For the demarshalling, we need to remember the sequence in which we have stored the fields in the parcel.
The Parcelable.Creator CREATOR field:
The CREATOR field is required for the demarshalling. As previously described, the Parcelable.Creator interface requires us to implement two methods:
public static final Parcelable.Creator 
CREATOR = new Parcelable.Creator() {
@Override
public YOUR_CLASS_NAME createFromParcel(Parcel in) {
From ParcelTo read data,Return YOUR_CLASS_NAME Object 
String message = in.readString();
.....
return new YOUR_CLASS_NAME(Params...); //YOUR_CLASS_NAME constructor
}

During the createFromParcel method we use the read methods which are provided in the Parcel to extract our state information. In the end we create a new class object with the corresponding state.

Example Pass data by implemeting Parcelable interface:
    Car.java implemeting Parcelable interface: :
package com.imrankhanandroid.PassdatausingParcelable;
import android.os.Parcel;
import android.os.Parcelable;

public class Car implements Parcelable {

    private String CarName;  
    private String companyName;  
    private int contactNum;
    public String getCarName() {  
        return CarName;  
    }  
    public void setCarName(String CarName) {  
        this.CarName = CarName;  
    }  
    public String getCompanyName() {  
        return companyName;  
    }  
    public void setCompanyName(String companyName) {  
        this.companyName = companyName;  
    }  
    public int getContactNum() {  
        return contactNum;  
    }  
    public void setcontactNum(int contactNum) {  
        this.contactNum = contactNum;  
    }  
    public static final Parcelable.Creator CREATOR =new Creator() {

  @Override
  public Car createFromParcel(Parcel source) {
   // TODO Auto-generated method stub
   Car mCar=new Car();
   mCar.CarName=source.readString();
   mCar.companyName=source.readString();
   mCar.contactNum=source.readInt();
   return mCar;
  }

  @Override
  public Car[] newArray(int size) {
   // TODO Auto-generated method stub
   return new Car[size];
  }
 };
 @Override
 public int describeContents() {
  // TODO Auto-generated method stub
  return 0;
 }

 @Override
 public void writeToParcel(Parcel parcel, int flags) {
  // TODO Auto-generated method stub
  parcel.writeString(CarName);
  parcel.writeString(companyName);
  parcel.writeInt(contactNum);
 }

}

    ObjectSenderActivity.java Activity: :
package com.imrankhanandroid.PassdatausingParcelable;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class ObjectSenderActivity extends Activity {
 private Button sButton;  
    public  final static String PAR_KEY = "com.imrankhanandroid.PassdatausingParcelable.par";  

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sButton = (Button)findViewById(R.id.btnsend); 
        sButton.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    PacelableMethod();
   }
  });
    }
  //PacelablePassing an object method
    public void PacelableMethod(){  
        Car mCar = new Car();  
        mCar.setCarName("jaguar xf sedan");  
        mCar.setCompanyName("jaguar");  
        mCar.setcontactNum(123456789);  
        Intent mIntent = new Intent(this,ObjectReceiverActivity.class);  
        Bundle mBundle = new Bundle();  
        mBundle.putParcelable(PAR_KEY, mCar);  
        mIntent.putExtras(mBundle);  
          
        startActivity(mIntent);  
    }  
}

    ObjectReceiverActivity.java Activity: :
package com.imrankhanandroid.PassdatausingParcelable;
import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;


public class ObjectReceiverActivity extends Activity {
 TextView txtview;
  /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.maintwo);
       //Get person object from Intent deliver to ObjectReceiverActivity
       Car mCar = (Car)getIntent().getParcelableExtra(ObjectSenderActivity.PAR_KEY);
       txtview=(TextView)findViewById(R.id.txtrev);
       txtview.append(Html.fromHtml("
Car Name :"+mCar.getCarName() +"
Company Name :"+mCar.getCompanyName() +"
Contact Num :"+mCar.getContactNum() )); } }

    src/layout/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" >

<TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="Welcome to Imran Khan's Blog."
    android:gravity="center"  
    android:layout_marginTop="80dp"
    />  
    <TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="Object Sender Activity"
    android:gravity="center"  
    android:layout_marginTop="80dp"
    /> 
<Button  
    android:id="@+id/btnsend"  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="Send Parcelable Object" 
    android:textSize="25px" 
    android:layout_marginTop="15dp"
/> 
</LinearLayout>


    src/layout/maintwo.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" >
    <TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="Obecjt Reciver Activity"
    android:gravity="center"  
    android:layout_marginTop="80dp"
    android:textSize="25px"
    /> 
    <TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="Data Recived from Sender Activity:-"
    android:layout_marginTop="80dp"
    android:id="@+id/txtrev"
    android:textSize="25px"
    /> 
</LinearLayout>


    AndroidManifest.xml: :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.imrankhanandroid.PassdatausingParcelable"
    android:versionCode="1"
    android:versionName="1.0" >
    <uses-sdk android:minSdkVersion="7" />
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="@string/app_name"
            android:name=".ObjectSenderActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ObjectReceiverActivity"></activity>
    </application>
</manifest>

Download Source Code: PassdatausingParcelable









Friday, May 25, 2012

Pass Custom Object Using Serializable : Android


Serialization is a process of reading or writing an object. It is a process of saving an object’s state to a sequence of bytes, as well as a process of rebuilding those bytes back into a live object at some future time. An object is marked serializable by implementing the java.io.Serializable interface, which is only a marker interface -- it simply allows the serialization mechanism to verify that the class can be persisted, typically to a file.
Transient variables cannot be serialized. The fields marked transient in a serializable object will not be transmitted in the byte stream. An example would be a file handle, a database connection, a system thread etc. Such objects are only meaningful locally. So they should be marked as transient in a serializable class.
Serialization can adversely affect performance since it:
  • Depends on reflection.
  • Has an incredibly verbose data format.
  • Is very easy to send surplus data..

Example Pass Custom Object by implementing Serializable interface:
   Create Person.java an Serializable class: :
package com.imrankhanandroid.Passdserialzedata;

import java.io.Serializable;

//Person Serializable Class
public class Person implements Serializable {
 //serialVersionUID generated by serialver tool.
 private static final long serialVersionUID = 10275439472837494L; 
    private String name;  
    private int age;  
    public String getName() {  
        return name;  
    }  
    public void setName(String name) {  
        this.name = name;  
    }  
    public int getAge() {  
        return age;  
    }  
    public void setAge(int age) {  
        this.age = age;  
    }  
}

   Create ObejctSenderActivity Activity: :
package com.imrankhanandroid.Passdserialzedata;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class ObejctSenderActivity extends Activity {
 private Button sButton;  
    public  final static String SER_KEY = 
            "com.imrankhanandroid.Passdserialzedata.ser";  

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        sButton = (Button)findViewById(R.id.btnsend); 
        sButton.setOnClickListener(new View.OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    SerializeMethod();
   }
  });
    }
  //Serializeable Passing objects  
    public void SerializeMethod(){ 
     //Create an mPerson Object of Person Class
        Person mPerson = new Person();  
        mPerson.setName("Imran Khan");  
        mPerson.setAge(25);  
        //Create an Intent for Passing to startActivity
        Intent mIntent = new Intent(this,ObjectReceiverActivity.class);  
        Bundle mBundle = new Bundle();  
        //put mPerson in bundle using putSerializable
        mBundle.putSerializable(SER_KEY,mPerson);  
        mIntent.putExtras(mBundle);  
          
        startActivity(mIntent);  
    }  
}

   Create ObjectReceiverActivity Activity: :
package com.imrankhanandroid.Passdserialzedata;

import android.app.Activity;
import android.os.Bundle;
import android.text.Html;
import android.widget.TextView;


public class ObjectReceiverActivity  extends Activity{
 TextView txtview;
  /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.maintwo);
        //Get person object from Intent deliver to ObjectReceiverActivity
        Person mPerson = (Person)getIntent()
        .getSerializableExtra(ObejctSenderActivity.SER_KEY);
        txtview=(TextView)findViewById(R.id.txtrev);
        txtview.append(Html.fromHtml("
Person Name :"+mPerson.getName()
          +"
Person Age :"+mPerson.getAge()));
    }
}

   res/layout/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" >

<TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="Welcome to Imran Khan's Blog."
    android:gravity="center"  
    android:layout_marginTop="80dp"
    />  
    <TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="Object Sender Activity"
    android:gravity="center"  
    android:layout_marginTop="80dp"
    /> 
<Button  
    android:id="@+id/btnsend"  
    android:layout_width="fill_parent"  
    android:layout_height="wrap_content"  
    android:text="Send Serializable Object" 
    android:textSize="25px" 
    android:layout_marginTop="15dp"
/>  

</LinearLayout>


   res/layout/maintwo.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" >
    <TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="Obecjt Reciver Activity"
    android:gravity="center"  
    android:layout_marginTop="80dp"
    android:textSize="25px"
    /> 
    <TextView    
    android:layout_width="fill_parent"   
    android:layout_height="wrap_content"   
    android:text="Data Recived from Sender Activity:-"
    android:layout_marginTop="80dp"
    android:id="@+id/txtrev"
    android:textSize="25px"
    /> 
</LinearLayout>


   res/layout/maintwo.xml: :

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.imrankhanandroid.Passdserialzedata"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="7" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:label="Welcome to Imran Khan's Blog."
            android:name=".ObejctSenderActivity" >
            <intent-filter >
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".ObjectReceiverActivity"></activity>
    </application>

</manifest>

Download Source Code: PassdatausingSerializable









Thursday, May 24, 2012

Android: Handle Screen Orientation

Android:Handle Screen Orientation in Your Application:

1. Lock the Orientation in Current Activity:-
   In the onCreate(Bundle) method of the current activity use the setRequestedOrientation(int) method to set the screen orientation.
The activity will stay in this orientation regardless of if the device is tilted or not.
Java code:
@Override
public void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    this.setRequestedOrientation(
    ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
}


2.  Detect the Current Screen Orientation:-
   Orientation property of the Configuration class returns four possible values corresponding to LANDSCAPE, PORTRAIT, SQUARE and UNDEFINED.
Java Code:
switch(this.getResources().getConfiguration().orientation)
{
case Configuration.ORIENTATION_PORTRAIT:
  // Do something here
  break;
case Configuration.ORIENTATION_LANDSCAPE:
  // Do something here
  break;
case Configuration.ORIENTATION_SQUARE:
  // Do something here
  break;
case Configuration.ORIENTATION_UNDEFINED:
  // Do something here
  break;
default:
  throw new Exception("Unexpected orientation enumeration returned");
  break;
}


3. Re-enable screen rotation for Appliction:-
   To enable the orientation to be automatically changed on device tilt simply pass the setRequestedOrientation(int) method the enumeration value for an unspecified orientation.
// Allow screen rotations again
this.setRequestedOrientation(
ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);


Download Source Code: ScreenorientationApp








Wednesday, May 23, 2012

Android : Way of Using setOnClickListener for an View

I'm going to use most common View Button for Setting onClick event :
Method One:- One Listener for One button:


Button btn = (Button) findViewById(R.id.myButton); btn. SetOnClickListener (new View.OnClickListener() { Public void onClick(View v) the { // Do Something } });


Method Two:- Share One Listener with Multiple buttons:


Button btn = (Button)findViewById(R.id.mybutton); Button btn2 = (Button)findViewById(R.id.mybutton2); btn.setOnClickListener(handler); btn2.setOnClickListener(handler); View.OnClickListener handler = View.OnClickListener() { Public void onClick(View v) the { switch(v.getId()) { case R.id.mybutton: // Do Something break; case R.id.mybutton2: // Do Something break; } }


Method Three:- Clicklistener bundled with an XML the layout of the Views element, Listener methods defined in the program with a View type of parameters as:


Buttontst.Xml : java code:: Button btn = (Button) findViewById(R.id.mybutton); public void mybuttonlistener(View target){ //do something }








Tuesday, May 22, 2012

Android open the System Settings interface : Android

Often need to open the system settings interface:

1. Open WirelessSettings:

Intent intent = new Intent("/"); ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.WirelessSettings"); intent.setComponent(cm); intent.setAction("android.intent.action.VIEW"); Activity.this.startActivityForResult( intent , 0);

2. Open GPS Settings:

Intent intent = new Intent(android.provider. Settings.ACTION_LOCATION_SOURCE_SETTINGS); Activity.this.startActivityForResult( intent , 0);

3. Open Development Settings:

Intent intent = new Intent("/"); ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.DevelopmentSettings"); intent.setComponent(cm); intent.setAction("android.intent.action.VIEW"); Activity.this.startActivityForResult( intent , 0);

4. Open Activity Picker:

Intent intent = new Intent("/"); ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.ActivityPicker"); intent.setComponent(cm); intent.setAction("android.intent.action.VIEW"); Activity.this.startActivityForResult( intent , 0);

5. Open Language Settings

Intent intent = new Intent("/"); ComponentName cm = new ComponentName("com.android.settings", "com.android.settings.LanguageSettings"); intent.setComponent(cm); intent.setAction("android.intent.action.VIEW"); Activity.this.startActivityForResult( intent , 0);

In same way use the following fields directly to open the corresponding system interface:

com.android.settings.AccessibilitySettings //Accessibility settings com.android.settings.ActivityPicker //Select activities com.android.settings.ApnSettings // APN settings com.android.settings.ApplicationSettings // Application Settings com.android.settings.BandMode // GSM / UMTS bands com.android.settings.BatteryInfo // battery information com.android.settings.DateTimeSettings //date and time setting com.android.settings.DateTimeSettingsSetupWizard //date and time settings Wizard com.android.settings.DevelopmentSettings //application settings com.android.settings.DeviceAdminSettings //device manager com.android.settings.DeviceInfoSettings // mobile phones info com.android.settings.Display - //Set the font size com.android.settings.DisplaySettings //display settings com.android.settings.DockSettings //base settings com.android.settings.IccLockSettings //SIM card lock settings com.android.settings.InstalledAppDetails //Installed Application Details com.android.settings.LanguageSettings //language and keyboard settings com.android.settings.LocalePicker //select the phone language com.android.settings.MasterClear //restore factory settings com.android.settings.MediaFormat //formatting the phone memory com.android.settings.PhysicalKeyboardSettings //set the keyboard com.android.settings.PrivacySettings //privacy settings com.android.settings.ProxySelector //proxy settings com.android.settings.RadioInfo //phone information com.android.settings.RunningServices //running programs (services) com.android.settings.SecuritySettings //location and security settings com.android.settings.Settings //system settings com.android.settings.SettingsSafetyLegalActivity //safety information com.android.settings.SoundSettings //sound settings com.android.settings.TestingSettings // Displays the phone, battery, usage statistics, Wifi information, service information com.android.settings.TetherSettings //Tethring Settings com.android.settings.UsageStats //Usage statistics com.android.settings.UserDictionarySettings // user dictionary











Sunday, May 20, 2012

Android: TimerTask Example



The TimerTask class represents a task to run at a specified time. The task may be run once or repeatedly.

TimerTask Class Methods:


TimerTask Example:

TimerTaskExample.java:



package com.imrankhanandroid.TimerTaskExamp; import java.util.Timer; import java.util.TimerTask; import android.util.Log; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.view.View; import android.widget.Button; import android.widget.TextView; public class TimerTaskExample extends Activity { /** Called when the activity is first created. */ private static String TAG = "TimerTaskExample"; private TextView mTextView = null; private Button mButton_start = null; private Button mButton_pause = null; private Timer mTimer = null; private TimerTask mTimerTask = null; private Handler mHandler = null; private static int count = 0; private boolean isPause = false; private boolean isStop = true; private static int delay = 1000; //1s private static int period = 1000; //1s private static final int UPDATE_TEXTVIEW = 0; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mTextView = (TextView)findViewById(R.id.mytextview); mButton_start = (Button)findViewById(R.id.mybutton_start); mButton_pause = (Button)findViewById(R.id.mybutton_pause); mButton_start.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if (isStop) { Log.i(TAG, "Start"); } else { Log.i(TAG, "Stop"); } isStop = !isStop; if (!isStop) { startTimer(); }else { stopTimer(); } if (isStop) { mButton_start.setText(R.string.start); } else { mButton_start.setText(R.string.stop); } } }); mButton_pause.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { if (isPause) { Log.i(TAG, "Resume"); } else { Log.i(TAG, "Pause"); } isPause = !isPause; if (isPause) { mButton_pause.setText(R.string.resume); } else { mButton_pause.setText(R.string.pause); } } }); mHandler = new Handler(){ @Override public void handleMessage(Message msg) { switch (msg.what) { case UPDATE_TEXTVIEW: updateTextView(); break; default: break; } } }; } private void updateTextView(){ mTextView.setText(String.valueOf(count)); } private void startTimer(){ if (mTimer == null) { mTimer = new Timer(); } if (mTimerTask == null) { mTimerTask = new TimerTask() { @Override public void run() { Log.i(TAG, "count: "+String.valueOf(count)); sendMessage(UPDATE_TEXTVIEW); do { try { Log.i(TAG, "sleep(1000)..."); Thread.sleep(1000); } catch (InterruptedException e) { } } while (isPause); count ++; } }; } if(mTimer != null && mTimerTask != null ) mTimer.schedule(mTimerTask, delay, period); } private void stopTimer(){ if (mTimer != null) { mTimer.cancel(); mTimer = null; } if (mTimerTask != null) { mTimerTask.cancel(); mTimerTask = null; } count = 0; } public void sendMessage(int id){ if (mHandler != null) { Message message = Message.obtain(mHandler, id); mHandler.sendMessage(message); } } }




main.xml:



strings.xml.xml:


TimerTaskExample 0 start stop pause resume


Download Source Code: TimerTaskExample








Android : CountDownTimer



CountDownTimer is used for Schedule a countdown until a time in the future, with regular notifications on intervals along the way.

CountDownTimer methods:


CountDownTimer Example:

RunOnUiThreadExample.java:


package com.imrankhanandroid.CountDownTimer; import android.app.Activity; import android.os.Bundle; import android.os.CountDownTimer; import android.widget.TextView; import android.widget.Toast; public class CountDownTimerExample extends Activity { /** Called when the activity is first created. */ private MyCount mc; private TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); tv = (TextView)findViewById(R.id.show); mc = new MyCount(30000, 1000); mc.start(); } /* Define a countdown internal class */ class MyCount extends CountDownTimer { public MyCount(long millisInFuture, long countDownInterval) { super(millisInFuture, countDownInterval); } @Override public void onFinish() { tv.setText("finish!!!"); } @Override public void onTick(long millisUntilFinished) { tv.setText("Please wait for 30 seconds." + "(" + millisUntilFinished / 1000 + ")..."); //Toast show the time delay Toast.makeText(CountDownTimerExample.this, millisUntilFinished / 1000 + "", Toast.LENGTH_LONG).show(); } } }




main.xml:




Download Source Code: CountDownTimerExample








runOnUiThread: Update UI Using runOnUiThread



Runs the specified action on the UI thread. If the current thread is the UI thread, then the action is executed immediately. If the current thread is not the UI thread, the action is posted to the event queue of the UI thread.

Example:

RunOnUiThreadExample.java:


package com.imrankhanandroid.runOnUiThreadExmp; import java.text.DateFormat; import java.util.Date; import android.app.Activity; import android.os.Bundle; import android.widget.TextView; public class RunOnUiThreadExample extends Activity { /** Called when the activity is first created. */ TextView txtview; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); txtview=(TextView)findViewById(R.id.txtview); myThread(); } public void myThread(){ Thread th=new Thread(){ @Override public void run(){ try { while(true) { Thread.sleep(100); RunOnUiThreadExample.this.runOnUiThread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub String currentDateTimeString = DateFormat. getDateTimeInstance().format(new Date()); txtview.setText(currentDateTimeString); } }); } }catch (InterruptedException e) { // TODO: handle exception } } }; th.start(); } }




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


Download Source Code: RunOnUiThreadExample









AsyncTask :Update UI Using AsyncTask

The characteristics of AsyncTask is the task to run outside the main thread, the callback method is executed in the main thread, which effectively avoids the use Handler trouble. Read AsyncTask source known the AsyncTask java.util.concurrent framework to manage the threads and the execution of tasks, concurrent framework is a very mature and efficient framework, after rigorous testing. This shows AsyncTask of well-designed to solve the problems of anonymous threads.

if you have any long task to do in backround.You just extend AsyncTask class in somewhrere in code.then,from the main thread, create an instance of your extended class and call the execute method of AsycTask.

Now,there are 3 kinds of data you will be pass or recive back from Asyctask in Ui Thread:
1. Params: The parameters you sent to the backgrund task,i.e. doInBackground(Params...).
2. Progress : The Background job progress units which will pass to UI thread reporting background job progress.
3. Result : The data that will be returned to Ui Thread on task Completion from Background task.

When AsyncTask is executed,it goes through from 4 steps:
A. onPreExecute() :
-Called before Background computation starts on Ui Thread.
-Use for do some setup like,dispay progress dialog.

B. doInBackground(Params...) :
-Called after onPreExecute() on Background Thread.
-Used for perfrom background Computation that can take long time.
-After Background Task Completion result are returned by this step to onPostExecute(result)
-This method invoke publishProgress(Progress... values) for publish updates on the UI Thread while background computation is still running.

C. onProgressUpdate(Progress... values):
-Run on Ui Thread after publishProgress(Progress... values) is invoked from doInBackground(Params...).

D. onPostExecute(Result result) :
-This method invoke on the Ui Thread after the background Computation finishes. the result of the Computation is passed to this step as a parameter.


Example of AsyncTask:
AsyncTaskExampleActivity.java:



package com.imrankhanandroid.AsyncTaskExample; import android.app.Activity; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.widget.Button; import android.widget.ProgressBar; import android.widget.TextView; public class AsyncTaskExampleActivity extends Activity { /** Called when the activity is first created. */ Button download; ProgressBar pb; TextView tv; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); pb=(ProgressBar)findViewById(R.id.pb); tv=(TextView)findViewById(R.id.tv); download = (Button)findViewById(R.id.download); download.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { DownloadTask dTask = new DownloadTask(); dTask.execute(100); } }); } class DownloadTask extends AsyncTask{ // Behind the angle brackets are the parameters (in case the thread rest time), //progress (publishProgress the used), the return value type @Override protected void onPreExecute() { // First execution method super.onPreExecute(); } @Override protected String doInBackground(Integer... params) { // Implementation of the second method, onPreExecute () //after the implementation of the implementation of for(int i=0;i<=100;i++){ pb.setProgress(i); publishProgress(i); try { Thread.sleep(params[0]); } catch (InterruptedException e) { e.printStackTrace(); } } return "Is finished"; } @Override protected void onProgressUpdate(Integer... progress) { // This function is triggered when the doInBackground call // publishProgress call only one parameter // But here taken to be an array, so use progesss[0] to the value // N parameter with progress [n] value tv.setText(progress[0]+"%"); super.onProgressUpdate(progress); } @Override protected void onPostExecute(String result) { // return the doInBackground trigger to change the sentence words, // is doInBackground execution after trigger // where the result is above doInBackground after the execution of // the return value, so here is the finished setTitle(result); super.onPostExecute(result); } } }


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" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello , Welcome to Imran khan's Blog!"/> <Button android:id="@+id/download" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Download"/> <TextView android:id="@+id/tv" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Progress"/> <ProgressBar android:id="@+id/pb" android:layout_width="fill_parent" android:layout_height="wrap_content" style="?android:attr/progressBarStyleHorizontal"/> </LinearLayout>


Download Source Code: AsyncTaskExample








Android : Handler Update UI Thread

Handler allows us to send and process Message and Runnable Objects associated with a thread's MessageQueue.

Why Handler?:
There are two main uses for a Handler:
a)- To Schedule Messages and Runnables to be executed as some point in the future.
b)- To enqueue an action to be performed on a different Thread than our own.

Message?:
Defines a message containing a description and orbitrary data object that can be sent to a Handler.this object contaions two extra fields.

Looper :
It's designed to make an ordinary thread into a Looper Thread.We need this this type of thread because we often need a thread which continuously cycle.if there is a new task execute them and continue to wait for the next task. Looper internally maintains a message queue(Linked Queue).

     NOTE: A Thread can only have a Looper object.

Class used to run a message loop for a thread. Threads by default do not have a Message loop associated with them; to create one, call prepare() in the thread that is to run loop, and then loop() to have it process messages until the loop is stopped.

          Class LooperThread extends Thread{
            public Handler mHandler;
            public void run(){
              Looper.prepare();
              mHandler=new Hanlder(){
                public void handleMessage(Message msg){
                   //process incomming messages here
                 }
              };
              Looper.loop();
            }
          }


Each Handler instance is associated with a single thread and that thread's message queue.

The Handler is the middleman between a new thread and the message queue.


   Note:- When we Create a new Handler,it's bound to the Thread/ MessageQueue of the Thread that is creating it-from that point on,it will deliver messages and runnables to that message queue and execute them as they come out of the queue.


Handler Ball Moving Example:

HandlerUIExample.java :

package com.imrankhanandroid.HandlerExample;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Window;

public class HandlerUIExample extends Activity {
    /** Called when the activity is first created. */
 protected static final int UiUpadte=0x1001;
 Thread myThread=null;
 BounceBallView UiBounceBallview=null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        this.UiBounceBallview=new BounceBallView(this);
        setContentView(this.UiBounceBallview);
        new Thread(new myThread()).start();
    }
    Handler Testhandler=new Handler(){
     public void handleMessage(Message msg){
      switch(msg.what)
      {
      case HandlerUIExample.UiUpadte:
       UiBounceBallview.invalidate();
       break;
      }
      super.handleMessage(msg);
     }
    };
    class myThread implements Runnable{
    /*Worker Thread for Updating UI */
  @Override
  public void run() {
   // TODO Auto-generated method stub
   while(!Thread.currentThread().isInterrupted()){
    Message mesg=new Message();
    mesg.what=HandlerUIExample.UiUpadte;
    HandlerUIExample.this.Testhandler.
                                sendMessage(mesg);
    try{
     Thread.sleep(100);
    }
    catch (InterruptedException  e) {
     // TODO: handle exception
     Thread.currentThread().interrupt();
    }
   }
  }
     
    }
}




BounceBallView.java :



package com.imrankhanandroid.HandlerExample; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.view.View; public class BounceBallView extends View { float x=20; float y=260; float xy=230; float yx=140; float yz=60; float yt=0; public BounceBallView(Context context) { super(context); // TODO Auto-generated constructor stub } @Override protected void onDraw(Canvas canvas) { Paint mPaint =new Paint(); mPaint.setAntiAlias(true); mPaint.setColor(Color.RED); canvas.drawCircle(x, yz, 30, mPaint); mPaint.setColor(Color.GREEN); canvas.drawCircle(x, yx, 30, mPaint); mPaint.setColor(Color.YELLOW); canvas.drawCircle(x, xy, 30, mPaint); if(x==y & x>20 ) { x=y-20; y-=20; yt=yz; yz=yx; yx=yt; } else { yt=yz; yz=yx; yx=yt; x+=10; y=260; } } }


Download Source Code: HandlerExample








Wednesday, May 16, 2012

Update UI Using HandlerThread


HanderThread class inherits from the Thread class, which encapsulates the Looper object, so that we do not care The Looper open and release details.

The HandlerThread object can be getLooper method to obtain a Looper object reference.

Methods in HandlerThread:

. getLooper():  This method returns the Looper associated with this thread.

. getThreadId():   Returns the identifier of this thread

. quit():   Ask the currently running looper to quit.

. run():   Calls the run() method of the Runnable object the receiver holds. If no Runnable is set, does nothing.

ProgressBar Example Using HandlerThread :

main.xml:
    
 <
      <
    




HanderThreadActivity.java :
package com.imrankhanandroid.HanderThread;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

public class HanderThreadActivity extends Activity {
    /** Called when the activity is first created. */
ProgressBar bar;
Button start;
Runnable progressThread;
MyHandler myHandler;
TextView txtprogress;
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Log.v("HanderThreadActivity :", "Activity Thread :"+Thread.currentThread().getId());
        bar=(ProgressBar)findViewById(R.id.bar);
        txtprogress=(TextView)findViewById(R.id.txtprogress);
        start=(Button)findViewById(R.id.startButton);
      //HandlerThread asynchronous thread, not the main thread public
        HandlerThread handlerThread=new HandlerThread("handler_thread");
      //GetLooper() method before you adjust the start() method 
        handlerThread.start();
        myHandler=new MyHandler(handlerThread.getLooper());
        start.setOnClickListener(new OnClickListener() {
   
   @Override
   public void onClick(View v) {
    // TODO Auto-generated method stub
    bar.setVisibility(ProgressBar.VISIBLE);
    myHandler.post(progressThread);
   }
  });
      //Runnable inner class
        progressThread=new Runnable() {
   int percent=0;
   @Override
   public void run() {
    // TODO Auto-generated method stub
    percent +=5;
    Log.v("HanderThreadActivity :", "Runnable  Thread :"+percent+"----"+Thread.currentThread().getId());
    Message msg=new Message();
    //Message object to pass parameters 
    Bundle bundle=new Bundle();
    bundle.putInt("percent", percent);
    msg.setData(bundle);
    myHandler.sendMessage(msg);
    try{
     Thread.sleep(1000);
    }catch (Exception e) {
     // TODO: handle exception
     e.printStackTrace();
    }
   }
  };
 }
 class MyHandler extends Handler{
  public MyHandler(Looper looper){
   super(looper);
  }
  @Override
  public void handleMessage(Message msg){
   Bundle bundle= msg.getData();
   bar.setProgress(bundle.getInt("percent"));
   //MyHandler Thread : 8
   Log.v("HanderThreadActivity :", "MyHandler Thread :"+bundle.getInt("percent")+"---"+Thread.currentThread().getId());
   myHandler.post(progressThread);
   if(bundle.getInt("percent")>=90)
   {
    myHandler.removeCallbacks(progressThread);
   }
  }
 }
}


Download Source Code: HanderThreadExample








 
Powered by Blogger