Tuesday, March 31, 2015

Run Linux command on Android

Android system have to Terminal application in default. This example provide user to run Linux command using ProcessBuilder, and display the result. But most Linux command not support in Android.

(If you want try the APK only, scroll down to the bottom.)


package com.example.androidrunlinuxcmd;

import java.io.IOException;
import java.io.InputStream;

import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;


public class MainActivity extends ActionBarActivity {
 
 EditText cmdBox;
 Button btnRun;
 TextView textResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        cmdBox = (EditText)findViewById(R.id.cmdbox);
     btnRun = (Button)findViewById(R.id.run);
     textResult = (TextView)findViewById(R.id.result);
     textResult.setTypeface(Typeface.MONOSPACE);
        
  btnRun.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    //Split String from EditText to String Array
    String[] cmd = cmdBox.getText().toString().split("\\s+"); 
    try {
     String cmdResult = runLinuxCmd(cmd);
     textResult.setTextColor(Color.WHITE);
     textResult.setText(cmdResult);
    } catch (IOException e) {
     e.printStackTrace();
     textResult.setTextColor(Color.RED);
     textResult.setText("Something Wrong!\n"
      + e.getMessage());
    }
   }});
    }

    //Run a Linux command and return result
 private String runLinuxCmd(String[] command) throws IOException {

    StringBuilder cmdReturn = new StringBuilder();

    ProcessBuilder processBuilder = new ProcessBuilder(command);
     Process process = processBuilder.start();

     InputStream inputStream = process.getInputStream();
     int c;

     while ((c = inputStream.read()) != -1) {
      cmdReturn.append((char) c);
     }

     return cmdReturn.toString();
   }
}


<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.example.androidrunlinuxcmd.MainActivity" >

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

    <EditText
        android:id="@+id/cmdbox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:singleLine="true" />

    <Button
        android:id="@+id/run"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Run Linux Command" />

    <ScrollView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#A0A0A0" >

        <TextView
            android:id="@+id/result"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_margin="10dp" />
    </ScrollView>

</LinearLayout>


download filesDownload the files.

Download and Try the APK.

Get memory info

Example to get memory information using MemoryInfo and Runtime.


Where:

  • MemoryInfo.availMem: the available memory on the system.
  • MemoryInfo.totalMem: the total memory accessible by the kernel.
  • Runtime.maxMemory(): the maximum number of bytes the heap can expand to.
  • Runtime.totalMemory(): the current number of bytes taken by the heap.
  • Runtime.freeMemory(): the current number of those bytes actually used by live objects.


package com.example.androidmeminfo;

import android.support.v7.app.ActionBarActivity;
import android.widget.TextView;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.os.Bundle;

public class MainActivity extends ActionBarActivity {

 TextView textMemInfo;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  textMemInfo = (TextView) findViewById(R.id.txmeminfo);
  textMemInfo.setText(getMemInfo());
 }

 private String getMemInfo() {
  MemoryInfo memoryInfo = new MemoryInfo();
  ActivityManager activityManager = 
   (ActivityManager) getSystemService(ACTIVITY_SERVICE);
  activityManager.getMemoryInfo(memoryInfo);
  
  Runtime runtime = Runtime.getRuntime();


  String strMemInfo = 
   "MemoryInfo.availMem = " + memoryInfo.availMem + "\n"
   + "MemoryInfo.totalMem = " + memoryInfo.totalMem + "\n" // API 16
   + "\n"
   + "Runtime.maxMemory() = " + runtime.maxMemory() + "\n"
   + "Runtime.totalMemory() = " + runtime.totalMemory() + "\n"
   + "Runtime.freeMemory() = " + runtime.freeMemory() + "\n";
  
  return strMemInfo;
 }

}


<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.example.androidmeminfo.MainActivity" >

    <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" />
    <TextView
        android:id="@+id/txmeminfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Monday, March 30, 2015

Read CPU frequency using linux command "cat /sys/devices/system/cpu/cpuX/cpufreq/scaling_cur_freq"

This example read files "/sys/devices/system/cpu/cpu[0..]/cpufreq/scaling_cur_freq" with Linux's cat command, to determine running cpu frequency.


In Linux, there will be some file like this, to show the CPUs frequency.
/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq
/sys/devices/system/cpu/cpu1/cpufreq/scaling_cur_freq
...

Run adb command:
$ adb shell ls /sys/devices/system/cpu/

It will show some directory named cpu0, cpu1..., it is the number of cpu in your system.

Run adb command, to show the current frequency of cpu0:
$ adb shell cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq



package com.example.androidcpu;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.io.InputStream;
import java.util.regex.Pattern;

