Friday, September 19, 2014

Java/JavaFX example: 1 server vs 30 clients

This video test how one Java/JavaFX server connected with 30 clients, all one on the same PC (running Linux) for testing.


reference:
Java/JavaFX Server link to Android Client
Java/JavaFX Client link to Android Server

Both server and client modified to suit for testing:

JavaFX_Server.java
package javafx_server;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketException;
import java.util.Enumeration;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.CheckBox;
import javafx.scene.control.Label;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFX_Server extends Application {

    TextField textTitle;
    Label labelSys, labelPort, labelIp;
    TextArea textAreaMsg;
    CheckBox optWelcome;

    ServerSocket serverSocket;

    @Override
    public void start(Stage primaryStage) {

        textTitle = new TextField();
        labelSys = new Label();
        labelPort = new Label();
        labelIp = new Label();
        textAreaMsg = new TextArea();
        
        //Auto scroll to bottom
        textAreaMsg.textProperty().addListener(new ChangeListener(){

            @Override
            public void changed(ObservableValue observable, Object oldValue, Object newValue) {
                textAreaMsg.setScrollTop(Double.MAX_VALUE); 
            }
        });
        
        optWelcome = new CheckBox("Send Welcome when connect");
        optWelcome.setSelected(true);

        labelSys.setText(
            System.getProperty("os.arch") + "/"
            + System.getProperty("os.name"));
        labelIp.setText(getIpAddress());

        VBox mainLayout = new VBox();
        mainLayout.setPadding(new Insets(5, 5, 5, 5));
        mainLayout.setSpacing(5);
        mainLayout.getChildren().addAll(textTitle,
            labelSys, labelPort, labelIp,
            optWelcome, textAreaMsg);

        StackPane root = new StackPane();
        root.getChildren().add(mainLayout);

        Scene scene = new Scene(root, 300, 400);

        primaryStage.setTitle("Android-er: JavaFX Server");
        primaryStage.setScene(scene);
        primaryStage.show();

        Thread socketServerThread = new Thread(new SocketServerThread());
        socketServerThread.setDaemon(true); //terminate the thread when program end
        socketServerThread.start();
    }

    public static void main(String[] args) {
        launch(args);
    }

    private class SocketServerThread extends Thread {

        static final int SocketServerPORT = 8080;
        int count = 0;

        @Override
        public void run() {
            try {
                Socket socket = null;
                
                serverSocket = new ServerSocket(SocketServerPORT);
                Platform.runLater(new Runnable() {

                    @Override
                    public void run() {
                        labelPort.setText("I'm waiting here: "
                            + serverSocket.getLocalPort());
                    }
                });

                while (true) {
                    socket = serverSocket.accept();
                    count++;
                    
                    //Start another thread 
                    //to prevent blocked by empty dataInputStream
                    Thread acceptedThread = new Thread(
                        new ServerSocketAcceptedThread(socket, count));
                    acceptedThread.setDaemon(true); //terminate the thread when program end
                    acceptedThread.start();

                }
            } catch (IOException ex) {
                Logger.getLogger(JavaFX_Server.class.getName()).log(Level.SEVERE, null, ex);
            }
            
        }

    }

    private class ServerSocketAcceptedThread extends Thread {

        Socket socket = null;
        DataInputStream dataInputStream = null;
        DataOutputStream dataOutputStream = null;
        int count;

        ServerSocketAcceptedThread(Socket s, int c) {
            socket = s;
            count = c;
        }

        @Override
        public void run() {
            try {
                dataInputStream = new DataInputStream(
                    socket.getInputStream());
                dataOutputStream = new DataOutputStream(
                    socket.getOutputStream());

                //If dataInputStream empty, 
                //this thread will be blocked by readUTF(),
                //but not the others
                String messageFromClient = dataInputStream.readUTF();

                String newMessage = "#" + count + " from " + socket.getInetAddress()
                    + ":" + socket.getPort() + "\n"
                    + "Msg from client: " + messageFromClient + "\n";
                
                Platform.runLater(new Runnable() {
                    
                    @Override
                    public void run() {
                        textAreaMsg.appendText(newMessage);
                    }
                });
                
                if (optWelcome.isSelected()) {
                    
                    String msgReply = count + ": " + textTitle.getText();
                    dataOutputStream.writeUTF(msgReply);
                }
                
            } catch (IOException ex) {
                Logger.getLogger(JavaFX_Server.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException ex) {
                        Logger.getLogger(JavaFX_Server.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                if (dataInputStream != null) {
                    try {
                        dataInputStream.close();
                    } catch (IOException ex) {
                        Logger.getLogger(JavaFX_Server.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }

                if (dataOutputStream != null) {
                    try {
                        dataOutputStream.close();
                    } catch (IOException ex) {
                        Logger.getLogger(JavaFX_Server.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
            }
        }

    }

    private String getIpAddress() {
        String ip = "";
        try {
            Enumeration<NetworkInterface> enumNetworkInterfaces = NetworkInterface
                .getNetworkInterfaces();
            while (enumNetworkInterfaces.hasMoreElements()) {
                NetworkInterface networkInterface = enumNetworkInterfaces
                    .nextElement();
                Enumeration<InetAddress> enumInetAddress = networkInterface
                    .getInetAddresses();
                while (enumInetAddress.hasMoreElements()) {
                    InetAddress inetAddress = enumInetAddress.nextElement();

                    if (inetAddress.isSiteLocalAddress()) {
                        ip += "SiteLocalAddress: "
                            + inetAddress.getHostAddress() + "\n";
                    }
                }
            }
        } catch (SocketException ex) {
            Logger.getLogger(JavaFX_Server.class.getName()).log(Level.SEVERE, null, ex);
        } 

        return ip;
    }

}

Download.

JavaFX_Client.java
package javafx_client;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.lang.management.ManagementFactory;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class JavaFX_Client extends Application {

    Label labelSys;
    TextField welcomeMsg;
    Label labelAddress;
    TextField textAddress;
    Label labelPort;
    TextField textPort;
    Button buttonConnect;
    Button buttonClear;
    Label textResponse;

    @Override
    public void start(Stage primaryStage) {

        labelSys = new Label();
        welcomeMsg = new TextField();
        labelAddress = new Label("IP Address");
        textAddress = new TextField();
        labelPort = new Label("Port");
        textPort = new TextField();
        buttonConnect = new Button("Connect");
        buttonClear = new Button("Clear");
        textResponse = new Label();

        labelSys.setText(
                System.getProperty("os.arch") + "/"
                + System.getProperty("os.name"));

        HBox buttonbox = new HBox();
        buttonbox.setSpacing(5);
        HBox.setHgrow(buttonConnect, Priority.ALWAYS);
        HBox.setHgrow(buttonClear, Priority.ALWAYS);
        buttonConnect.setMaxWidth(Double.MAX_VALUE);
        buttonClear.setMaxWidth(Double.MAX_VALUE);
        buttonbox.getChildren().addAll(buttonConnect, buttonClear);

        buttonConnect.setOnAction(buttonConnectEventHandler);
        
        buttonClear.setOnAction(new EventHandler<ActionEvent>() {

            @Override
            public void handle(ActionEvent event) {
                textResponse.setText("");
            }
        });

        VBox mainLayout = new VBox();
        mainLayout.setPadding(new Insets(5, 5, 5, 5));
        mainLayout.setSpacing(5);
        mainLayout.getChildren().addAll(labelSys, welcomeMsg,
                labelAddress, textAddress, labelPort, textPort,
                buttonbox, textResponse);

        StackPane root = new StackPane();
        root.getChildren().add(mainLayout);

        Scene scene = new Scene(root, 300, 400);

        String myPID = ManagementFactory.getRuntimeMXBean().getName();
        primaryStage.setTitle(myPID);
        primaryStage.setScene(scene);
        primaryStage.show();
        
        //Prepare and send preset setting
        String presetMsg = "Hello from " + myPID;
        welcomeMsg.setText(presetMsg);
        textAddress.setText("192.168.1.103");
        textPort.setText("8080");
        RunnableClient presetClient
            = new RunnableClient(textAddress.getText(), 
                    Integer.parseInt(textPort.getText()),
                    presetMsg);
            
        new Thread(presetClient).start();
        //---
    }

    public static void main(String[] args) {
        launch(args);
    }

    EventHandler<ActionEvent> buttonConnectEventHandler
        = new EventHandler<ActionEvent>() {

        @Override
        public void handle(ActionEvent event) {
            String tMsg = welcomeMsg.getText();
            if (tMsg.equals("")) {
                tMsg = null;
            }

            RunnableClient runnableClient
                = new RunnableClient(textAddress.getText(), 
                    Integer.parseInt(textPort.getText()),
                    tMsg);
            
            new Thread(runnableClient).start();
        }
    };

    class RunnableClient implements Runnable{
        
        String dstAddress;
        int dstPort;
        String response = "";
        String msgToServer;
        
        public RunnableClient(String addr, int port, String msgTo) {
            dstAddress = addr;
            dstPort = port;
            msgToServer = msgTo;
        }

        @Override
        public void run() {
            Socket socket = null;
            DataOutputStream dataOutputStream = null;
            DataInputStream dataInputStream = null;

            try {
                socket = new Socket(dstAddress, dstPort);
                dataOutputStream = new DataOutputStream(
                    socket.getOutputStream());
                dataInputStream = new DataInputStream(socket.getInputStream());

                if(msgToServer != null){
                    dataOutputStream.writeUTF(msgToServer);
                }
    
                response = dataInputStream.readUTF();
   

            } catch (IOException ex) { 
                Logger.getLogger(JavaFX_Client.class.getName()).log(Level.SEVERE, null, ex);
            } finally {
                
                Platform.runLater(new Runnable(){

                    @Override
                    public void run() {
                        textResponse.setText(response);
                    }
                    
                });
                
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException ex) {
                        Logger.getLogger(JavaFX_Client.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                
                if (dataOutputStream != null) {
                    try {
                        dataOutputStream.close();
                    } catch (IOException ex) {
                        Logger.getLogger(JavaFX_Client.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                
                if (dataInputStream != null) {
                    try {
                        dataInputStream.close();
                    } catch (IOException ex) {
                        Logger.getLogger(JavaFX_Client.class.getName()).log(Level.SEVERE, null, ex);
                    }
                }
                
            }
        }
        
    }

}

Download.

For testing, you have to create a shell script and make it executable. to start 30 JavaFX_Client application.



Thursday, September 18, 2014

Improve JPG loading with ExifInterface.getThumbnail()

Refer to last example of "getView() to load images in AsyncTask", the loading of large images (such as photos from camera/DSLR) is too slow to accept. Most JPG embedd with thumbnail, we can use ExifInterface to check and load if it has thumbnail embedded.

Check this video to know how it improve the performance:


Modify MainActivity.java from last example of "getView() to load images in AsyncTask", accepet jpg only, and check and load thumbnail.

package com.example.androidgridview;

import java.io.File;
import java.io.FilenameFilter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;

import android.media.ExifInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends Activity {
 
 AsyncTaskLoadFiles myAsyncTaskLoadFiles;

 public class AsyncTaskLoadFiles extends AsyncTask<Void, String, Void> {
  
  File targetDirector;
  ImageAdapter myTaskAdapter;

  public AsyncTaskLoadFiles(ImageAdapter adapter) {
   myTaskAdapter = adapter;
  }

  @Override
  protected void onPreExecute() {
   String ExternalStorageDirectoryPath = Environment
     .getExternalStorageDirectory().getAbsolutePath();

   String targetPath = ExternalStorageDirectoryPath + "/test/";
   targetDirector = new File(targetPath);
   myTaskAdapter.clear();
   
   super.onPreExecute();
  }

  @Override
  protected Void doInBackground(Void... params) {
   
   //open jpg only
   File[] files = targetDirector.listFiles(new FilenameFilter() {
       public boolean accept(File dir, String name)
       {
           return (name.endsWith(".jpg")||name.endsWith(".JPG")); 
       }
   });
   //File[] files = targetDirector.listFiles();
   
   Arrays.sort(files);
   for (File file : files) {
    publishProgress(file.getAbsolutePath());
    if (isCancelled()) break;
   }
   return null;
  }

  @Override
  protected void onProgressUpdate(String... values) {
   myTaskAdapter.add(values[0]);
   super.onProgressUpdate(values);
  }

  @Override
  protected void onPostExecute(Void result) {
   myTaskAdapter.notifyDataSetChanged();
   super.onPostExecute(result);
  }

 }

 public class ImageAdapter extends BaseAdapter {

  private Context mContext;
  ArrayList<String> itemList = new ArrayList<String>();

  public ImageAdapter(Context c) {
   mContext = c;
  }

  void add(String path) {
   itemList.add(path);
  }
  
  void clear() {
   itemList.clear();
  }
  
  void remove(int index){
   itemList.remove(index);
  }

  @Override
  public int getCount() {
   return itemList.size();
  }

  @Override
  public Object getItem(int position) {
   // TODO Auto-generated method stub
   return itemList.get(position);
  }

  @Override
  public long getItemId(int position) {
   // TODO Auto-generated method stub
   return 0;
  }

  //getView load bitmap in AsyncTask
  @Override
  public View getView(final int position, View convertView, ViewGroup parent) {
   ViewHolder holder;

   ImageView imageView;
   if (convertView == null) { // if it's not recycled, initialize some
          // attributes
    imageView = new ImageView(mContext);
    imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
    imageView.setPadding(8, 8, 8, 8);
    
    convertView = imageView;
    
    holder = new ViewHolder();
    holder.image = imageView;
    holder.position = position;
    convertView.setTag(holder);
   } else {
    //imageView = (ImageView) convertView;
    holder = (ViewHolder) convertView.getTag();
    ((ImageView)convertView).setImageBitmap(null);
   }
   
   //Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220, 220);
   // Using an AsyncTask to load the slow images in a background thread
   new AsyncTask<ViewHolder, Void, Bitmap>() {
       private ViewHolder v;

       @Override
       protected Bitmap doInBackground(ViewHolder... params) {
        
        Bitmap bm = null;
        
        boolean haveThumbNail = false;
        
        try {
      ExifInterface exifInterface = 
       new ExifInterface(itemList.get(position));
      if(exifInterface.hasThumbnail()){
       byte[] thumbnail = exifInterface.getThumbnail();
       bm = BitmapFactory.decodeByteArray(thumbnail, 0, thumbnail.length);
      }
      haveThumbNail = true;
     } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
        
        if(!haveThumbNail){
         bm = decodeSampledBitmapFromUri(
           itemList.get(position), 220, 220);
        }

           v = params[0];
           return bm;
       }

       @Override
       protected void onPostExecute(Bitmap result) {
           super.onPostExecute(result);
           //Not work for me!
           /*
           if (v.position == position) {
               // If this item hasn't been recycled already, 
            // show the image
               v.image.setImageBitmap(result);
           }
           */

           v.image.setImageBitmap(result);

       }
   }.execute(holder);

   //imageView.setImageBitmap(bm);
   //return imageView;
   return convertView;
  }

  public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth,
    int reqHeight) {

   Bitmap bm = null;
   // First decode with inJustDecodeBounds=true to check dimensions
   final BitmapFactory.Options options = new BitmapFactory.Options();
   options.inJustDecodeBounds = true;
   BitmapFactory.decodeFile(path, options);

   // Calculate inSampleSize
   options.inSampleSize = calculateInSampleSize(options, reqWidth,
     reqHeight);

   // Decode bitmap with inSampleSize set
   options.inJustDecodeBounds = false;
   bm = BitmapFactory.decodeFile(path, options);

   return bm;
  }

  public int calculateInSampleSize(

  BitmapFactory.Options options, int reqWidth, int reqHeight) {
   // Raw height and width of image
   final int height = options.outHeight;
   final int width = options.outWidth;
   int inSampleSize = 1;

   if (height > reqHeight || width > reqWidth) {
    if (width > height) {
     inSampleSize = Math.round((float) height
       / (float) reqHeight);
    } else {
     inSampleSize = Math.round((float) width / (float) reqWidth);
    }
   }

   return inSampleSize;
  }
  
  class ViewHolder {
            ImageView image;
            int position;
        }

 }

 ImageAdapter myImageAdapter;

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

  final GridView gridview = (GridView) findViewById(R.id.gridview);
  myImageAdapter = new ImageAdapter(this);
  gridview.setAdapter(myImageAdapter);

  /*
   * Move to asyncTaskLoadFiles String ExternalStorageDirectoryPath =
   * Environment .getExternalStorageDirectory() .getAbsolutePath();
   * 
   * String targetPath = ExternalStorageDirectoryPath + "/test/";
   * 
   * Toast.makeText(getApplicationContext(), targetPath,
   * Toast.LENGTH_LONG).show(); File targetDirector = new
   * File(targetPath);
   * 
   * File[] files = targetDirector.listFiles(); for (File file : files){
   * myImageAdapter.add(file.getAbsolutePath()); }
   */
  myAsyncTaskLoadFiles = new AsyncTaskLoadFiles(myImageAdapter);
  myAsyncTaskLoadFiles.execute();

  gridview.setOnItemClickListener(myOnItemClickListener);
  
  Button buttonReload = (Button)findViewById(R.id.reload);
  buttonReload.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View arg0) {
    
    //Cancel the previous running task, if exist.
    myAsyncTaskLoadFiles.cancel(true);
    
    //new another ImageAdapter, to prevent the adapter have
    //mixed files
    myImageAdapter = new ImageAdapter(MainActivity.this);
    gridview.setAdapter(myImageAdapter);
    myAsyncTaskLoadFiles = new AsyncTaskLoadFiles(myImageAdapter);
    myAsyncTaskLoadFiles.execute();
   }});

 }

 OnItemClickListener myOnItemClickListener = new OnItemClickListener() {

  @Override
  public void onItemClick(AdapterView<?> parent, View view, int position,
    long id) {
   String prompt = "remove " + (String) parent.getItemAtPosition(position);
   Toast.makeText(getApplicationContext(), prompt, Toast.LENGTH_SHORT)
     .show();
   
   myImageAdapter.remove(position);
   myImageAdapter.notifyDataSetChanged();

  }
 };

}

download filesDownload the files.

Apply animation on buttons to start activity

Example to apply Animation on Buttons, and implement AnimationListener to startActivity() when onAnimationEnd() called. Notice that when a animation is running, the buttons still can accept click to start other animation, and create more AnimationListener to start more than one second activity when ended. (It's further work on former exercise "Apply animation on Button")


Create animation xml in /res/anim folder.

/res/anim/anim_alpha.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <alpha 
        android:fromAlpha="1.0" 
        android:toAlpha="0.1" 
        android:duration="500" 
        android:repeatCount="1"
        android:repeatMode="reverse" />
</set>

/res/anim/anim_rotate.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <rotate
        android:fromDegrees="0"
        android:toDegrees="360"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="500"
        android:startOffset="0"
        android:repeatCount="1"
        android:repeatMode="reverse" />
</set>

/res/anim/anim_scale.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <scale
        android:fromXScale="1.0"
        android:toXScale="3.0"
        android:fromYScale="1.0"
        android:toYScale="3.0"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="500" 
        android:repeatCount="1"
        android:repeatMode="reverse" />
</set>

/res/anim/anim_translate.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
    android:interpolator="@android:anim/linear_interpolator">
    <translate
        android:fromXDelta="0"
        android:toXDelta="100%p"
        android:duration="500"
        android:repeatCount="1"
        android:repeatMode="reverse"/>
</set>

/res/layout/main.xml, layout of main activity(AndroidAnimButtonsActivity.java).
<?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="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <Button
        android:id="@+id/translate"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Translate" />
    <Button
        android:id="@+id/alpha"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Alpha" />
    <Button
        android:id="@+id/scale"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Scale" />
    <Button
        android:id="@+id/rotate"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Rotate" />

</LinearLayout>

AndroidAnimButtonsActivity.java
package com.exercise.AndroidAnimButtons;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Animation.AnimationListener;
import android.view.animation.AnimationUtils;
import android.widget.Button;

public class AndroidAnimButtonsActivity extends Activity {
 
 static String KEY_ANIM = "TARGET_ANIM";
 static String Target_Translate = "Translate";
 static String Target_Alpha = "Alpha";
 static String Target_Scale = "Scale";
 static String Target_Rotate = "Rotate";
 String target_op = Target_Translate; //dummy default 
 
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        final Animation animTranslate = AnimationUtils.loadAnimation(this, R.anim.anim_translate);
        final Animation animAlpha = AnimationUtils.loadAnimation(this, R.anim.anim_alpha);
        final Animation animScale = AnimationUtils.loadAnimation(this, R.anim.anim_scale);
        final Animation animRotate = AnimationUtils.loadAnimation(this, R.anim.anim_rotate);
        
        Button btnTranslate = (Button)findViewById(R.id.translate);
        Button btnAlpha = (Button)findViewById(R.id.alpha);
        Button btnScale = (Button)findViewById(R.id.scale);
        Button btnRotate = (Button)findViewById(R.id.rotate);
        
        btnTranslate.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    target_op = Target_Translate;
    arg0.startAnimation(animTranslate);
   }});
        
        btnAlpha.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    target_op = Target_Alpha;
    arg0.startAnimation(animAlpha);
   }});
        
        btnScale.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    target_op = Target_Scale;
    arg0.startAnimation(animScale);
   }});
        
        btnRotate.setOnClickListener(new Button.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    target_op = Target_Rotate;
    arg0.startAnimation(animRotate);
   }});
        
        animTranslate.setAnimationListener(animationListener);
        animAlpha.setAnimationListener(animationListener);
        animScale.setAnimationListener(animationListener);
        animRotate.setAnimationListener(animationListener);
    }
    
    AnimationListener animationListener = new AnimationListener(){

  @Override
  public void onAnimationStart(Animation animation) {
   // TODO Auto-generated method stub
   
  }

  @Override
  public void onAnimationEnd(Animation animation) {
   Intent intent = new Intent(
     AndroidAnimButtonsActivity.this, 
     SecondActivity.class);
        intent.putExtra(KEY_ANIM, target_op);
        startActivity(intent);
  }

  @Override
  public void onAnimationRepeat(Animation animation) {
   // TODO Auto-generated method stub
   
  }};
}

