Mar 31, 2013

Example of ToggleButton

ToggleButton
Example of ToggleButton


<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <ToggleButton
        android:id="@+id/togglebutton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textOn="Button On"
        android:textOff="Button Off" />

</RelativeLayout>


package com.example.androidtogglebutton;

import android.os.Bundle;
import android.app.Activity;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.Toast;
import android.widget.ToggleButton;

public class MainActivity extends Activity {

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  ToggleButton toggleButton = (ToggleButton)findViewById(R.id.togglebutton);
  toggleButton.setOnCheckedChangeListener(new OnCheckedChangeListener(){

   @Override
   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    Toast.makeText(getApplicationContext(), 
      "isChecked : " + String.valueOf(isChecked), 
      Toast.LENGTH_SHORT).show();
    
   }});
 }

}


Mar 26, 2013

Force Activity to have Single Instances

To force a Activity to have a Single Instances, you can include android:launchMode="singleTask" under <activity> in AndroidManifest.xml.

android:launchMode determine how the activity should be launched. With android:launchMode="singleTask", The system creates the activity at the root of a new task and routes the intent to it. However, if an instance of the activity already exists, the system routes the intent to existing instance through a call to its onNewIntent() method, rather than creating a new one.

Example:

force Single Instances for Activity
force Single Instances for Activity


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.androidlaunchmode"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="17" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.example.androidlaunchmode.MainActivity"
            android:label="@string/app_name" 
            android:launchMode="singleTask">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>


package com.example.androidlaunchmode;

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

public class MainActivity extends Activity {
 
 TextView prompt;
 int counter;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  //setContentView(R.layout.activity_main);
  
  prompt = new TextView(this);
  setContentView(prompt);
  
  counter = 0;
  prompt.setText("number of onNewIntent() called = " + counter);
 }

 @Override
 protected void onNewIntent(Intent intent) {
  // TODO Auto-generated method stub
  super.onNewIntent(intent);
  Toast.makeText(getApplicationContext(), 
    "onNewIntent()", 
    Toast.LENGTH_LONG).show();
  counter++;
  prompt.setText("number of onNewIntent() called = " + counter);
 }

}


Mar 24, 2013

Shortcuts: Kick-start Google Maps Android API v2 Development

The video show how to get started with Google Maps Android API v2 in five minutes or less with his Android "hellomap" bootstrap project for Eclipse, IntelliJ, or Ant.



Mar 12, 2013

Detect if it's running in UI thread

To detect if it the code is running in ui thread, use the code:

Looper.getMainLooper().getThread() == Thread.currentThread()

Example:

detect if it the code is running in ui thread
detect if it the code is running in ui thread


package com.example.androidrunnable;

import android.os.Bundle;
import android.os.Looper;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 static TextView prompt;
 static int counter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        prompt = new TextView(this);
        setContentView(prompt);

        display_in_ui(String.valueOf("Hello"));
        
        Thread myThread = new Thread(myRunnable);
        myThread.start();
    }

    Runnable myRunnable = new Runnable(){

  @Override
  public void run() {
   counter = 0;
   while(true){
    try {
     Thread.sleep(1000);
     display_in_ui(String.valueOf(counter));
     counter++;
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  } 
    };
    
    private void display_in_ui(final String txt){
     if (Looper.getMainLooper().getThread() == 
       Thread.currentThread()) {
      //currently run on UI thread
      prompt.setText("on ui thread: " + txt);
     } else {
      //not on UI thread
      runOnUiThread(new Runnable(){

    @Override
    public void run() {
     prompt.setText("NOT on ui thread: " + txt);
    }
    
   });
     }
     
    }

}


runOnUiThread, runs the specified action on the UI thread

The method runOnUiThread(Runnable action) 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:

package com.example.androidrunnable;

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

public class MainActivity extends Activity {
 
 static TextView prompt;
 static int counter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        prompt = new TextView(this);
        setContentView(prompt);
        
        prompt.setText("Hello");
        
        Thread myThread = new Thread(myRunnable);
        myThread.start();
    }

    Runnable myRunnable = new Runnable(){

  @Override
  public void run() {
   counter = 0;
   while(true){
    try {
     Thread.sleep(1000);
     runOnUiThread(new Runnable(){

      @Override
      public void run() {
       prompt.setText(String.valueOf(counter));
      }
      
     });
     counter++;
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  } 
    };

}


Access UI thread in Handler

Last example demonstrate how to implement Thread and Runnable. You cannot access UI elements directly in background thread. Handler can be used to access UI elements.

package com.example.androidrunnable;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.widget.TextView;

public class MainActivity extends Activity {
 
 static TextView prompt;
 static int counter;
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        prompt = new TextView(this);
        setContentView(prompt);
        
        prompt.setText("Hello");
        
        Thread myThread = new Thread(myRunnable);
        myThread.start();
    }
    
 static Handler myHandler = new Handler(){

  @Override
  public void handleMessage(Message msg) {
   prompt.setText(String.valueOf(counter));
  }
     
    };

    Runnable myRunnable = new Runnable(){

  @Override
  public void run() {
   counter = 0;
   while(true){
    try {
     Thread.sleep(1000);
     myHandler.sendMessage(myHandler.obtainMessage());
     counter++;
    } catch (InterruptedException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
    }
   }
  } 
    };
    
}


Simple example of using Thread and Runnable

package com.example.androidrunnable;

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

public class MainActivity extends Activity {
 
 static TextView prompt;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_main);
        prompt = new TextView(this);
        setContentView(prompt);
        
        prompt.setText("Hello");
        
        Thread myThread = new Thread(myRunnable);
        myThread.start();
    }

    Runnable myRunnable = new Runnable(){

  @Override
  public void run() {

   while(true){
    //do something in background thread
   }
  } 
    };
    
}


You cannot access UI elements directly in background thread. Handler or runOnUiThread() can be used to access UI elements.

Infolinks In Text Ads