import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {
 
 TextView textAvProc, textNumOfCpu, textMsg;
 Button btnReadCpuFreq;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textAvProc = (TextView)findViewById(R.id.avproc);
        textNumOfCpu = (TextView)findViewById(R.id.numofcpu);
        textMsg = (TextView)findViewById(R.id.msg);
        btnReadCpuFreq = (Button)findViewById(R.id.readfreq);
        
        Runtime runtime = Runtime.getRuntime();
        int availableProcessors = runtime.availableProcessors();
        textAvProc.setText("availableProcessors = " + availableProcessors);

        btnReadCpuFreq.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    readCpuFreqNow();
   }});
        
        readCpuFreqNow();
    }
    
    private void readCpuFreqNow(){
     File[] cpuFiles = getCPUs();
        textNumOfCpu.setText("number of cpu: " + cpuFiles.length);
        
        String strFileList = "";
        for(int i=0; i<cpuFiles.length; i++){
         
         String path_scaling_cur_freq = 
          cpuFiles[i].getAbsolutePath()+"/cpufreq/scaling_cur_freq";
         
         String scaling_cur_freq = cmdCat(path_scaling_cur_freq);
         
         strFileList +=
          i + ": " 
          + path_scaling_cur_freq + "\n"
          + scaling_cur_freq
          + "\n";
        }
        
        textMsg.setText(strFileList);
    }

    //run Linux command 
    //$ cat f
    private String cmdCat(String f){

     String[] command = {"cat", f};
     StringBuilder cmdReturn = new StringBuilder();
     
     try {
      ProcessBuilder processBuilder = new ProcessBuilder(command);
      Process process = processBuilder.start();
      
      InputStream inputStream = process.getInputStream();
      int c;
      
      while ((c = inputStream.read()) != -1) {
       cmdReturn.append((char) c); 
      }
         
      return cmdReturn.toString();
      
     } catch (IOException e) {
      e.printStackTrace();
      return "Something Wrong";
     }

    }

    /*
     * Get file list of the pattern
     * /sys/devices/system/cpu/cpu[0..9]
     */
    private File[] getCPUs(){
     
     class CpuFilter implements FileFilter {
            @Override
            public boolean accept(File pathname) {
                if(Pattern.matches("cpu[0-9]+", pathname.getName())) {
                    return true;
                }
                return false;
            }      
        }
     
     File dir = new File("/sys/devices/system/cpu/");
     File[] files = dir.listFiles(new CpuFilter());
     return files;
    }
}

<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.example.androidcpu.MainActivity" >

    <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" />
    
    <TextView
        android:id="@+id/avproc"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <Button
        android:id="@+id/readfreq"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Read CPUs Frequency now"/>
    <TextView
        android:id="@+id/numofcpu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
    <TextView
        android:id="@+id/msg"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

</LinearLayout>

Related:
- Java SE version on Raspberry Pi and Linux

Sunday, March 29, 2015

adb command to reboot Android device

To deboot connect devies using adb, enter the commnad:
$ adb shell am broadcast -a android.intent.action.BOOT_COMPLETED


Thursday, March 26, 2015

ViewPager auto scroll to the first, last or any page

By calling setCurrentItem() method of ViewPager, you can force it to scroll to any specified page. This example show how to scroll to the first and the last page.


package com.example.androidviewpagerapp;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBarActivity;
import android.text.method.ScrollingMovementMethod;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

 ViewPager viewPager;
 MyPagerAdapter myPagerAdapter;
 TextView textMsg;
 Button btnToFirst, btnToLast;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  textMsg = (TextView)findViewById(R.id.msg);
  textMsg.setMovementMethod(new ScrollingMovementMethod());
  
  viewPager = (ViewPager) findViewById(R.id.myviewpager);
  myPagerAdapter = new MyPagerAdapter();
  viewPager.setAdapter(myPagerAdapter);
  
  viewPager.setOnPageChangeListener(myOnPageChangeListener);
  
  btnToFirst = (Button)findViewById(R.id.tofirst);
  btnToLast = (Button)findViewById(R.id.tolast);
  btnToFirst.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    viewPager.setCurrentItem(0);
   }});
  btnToLast.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    int indexLast = viewPager.getAdapter().getCount() - 1;;
    viewPager.setCurrentItem(indexLast);
   }});
 }
 
 OnPageChangeListener myOnPageChangeListener = 
   new OnPageChangeListener(){

  @Override
  public void onPageScrollStateChanged(int state) {
   //Called when the scroll state changes.
  }

  @Override
  public void onPageScrolled(int position, 
    float positionOffset, int positionOffsetPixels) {
   //This method will be invoked when the current page is scrolled, 
   //either as part of a programmatically initiated smooth scroll 
   //or a user initiated touch scroll.
  }

  @Override
  public void onPageSelected(int position) {
   //This method will be invoked when a new page becomes selected.
   textMsg.append("onPageSelected:" + position + "\n");
  }};

 private class MyPagerAdapter extends PagerAdapter {

  int NumberOfPages = 5;

  int[] res = { android.R.drawable.ic_dialog_alert,
    android.R.drawable.ic_menu_camera,
    android.R.drawable.ic_menu_compass,
    android.R.drawable.ic_menu_directions,
    android.R.drawable.ic_menu_gallery };
  int[] backgroundcolor = { 0xFF101010, 0xFF202020, 0xFF303030,
    0xFF404040, 0xFF505050 };

  @Override
  public int getCount() {
   return NumberOfPages;
  }

  @Override
  public boolean isViewFromObject(View view, Object object) {
   return view == object;
  }

  @Override
  public Object instantiateItem(ViewGroup container, int position) {
   
   textMsg.append("instantiateItem:" + position + "\n");

   TextView textView = new TextView(MainActivity.this);
   textView.setTextColor(Color.WHITE);
   textView.setTextSize(30);
   textView.setTypeface(Typeface.DEFAULT_BOLD);
   textView.setText(String.valueOf(position));

   ImageView imageView = new ImageView(MainActivity.this);
   imageView.setImageResource(res[position]);
   LayoutParams imageParams = new LayoutParams(
     LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
   imageView.setLayoutParams(imageParams);

   LinearLayout layout = new LinearLayout(MainActivity.this);
   layout.setOrientation(LinearLayout.VERTICAL);
   LayoutParams layoutParams = new LayoutParams(
     LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
   layout.setBackgroundColor(backgroundcolor[position]);
   layout.setLayoutParams(layoutParams);
   layout.addView(textView);
   layout.addView(imageView);

   final int page = position;
   layout.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
     Toast.makeText(MainActivity.this,
       "Page " + page + " clicked", Toast.LENGTH_LONG)
       .show();
    }
   });

   container.addView(layout);
   return layout;
  }

  @Override
  public void destroyItem(ViewGroup container, int position, Object object) {
   container.removeView((LinearLayout) object);
   
   textMsg.append("destroyItem:" + position + "\n");
  }

 }
}