/res/layout/second.xml, layout of the second activity(SecondActivity.java).
<?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="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:autoLink="web"
        android:text="http://android-er.blogspot.com/"
        android:textStyle="bold" />

    <Button
        android:id="@+id/anbutton"
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:text="Translate" />

</LinearLayout>

SecondActivity.java
package com.exercise.AndroidAnimButtons;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewTreeObserver.OnGlobalLayoutListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;

public class SecondActivity extends Activity {

 Animation anim;
 Button anButton;
 
 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.second);
  Intent intent = getIntent();
  String op = intent.getStringExtra(AndroidAnimButtonsActivity.KEY_ANIM);
  if (op.equals(AndroidAnimButtonsActivity.Target_Translate)){
   anim = AnimationUtils.loadAnimation(SecondActivity.this, R.anim.anim_translate);
  }else if (op.equals(AndroidAnimButtonsActivity.Target_Alpha)){
   anim = AnimationUtils.loadAnimation(SecondActivity.this, R.anim.anim_alpha);
  }else if (op.equals(AndroidAnimButtonsActivity.Target_Scale)){
   anim = AnimationUtils.loadAnimation(SecondActivity.this, R.anim.anim_scale);
  }else if (op.equals(AndroidAnimButtonsActivity.Target_Rotate)){
   anim = AnimationUtils.loadAnimation(SecondActivity.this, R.anim.anim_rotate);
  }
  
  anButton = (Button)findViewById(R.id.anbutton);
  anButton.setText(op);
  
  anButton.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener(){

   @Override
   public void onGlobalLayout() {

    anButton.startAnimation(anim);
    
    //deprecated in API level 16
    anButton.getViewTreeObserver().removeGlobalOnLayoutListener(this);
       //for API Level >= 16
       //anImage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
   }});
  
  anButton.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    anButton.startAnimation(anim);
   }});
 }

}

Modify AndroidManifest.xml to add SecondActivity.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.exercise.AndroidAnimButtons"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

</manifest>


download filesDownload the files.


How to enable emoji input on Android

Open Setting -> Language & input, scroll down to Keyboard & Input Method. If you see the option of iWnn IME (Emoji), that means your device built-in support Emoji input. Check to enable it.


When you enter text, press and hold SpaceBar, to switch to Emoji (iWnn IME).