<LinearLayout 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:orientation="vertical"
    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="com.example.androidviewpagerapp.MainActivity" >

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="bottom" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <Button
            android:id="@+id/tofirst"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="to First" />
        <Button
            android:id="@+id/tolast"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="to Last" />
    </LinearLayout>
    
    <android.support.v4.view.ViewPager
        android:id="@+id/myviewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>



download filesDownload the files.

Wednesday, March 25, 2015

Implement OnPageChangeListener for ViewPager to monitor the current visible page

Refer to the former example of "Example of ViewPager with custom PagerAdapter": at start-up, instantiateItem() of MyPagerAdapter will be called twice, with position 0 and 1. When you you scroll page forward, extra instantiateItem() with position of the next invisible page will be called. And when you you scroll page backward, extra instantiateItem() with position of the former invisible page will be called.

So how can you know when page is scrolled, and which page is currently visible? One approach is to implement OnPageChangeListener for the ViewPager. The onPageSelected(int position) method will be called when a new page becomes selected. But not the first page at start-up.

Example:


package com.example.androidviewpagerapp;

import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.support.v7.app.ActionBarActivity;
import android.text.method.ScrollingMovementMethod;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

 ViewPager viewPager;
 MyPagerAdapter myPagerAdapter;
 TextView textMsg;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  textMsg = (TextView)findViewById(R.id.msg);
  textMsg.setMovementMethod(new ScrollingMovementMethod());
  
  viewPager = (ViewPager) findViewById(R.id.myviewpager);
  myPagerAdapter = new MyPagerAdapter();
  viewPager.setAdapter(myPagerAdapter);
  
  viewPager.setOnPageChangeListener(myOnPageChangeListener);
 }
 
 OnPageChangeListener myOnPageChangeListener = 
   new OnPageChangeListener(){

  @Override
  public void onPageScrollStateChanged(int state) {
   //Called when the scroll state changes.
  }

  @Override
  public void onPageScrolled(int position, 
    float positionOffset, int positionOffsetPixels) {
   //This method will be invoked when the current page is scrolled, 
   //either as part of a programmatically initiated smooth scroll 
   //or a user initiated touch scroll.
  }

  @Override
  public void onPageSelected(int position) {
   //This method will be invoked when a new page becomes selected.
   textMsg.append("onPageSelected:" + position + "\n");
  }};

 private class MyPagerAdapter extends PagerAdapter {

  int NumberOfPages = 5;

  int[] res = { android.R.drawable.ic_dialog_alert,
    android.R.drawable.ic_menu_camera,
    android.R.drawable.ic_menu_compass,
    android.R.drawable.ic_menu_directions,
    android.R.drawable.ic_menu_gallery };
  int[] backgroundcolor = { 0xFF101010, 0xFF202020, 0xFF303030,
    0xFF404040, 0xFF505050 };

  @Override
  public int getCount() {
   return NumberOfPages;
  }

  @Override
  public boolean isViewFromObject(View view, Object object) {
   return view == object;
  }

  @Override
  public Object instantiateItem(ViewGroup container, int position) {
   
   textMsg.append("instantiateItem:" + position + "\n");

   TextView textView = new TextView(MainActivity.this);
   textView.setTextColor(Color.WHITE);
   textView.setTextSize(30);
   textView.setTypeface(Typeface.DEFAULT_BOLD);
   textView.setText(String.valueOf(position));

   ImageView imageView = new ImageView(MainActivity.this);
   imageView.setImageResource(res[position]);
   LayoutParams imageParams = new LayoutParams(
     LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
   imageView.setLayoutParams(imageParams);

   LinearLayout layout = new LinearLayout(MainActivity.this);
   layout.setOrientation(LinearLayout.VERTICAL);
   LayoutParams layoutParams = new LayoutParams(
     LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
   layout.setBackgroundColor(backgroundcolor[position]);
   layout.setLayoutParams(layoutParams);
   layout.addView(textView);
   layout.addView(imageView);

   final int page = position;
   layout.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
     Toast.makeText(MainActivity.this,
       "Page " + page + " clicked", Toast.LENGTH_LONG)
       .show();
    }
   });

   container.addView(layout);
   return layout;
  }

  @Override
  public void destroyItem(ViewGroup container, int position, Object object) {
   container.removeView((LinearLayout) object);
   
   textMsg.append("destroyItem:" + position + "\n");
  }

 }
}

<LinearLayout 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:orientation="vertical"
    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="com.example.androidviewpagerapp.MainActivity" >

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

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="100dp" >

        <TextView
            android:id="@+id/msg"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="bottom" />
    </LinearLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/myviewpager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>



download filesDownload the files.

Next:
- ViewPager auto scroll to the first, last or any page

Setting Up Google Play Services, for Eclipse-Android SDK

This video show how to set up Google Play Services on Eclipse with Android SDK, reference Google document Setting Up Google Play Services.


Include how to:
- Install Google Play services SDK using Android SDK Manager.
- Import library project google-play-services_lib.
- Add referencing to google-play-services_lib in your project.
- Modify AndroidManifest.xml, to add <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> under <application>.

Also override onResume() method, to call GooglePlayServicesUtil.isGooglePlayServicesAvailable() method to test our setup.

Then finally, try something wrong, in case:
- With google-play-services_lib project closed, Errors of java.lang.NullPointerException occurred during the build.


- Without <meta-data...> in AndroidManifest.xml, no error in compiling, but fail in run time.


- Without referencing to google-play-services_lib, cannot resolve com.google


Once you've set up your project to reference the library project, you can begin developing features with the Google Play services APIs.

Friday, March 20, 2015

Get WiFi info using WifiManager and WifiInfo

Example to get connected WiFi information using WifiManager and WifiInfo.


package com.example.androidwifisetting;

import android.support.v7.app.ActionBarActivity;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.widget.TextView;

/*
 * Permission needed:
 * android.permission.ACCESS_WIFI_STATE
 * 
 * minSdkVersion="21"
 * for WifiInfo.getFrequency()
 */

public class MainActivity extends ActionBarActivity {
 
 TextView textWifiInfo;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textWifiInfo = (TextView)findViewById(R.id.wifiinfo);
        
        String strWifiInfo = "";

        WifiManager wifiManager = (WifiManager)getSystemService(Context.WIFI_SERVICE);
        WifiInfo connectionInfo = wifiManager.getConnectionInfo();

        int ipAddress = connectionInfo.getIpAddress();
        String ipString = String.format("%d.%d.%d.%d",
          (ipAddress & 0xff),
          (ipAddress >> 8 & 0xff),
          (ipAddress >> 16 & 0xff),
          (ipAddress >> 24 & 0xff));
        
        final int NumOfRSSILevels = 5;
        
        strWifiInfo += 
         "SSID: " + connectionInfo.getSSID() + "\n" +
         "BSSID: " + connectionInfo.getBSSID() + "\n" +
         "IP Address: " + ipString + "\n" +
         "MAC Address: " + connectionInfo.getMacAddress() + "\n" +
         "Frequency: " + connectionInfo.getFrequency() + WifiInfo.FREQUENCY_UNITS + "\n" +
         "LinkSpeed: " + connectionInfo.getLinkSpeed() + WifiInfo.LINK_SPEED_UNITS + "\n" +
         "Rssi: " + connectionInfo.getRssi() + "dBm" + "\n" +
         "Rssi Level: " + 
          WifiManager.calculateSignalLevel(connectionInfo.getRssi(), NumOfRSSILevels) + 
          " of " + NumOfRSSILevels;

        textWifiInfo.setText(strWifiInfo);
    }

}

<LinearLayout 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"
    android:orientation="vertical"
    tools:context="com.example.androidwifisetting.MainActivity" >

    <TextView
        android:id="@+id/title"
        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" />
    
   <TextView
        android:id="@+id/wifiinfo"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:textSize="20dp"
        android:textStyle="bold" />

</LinearLayout>

Wednesday, March 18, 2015

How to set static IP on Android

This video show how to set static IP address on Android device.




  • In Wi-Fi settings.
  • Tap and hold the network you want to connect.
  • Tap Modify Network.
  • Tap to check Advanced Options.
  • Tap to select IP Settings, select Static.
  • Enter your setting.
  • Tap Save.



Monday, March 16, 2015

Draw text on Bitmap

Example to draw text on Bitmap.


package com.example.androidimageview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.SeekBar;

public class MainActivity extends ActionBarActivity {

 SeekBar textSizeBar;
 ImageView image1, image2;
 Button btnDrawText;
 EditText textIn;

 Bitmap bitmapOriginal;

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

  textSizeBar = (SeekBar) findViewById(R.id.textsize);
  btnDrawText = (Button) findViewById(R.id.drawtext);
  textIn = (EditText) findViewById(R.id.textin);
  image1 = (ImageView) findViewById(R.id.image1);
  image2 = (ImageView) findViewById(R.id.image2);

  bitmapOriginal = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);
  image1.setImageBitmap(bitmapOriginal);

  btnDrawText.setOnClickListener(btnDrawTextOnClickListener);

  ReloadImage();

 }
 
 OnClickListener btnDrawTextOnClickListener = new OnClickListener(){

  @Override
  public void onClick(View v) {
   ReloadImage();
  }};

 private void ReloadImage() {

  int textSize = textSizeBar.getProgress();
  String textToDraw = textIn.getText().toString();

  Bitmap newBitmap = bitmapOriginal.copy(bitmapOriginal.getConfig(), true);

  Canvas newCanvas = new Canvas(newBitmap);
  Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
  paint.setColor(Color.RED);
  paint.setTextSize(textSize);

  Rect bounds = new Rect();
  paint.getTextBounds(textToDraw, 0, textToDraw.length(), bounds);
  int x = 0;
  int y = newBitmap.getHeight();
  
  newCanvas.drawText(textToDraw, x, y, paint);
  
  image1.setImageBitmap(newBitmap);
  image2.setImageBitmap(newBitmap);

 }

}

<LinearLayout 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:orientation="vertical"
    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="com.example.androidimageview.MainActivity" >

    <TextView
        android:id="@+id/title"
        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" />
    
    <EditText
        android:id="@+id/textin"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <SeekBar
        android:id="@+id/textsize"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="50"
        android:progress="10" />
    
    <Button
        android:id="@+id/drawtext"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Draw text on bitmap" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/image1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
        
        <ImageView
            android:id="@+id/image2"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#D0D0D0" />
    </LinearLayout>

</LinearLayout>


Friday, March 13, 2015

Android 5.1 Lollipop animation in Clock App

Xamarin Cross-platform Application Development - Second Edition

Develop production-ready applications for iOS and Android using Xamarin

Xamarin Cross-platform Application Development - Second Edition

About This Book
  • Write native iOS and Android applications with Xamarin.iOS and Xamarin.Android respectively
  • Learn strategies that allow you to share code between iOS and Android
  • Design user interfaces that can be shared across Android, iOS, and Windows Phone using Xamarin.Forms
Who This Book Is For
If you are a developer with experience in C# and are just getting into mobile development, this is the book for you. If you have experience with desktop applications or the Web, this book will give you a head start on cross-platform development.

In Detail
Developing a mobile application for just one platform is becoming a thing of the past. Companies expect their apps to be supported on both iOS and Android, while leveraging the best native features on both. Xamarin's tools help ease this problem by giving developers a single toolset to target both platforms.

This book is a step-by-step guide to building real-world applications for iOS and Android. The book walks you through building a chat application, complete with a backend web service and native features such as GPS location, camera, and push notifications. Additionally, you'll learn how to use external libraries with Xamarin and Xamarin.Forms to create shared user interfaces and make app-store-ready applications. This second edition has been updated with new screenshots and detailed steps to provide you with a holistic overview of the new features incorporated in Xamarin 3. By the end of the book, you will have gained expertise to build on the concepts learned and effectively develop a market-ready cross-platform application.

Thursday, March 12, 2015

Nexus 7 WiFi (2012) updated Android 5.1 Lollipop

My Nexus 7 WiFi (2012) updated Android 5.1 Lollipop. Tried for 5 minutes, seem improved greatly on performance:)




Tuesday, March 10, 2015

Merge bitmaps

Example show how to combin two bitmaps to one.


package com.example.androidimageview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends ActionBarActivity {

 SeekBar xScaleBar, yScaleBar;
 ImageView image1, image2, image3, image4;

 Bitmap bitmapOriginal;

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

  xScaleBar = (SeekBar) findViewById(R.id.xscale);
  yScaleBar = (SeekBar) findViewById(R.id.yscale);
  image1 = (ImageView) findViewById(R.id.image1);
  image2 = (ImageView) findViewById(R.id.image2);
  image3 = (ImageView) findViewById(R.id.image3);
  image4 = (ImageView) findViewById(R.id.image4);

  bitmapOriginal = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);
  image1.setImageBitmap(bitmapOriginal);

  xScaleBar.setOnSeekBarChangeListener(OnScaleChangeListener);
  yScaleBar.setOnSeekBarChangeListener(OnScaleChangeListener);

  ReloadImage();

 }

 OnSeekBarChangeListener OnScaleChangeListener = new OnSeekBarChangeListener() {

  @Override
  public void onProgressChanged(SeekBar seekBar, int progress,
    boolean fromUser) {
  }

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) {
  }

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) {
   ReloadImage();
  }
 };

 private void ReloadImage() {

  float xScale = (float)(xScaleBar.getProgress()-10) / 10.0f;
  float yScale = (float)(yScaleBar.getProgress()-10) / 10.0f;

  //between +1 and -1,
  //cannot be 0
  if (xScale >= 0 && xScale < 0.1f) {
   xScale = 0.1f;
  }else if(xScale < 0 && xScale > -0.1f){
   xScale = -0.1f;
  }

  if (yScale >= 0 && yScale < 0.1f) {
   yScale = 0.1f;
  }else if(yScale < 0 && yScale > -0.1f){
   yScale = -0.1f;
  }

  // create scaled bitmap using Matrix
  Matrix matrix = new Matrix();
  matrix.postScale(xScale, yScale);

  Bitmap bitmapScaled = Bitmap.createBitmap(bitmapOriginal, 0, 0,
    bitmapOriginal.getWidth(), bitmapOriginal.getHeight(), matrix,
    false);

  image2.setImageBitmap(bitmapScaled);
  
  //Merge two bitmaps to one
  Bitmap bitmapMerged = Bitmap.createBitmap(
    bitmapOriginal.getWidth(), 
    bitmapOriginal.getHeight(), 
    bitmapOriginal.getConfig()); 
  Canvas canvasMerged = new Canvas(bitmapMerged);
  canvasMerged.drawBitmap(bitmapOriginal, 0, 0, null);
  canvasMerged.drawBitmap(bitmapScaled, 0, 0, null);
  
  image3.setImageBitmap(bitmapMerged);
  image4.setImageBitmap(bitmapMerged);

 }

}

<LinearLayout 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:orientation="vertical"
    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="com.example.androidimageview.MainActivity" >

    <TextView
        android:id="@+id/title"
        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" />

    <SeekBar
        android:id="@+id/xscale"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="20"
        android:progress="20" />

    <SeekBar
        android:id="@+id/yscale"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="20"
        android:progress="20" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/image1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ImageView
            android:id="@+id/image2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#D0D0D0" />

        <ImageView
            android:id="@+id/image3"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#B0B0B0" />
        
        <ImageView
            android:id="@+id/image4"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#909090" />
    </LinearLayout>

</LinearLayout>


Monday, March 9, 2015

Flip bitmap using Matrix

Example to create flipped bitmap using Matrix.


package com.example.androidimageview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends ActionBarActivity {

 SeekBar xScaleBar, yScaleBar;
 ImageView image1, image2, image3;

 Bitmap bitmapOriginal;

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

  xScaleBar = (SeekBar) findViewById(R.id.xscale);
  yScaleBar = (SeekBar) findViewById(R.id.yscale);
  image1 = (ImageView) findViewById(R.id.image1);
  image2 = (ImageView) findViewById(R.id.image2);
  image3 = (ImageView) findViewById(R.id.image3);

  bitmapOriginal = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);
  image1.setImageBitmap(bitmapOriginal);

  xScaleBar.setOnSeekBarChangeListener(OnScaleChangeListener);
  yScaleBar.setOnSeekBarChangeListener(OnScaleChangeListener);

  ReloadImage();

 }

 OnSeekBarChangeListener OnScaleChangeListener = new OnSeekBarChangeListener() {

  @Override
  public void onProgressChanged(SeekBar seekBar, int progress,
    boolean fromUser) {
  }

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) {
  }

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) {
   ReloadImage();
  }
 };

 private void ReloadImage() {

  float xScale = (float)(xScaleBar.getProgress()-10) / 10.0f;
  float yScale = (float)(yScaleBar.getProgress()-10) / 10.0f;

  //between +1 and -1,
  //cannot be 0
  if (xScale >= 0 && xScale < 0.1f) {
   xScale = 0.1f;
  }else if(xScale < 0 && xScale > -0.1f){
   xScale = -0.1f;
  }

  if (yScale >= 0 && yScale < 0.1f) {
   yScale = 0.1f;
  }else if(yScale < 0 && yScale > -0.1f){
   yScale = -0.1f;
  }

  // create scaled bitmap using Matrix
  Matrix matrix = new Matrix();
  matrix.postScale(xScale, yScale);

  Bitmap bitmapScaled = Bitmap.createBitmap(bitmapOriginal, 0, 0,
    bitmapOriginal.getWidth(), bitmapOriginal.getHeight(), matrix,
    false);

  image2.setImageBitmap(bitmapScaled);
  image3.setImageBitmap(bitmapScaled);

 }

}

<LinearLayout 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:orientation="vertical"
    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="com.example.androidimageview.MainActivity" >

    <TextView
        android:id="@+id/title"
        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" />

    <SeekBar
        android:id="@+id/xscale"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="20"
        android:progress="20" />

    <SeekBar
        android:id="@+id/yscale"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="20"
        android:progress="20" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/image1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ImageView
            android:id="@+id/image2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#D0D0D0" />

        <ImageView
            android:id="@+id/image3"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#B0B0B0" />
    </LinearLayout>

</LinearLayout>


Sunday, March 8, 2015

Rotate bitmap using Matrix

Example show how to create rotated bitmap using Matrix.


package com.example.androidimageview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends ActionBarActivity {

 SeekBar rotateBar;
 ImageView image1, image2, image3;

 Bitmap bitmapOriginal;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  rotateBar = (SeekBar)findViewById(R.id.rotate);
  image1 = (ImageView) findViewById(R.id.image1);
  image2 = (ImageView) findViewById(R.id.image2);
  image3 = (ImageView) findViewById(R.id.image3);

  bitmapOriginal = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);
  image1.setImageBitmap(bitmapOriginal);
  
  rotateBar.setOnSeekBarChangeListener(OnRotateChangeListener);

  ReloadImage();

 }
 
 OnSeekBarChangeListener OnRotateChangeListener = new OnSeekBarChangeListener(){

  @Override
  public void onProgressChanged(SeekBar seekBar, int progress,
    boolean fromUser) {}

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) {}

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) {
   ReloadImage();
  }};
  
 private void ReloadImage(){
  
  float degrees = rotateBar.getProgress() - 180;

  //create rotated bitmap using Matrix
        Matrix matrix = new Matrix();
        matrix.postRotate(degrees, 
         bitmapOriginal.getWidth()/2, bitmapOriginal.getHeight()/2);
        
        Bitmap bitmapRot = Bitmap.createBitmap(
          bitmapOriginal, 
          0, 0, 
          bitmapOriginal.getWidth(), bitmapOriginal.getHeight(), 
          matrix, true);

  image2.setImageBitmap(bitmapRot);
  image3.setImageBitmap(bitmapRot);
 }

}

<LinearLayout 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:orientation="vertical"
    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="com.example.androidimageview.MainActivity" >

    <TextView
        android:id="@+id/title"
        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" />

    <SeekBar
        android:id="@+id/rotate"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="360"
        android:progress="180" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/image1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ImageView
            android:id="@+id/image2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#D0D0D0" />

        <ImageView
            android:id="@+id/image3"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#B0B0B0" />
    </LinearLayout>

</LinearLayout>


Scale bitmap using Matrix

This example show how to create scaled bitmap using Matrix.


package com.example.androidimageview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.Toast;
import android.widget.SeekBar.OnSeekBarChangeListener;

public class MainActivity extends ActionBarActivity {

 SeekBar xScaleBar, yScaleBar;
 ImageView image1, image2;

 Bitmap bitmapOriginal;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  xScaleBar = (SeekBar)findViewById(R.id.xscale);
  yScaleBar = (SeekBar)findViewById(R.id.yscale);
  image1 = (ImageView) findViewById(R.id.image1);
  image2 = (ImageView) findViewById(R.id.image2);

  bitmapOriginal = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);
  image1.setImageBitmap(bitmapOriginal);
  
  xScaleBar.setOnSeekBarChangeListener(OnScaleChangeListener);
  yScaleBar.setOnSeekBarChangeListener(OnScaleChangeListener);
  
  Toast.makeText(MainActivity.this, 
    bitmapOriginal.getWidth() + " x " + bitmapOriginal.getHeight(), 
    Toast.LENGTH_LONG).show();
  
  ReloadImage();

 }
 
 OnSeekBarChangeListener OnScaleChangeListener = new OnSeekBarChangeListener(){

  @Override
  public void onProgressChanged(SeekBar seekBar, int progress,
    boolean fromUser) {}

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) {}

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) {
   ReloadImage();
  }};
  
 private void ReloadImage(){
  
  float xScale = xScaleBar.getProgress()/10.0f;
  float yScale = yScaleBar.getProgress()/10.0f;

  if(xScale<=0){
   xScale = 0.1f;
  }
  
  if(yScale<=0){
   yScale = 0.1f;
  }
  
  //create scaled bitmap using Matrix
  Matrix matrix = new Matrix();
        matrix.postScale(xScale, yScale);

        Bitmap bitmapScaled = Bitmap.createBitmap(
          bitmapOriginal, 
          0, 0, 
          bitmapOriginal.getWidth(), bitmapOriginal.getHeight(), 
          matrix, true);

  image2.setImageBitmap(bitmapScaled);

 }

}

<LinearLayout 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:orientation="vertical"
    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="com.example.androidimageview.MainActivity" >

    <TextView
        android:id="@+id/title"
        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" />

    <SeekBar
        android:id="@+id/xscale"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="30"
        android:progress="10" />

    <SeekBar
        android:id="@+id/yscale"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:max="30"
        android:progress="10" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/image1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ImageView
            android:id="@+id/image2"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    </LinearLayout>

</LinearLayout>


Wednesday, March 4, 2015

Professional Android Wearables

The fast and easy way to get up and running on Android wearables

Professional Android Wearables

Written by an expert author team with years of hands-on experience in designing and building wearables, Professional Android Wearables covers how to use the Android Wear platform and other techniques to build real-world apps for a variety of wearables including smartbands, smartwatches, and smart glasses. In no time, you'll grasp how wearables can connect us to the Internet in more pervasive ways than with PCs, tablets, or mobile devices; how to build code using Google's Wear SDK for Android-enabled hardware devices; how Android Wear and other Android development techniques are capable of building several presented example projects; and much more.

Wearables are the next generation of smart mobile devices, it's no wonder you will want to master Android Wear SDK to build smart wearable apps for a multitude of form factors and applications.

  • Shows you how to navigate Android Wear SDK
  • Clearly explains how to use the Android Wear platform to build real-world apps
  • The companion website includes source code for all of the projects described in the book

If you're an experienced Android developer looking to master Android Wear SDK to build wearable apps, you've come to the right place.

Learning Java by Building Android Games


Learning Java by Building Android Games

Android is the fastest growing operating system (OS) with one of the largest installed bases of any mobile OS. Android uses one of the most popular programming languages, Java, as the primary language for building apps of all types. So, you should first obtain a solid grasp of the Java language and its foundation APIs to improve the chances of succeeding as an Android app developer.

This book will show you how to get your Android development environment set up and you will soon have your first working game. The difficulty level grows steadily with the introduction of key Java topics such as loops, methods, and OOP. You'll then use them in the development of games. You will learn how to build a math test game, a Simon-like memory game, a retro pong-style game, and for the grand finale, a Snake-style, retro arcade game with real Google Play leaderboards and achievements. The book has a hands-on approach and is packed with screenshots.

Monday, March 2, 2015

Exploring SE for Android

Discover Security Enhancements (SE) for Android to build your own protected Android-based systems

About This Book

Exploring SE for Android
  • Learn the fundamental security models and motivations behind Linux, SELinux, and SE for Android.
  • Build and enable current security enhancements from the SE for Android project onto a working embedded UDOO board.
  • Discover how to leverage SE for Android to secure your own projects in powerful ways using this step by step guide.

Who This Book Is For
This book is intended for developers and engineers with some familiarity of operating system concepts as implemented by Linux. A basic background in C code would be helpful. Their positions range from hobbyists wanting to secure their Android powered creations to OEM engineers building handsets to engineers of emerging areas where Android is seeing growth.

In Detail
You will start by exploring the nature of the security mechanisms behind Linux and SELinux, and as you complete the chapters, you will integrate and enable SE for Android into a System on Chip (SoC), a process that, prior to this book, has never before been documented in its entirety! Discover Android's unique user space, from its use of the common UID and GID model to promote its security goals to its custom binder IPC mechanism. Explore the interface between the kernel and user space with respect to SELinux and investigate contexts and labels and their application to system objects.

This book will help you develop the necessary skills to evaluate and engineer secured products with the Android platform, whether you are new to world of Security Enhanced Linux (SELinux) or experienced in secure system deployment.

Sunday, March 1, 2015

interactive exercise of ScriptIntrinsicConvolve3x3

Last example show how to "Sharpen and blur bitmap using ScriptIntrinsicConvolve3x3", here is a interactive exercise of ScriptIntrinsicConvolve3x3. You can adjust coefficients of ScriptIntrinsicConvolve3x3, and view the result.


package com.example.androidimageview;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.renderscript.Allocation;
import android.renderscript.Element;
import android.renderscript.RenderScript;
import android.renderscript.ScriptIntrinsicConvolve3x3;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class MainActivity extends ActionBarActivity {

 ImageView image1, image2;
 SeekBar coeff0, coeff1, coeff2;
 SeekBar coeff3, coeff4, coeff5;
 SeekBar coeff6, coeff7, coeff8;
 SeekBar devBy;
 Button btnBlur, btnOrg, btnSharpen;
 
 TextView textCoeff;
 
 float[] matrix = {
   0, 0, 0,
   0, 1, 0,
   0, 0, 0
 };

 Bitmap bitmapOriginal, bitmapCoeff;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  
  coeff0 = (SeekBar)findViewById(R.id.coeff0);
  coeff1 = (SeekBar)findViewById(R.id.coeff1);
  coeff2 = (SeekBar)findViewById(R.id.coeff2);
  coeff3 = (SeekBar)findViewById(R.id.coeff3);
  coeff4 = (SeekBar)findViewById(R.id.coeff4);
  coeff5 = (SeekBar)findViewById(R.id.coeff5);
  coeff6 = (SeekBar)findViewById(R.id.coeff6);
  coeff7 = (SeekBar)findViewById(R.id.coeff7);
  coeff8 = (SeekBar)findViewById(R.id.coeff8);
  devBy = (SeekBar)findViewById(R.id.coeffdivby);
  textCoeff = (TextView)findViewById(R.id.textcoeff);
  btnBlur = (Button)findViewById(R.id.blur);
  btnOrg = (Button)findViewById(R.id.org);
  btnSharpen = (Button)findViewById(R.id.sharpen);
  image1 = (ImageView) findViewById(R.id.image1);
  image2 = (ImageView) findViewById(R.id.image2);

  bitmapOriginal = BitmapFactory.decodeResource(getResources(),
    R.drawable.ic_launcher);
  
  coeff0.setOnSeekBarChangeListener(OnCoeffChangeListener);
  coeff1.setOnSeekBarChangeListener(OnCoeffChangeListener);
  coeff2.setOnSeekBarChangeListener(OnCoeffChangeListener);
  coeff3.setOnSeekBarChangeListener(OnCoeffChangeListener);
  coeff4.setOnSeekBarChangeListener(OnCoeffChangeListener);
  coeff5.setOnSeekBarChangeListener(OnCoeffChangeListener);
  coeff6.setOnSeekBarChangeListener(OnCoeffChangeListener);
  coeff7.setOnSeekBarChangeListener(OnCoeffChangeListener);
  coeff8.setOnSeekBarChangeListener(OnCoeffChangeListener);
  devBy.setOnSeekBarChangeListener(OnCoeffChangeListener);
  
  ReloadImage();
  
  btnBlur.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    coeff0.setProgress(1+10);
    coeff1.setProgress(1+10);
    coeff2.setProgress(1+10);
    coeff3.setProgress(1+10);
    coeff4.setProgress(1+10);
    coeff5.setProgress(1+10);
    coeff6.setProgress(1+10);
    coeff7.setProgress(1+10);
    coeff8.setProgress(1+10);
    devBy.setProgress(9-1);
    ReloadImage();
   }});
  
  btnOrg.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    coeff0.setProgress(0+10);
    coeff1.setProgress(0+10);
    coeff2.setProgress(0+10);
    coeff3.setProgress(0+10);
    coeff4.setProgress(1+10);
    coeff5.setProgress(0+10);
    coeff6.setProgress(0+10);
    coeff7.setProgress(0+10);
    coeff8.setProgress(0+10);
    devBy.setProgress(1-1);
    ReloadImage();
   }});
  
  btnSharpen.setOnClickListener(new OnClickListener(){

   @Override
   public void onClick(View v) {
    coeff0.setProgress(0+10);
    coeff1.setProgress(-1+10);
    coeff2.setProgress(0+10);
    coeff3.setProgress(-1+10);
    coeff4.setProgress(5+10);
    coeff5.setProgress(-1+10);
    coeff6.setProgress(0+10);
    coeff7.setProgress(-1+10);
    coeff8.setProgress(0+10);
    devBy.setProgress(1-1);
    ReloadImage();
   }});
 }
 
 OnSeekBarChangeListener OnCoeffChangeListener = new OnSeekBarChangeListener(){

  @Override
  public void onProgressChanged(SeekBar seekBar, int progress,
    boolean fromUser) {}

  @Override
  public void onStartTrackingTouch(SeekBar seekBar) {}

  @Override
  public void onStopTrackingTouch(SeekBar seekBar) {
   ReloadImage();
  }};
  
 private void ReloadImage(){
  updateMatrix();
  bitmapCoeff = createBitmap_convolve(bitmapOriginal, matrix);
  image1.setImageBitmap(bitmapCoeff);
  image2.setImageBitmap(bitmapCoeff);
 }
 
 private void updateMatrix(){
  float div = devBy.getProgress() + 1;
  matrix[0] = (coeff0.getProgress()-10)/div;
  matrix[1] = (coeff1.getProgress()-10)/div;
  matrix[2] = (coeff2.getProgress()-10)/div;
  matrix[3] = (coeff3.getProgress()-10)/div;
  matrix[4] = (coeff4.getProgress()-10)/div;
  matrix[5] = (coeff5.getProgress()-10)/div;
  matrix[6] = (coeff6.getProgress()-10)/div;
  matrix[7] = (coeff7.getProgress()-10)/div;
  matrix[8] = (coeff8.getProgress()-10)/div;
  
  textCoeff.setText(
   matrix[0] + " , " + matrix[1] + " , " + matrix[2] + " , \n" +
   matrix[3] + " , " + matrix[4] + " , " + matrix[5] + " , \n" +
   matrix[6] + " , " + matrix[7] + " , " + matrix[8]);
 }
 
 private Bitmap createBitmap_convolve(Bitmap src, float[] coefficients) {

  Bitmap result = Bitmap.createBitmap(src.getWidth(),
    src.getHeight(), src.getConfig());

  RenderScript renderScript = RenderScript.create(this);

  Allocation input = Allocation.createFromBitmap(renderScript, src);
  Allocation output = Allocation.createFromBitmap(renderScript, result);

  ScriptIntrinsicConvolve3x3 convolution = ScriptIntrinsicConvolve3x3
    .create(renderScript, Element.U8_4(renderScript));
  convolution.setInput(input);
  convolution.setCoefficients(coefficients);
  convolution.forEach(output);

  output.copyTo(result);
  renderScript.destroy();
  return result;
 }

}

<LinearLayout 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:orientation="vertical"
    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="com.example.androidimageview.MainActivity" >

    <TextView
        android:id="@+id/title"
        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" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <SeekBar
            android:id="@+id/coeff0"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:max="20"
            android:progress="10" />

        <SeekBar
            android:id="@+id/coeff1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:max="20"
            android:progress="10" />

        <SeekBar
            android:id="@+id/coeff2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:max="20"
            android:progress="10" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <SeekBar
            android:id="@+id/coeff3"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:max="20"
            android:progress="10" />

        <SeekBar
            android:id="@+id/coeff4"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:max="20"
            android:progress="11" />

        <SeekBar
            android:id="@+id/coeff5"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:max="20"
            android:progress="10" />
    </LinearLayout>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <SeekBar
            android:id="@+id/coeff6"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:max="20"
            android:progress="10" />

        <SeekBar
            android:id="@+id/coeff7"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:max="20"
            android:progress="10" />

        <SeekBar
            android:id="@+id/coeff8"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:max="20"
            android:progress="10" />
    </LinearLayout>
    
    <SeekBar
            android:id="@+id/coeffdivby"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:max="19"
            android:progress="0" />
    
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >
        
        <Button
            android:id="@+id/blur"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Blur"/>
        <Button
            android:id="@+id/org"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Original"/>
        <Button
            android:id="@+id/sharpen"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:text="Sharpen"/>
        
    </LinearLayout>
    
    <TextView
        android:id="@+id/textcoeff"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/image1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <ImageView
            android:id="@+id/image2"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </LinearLayout>

</LinearLayout>



download filesDownload the files.