Sunday, 18 August 2019

Things after Kotlin Android Extensions

Things after Kotlin Android Extensions(KTX)

I remembered in MVVM when I have to declare ViewModel, I initialize View Model like this.
private val viewModel: MainViewModel by lazy {

    ViewModelProvider(this).get(MainViewModel::class.java)
}
but now using KTX it becomes
//when you need fragment scope
private val viewModel: MainViewModel by viewModels()

//when you need activity scope
private val viewModel: MainViewModel by activityViewModels()
And when I have to declare RecyclerView View Holder, then either I use normal findByViewId() or Databinding
class RecyclerVH(private val binding: ItemXBinding) : RecyclerView.ViewHolder(binding.root) {

    fun bind(dataB: DataB) {
    
        binding.tvNote.text = dataB.note
    }
}
but after KTX View Holder become
class RecyclerVH(private val view: View) : RecyclerView.ViewHolder(view),LayoutContainer {

    override val containerView: View?
        get() = view
        
    fun bind(dataB: DataB) {
    
        tv_note.text = dataB.note
    }
}
And same activity, fragment or custom view, when you inflate then you have to initialize data binding

in Fragment
lateint var binding:MyviewFragmentBinding
override fun onCreateView(
    inflater: LayoutInflater, container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {

    binding=inflater.inflate(R.layout.myview_fragment, container, false))
    return binding.root!!
}

//To access view
binding.tvNote.text="Hello Binding"
in Activity
private val binding: ActivityMyviewBinding by lazy {

    DataBindingUtil.setContentView>(this, R.layout.activity_myview)
}

//To access view
binding.tvNote.text="Hello Binding"
But after KTX, Just access view id directly, more elegant code no more binding
tv_note.text="Hello DataBinding"
And for Custom View before KTX
class MyView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), View.OnClickListener {

    val binding = MyViewBinding.inflate(LayoutInflater.from(context), this, true)
    
    init{
    
      binding.tvNote.text="Hello binding"       
   }    
}
And after KTX it becomes
class MyView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), View.OnClickListener {

init{
    MyViewBinding.inflate(LayoutInflater.from(context), this, true)
    
    tv_note.text="Hello binding"       
   }    
   
}
or use LayoutContainer
class MyView @JvmOverloads constructor(
    context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0
) : FrameLayout(context, attrs, defStyleAttr), View.OnClickListener, LayoutContainer {

  private val view = LayoutInflater.from(context).inflate(R.layout.myview, this, true)

  override val containerView: View?
    get() = view
    init{
      tv_note.text="Hello LayoutContainer"       
   }    
}
Kotlin Android extension libraries or plugin which I have used for above sample codes
//For LayoutContainer and access view id directly.
apply plugin: 'kotlin-android-extensions' //in app build.gradle
//in android{} block
androidExtensions {
    experimental = true
}
//for viewModels and activityViewModels
androidx.fragment:fragment-ktx:$version

Monday, 23 April 2018

FFmpeg Commands


How to show video in middle and add padding around?

Original video dimension 720x402

 ffplay -vf "scale=640:240,pad=1280:480:(ow-iw)/2:(oh-ih)/2:color=red" Example2.mp4   

640x240 is (to be scaled) video width x height
1280x480 is padding

1280 = (1280-640)=640 padding we are adding in width, (ow-iw)/2 is a position, its mean, its in center.
same for 480,
480=(480-240)=240 padding we are adding in height, (oh-ih)/2 is a position, its mean, its in center

color=red is a background color, it can be in RRGGBB format e.g 0xff0000

Friday, 12 August 2016

Android ADB Commands, Tricks & Hacks

Android ADB Commands & Tricks

Android Debug Bridge (adb) is a versatile command line tool that lets you communicate with an emulator instance or connected Android device. It facilitates a variety of device actions, such as installing and debugging apps, and it provides access a Unix shell that you can use to run a variety of commands on an emulator or connected device. It is a client-server program that includes three components:
  • A client, which sends commands. The client runs on your development machine. You can invoke a client from a command-line terminal by issuing an adb command.
  • A daemon, which runs commands on a device. The daemon runs as a background process on each emulator or device instance.
  • A server, which manages communication between the client and the daemon. The server runs as a background process on your development machine.
read more

adb devices 

list all the devices which is connected with the system.

adb -e shell

open emulator shell

adb -d shell

open device shell

what if we have more than 2 emulators or devices

adb -s <serial no> shell

use serial number to open device shell

adb  shell pm list packages 

list all the installed app package name.

but how to get debugable apps package name

adb jdwp
list all debugable apps process id

adb shell cat /proc/<process id>/cmdline 
              or  
adb shell cat /proc/<process id>/comm  

use process id to get the package name

adb shell ps <process id>

use process id to know the process information

you can fire all those cmd in adb shell also

$adb shell

to enter in android shell

$cat /proc/<process id>/cmdline 
               or  
$cat /proc/<process id>/comm
use process id to get the package name

$ps <process id>

use process id to know the process information

some more interesting commands

Dial Number: 

adb shell service call phone 1 s16 "+9191919191" 

here phone is a service, 1 is service code & s16 is parameter type and "+9191919191" is a parameter value.

Call Number:

adb shell service call phone 2 s16 "" s16 "+9191919191"

here phone is a service, 2 is service code & s16 is a 1st parameter type but no value & s16 is a 2nd parameter type and "+9191919191" is a parameter value.

Kill-APP:

adb  shell am force-stop <package name> 

Start App

adb shell monkey -p <package name> -c android.intent.category.LAUNCHER 1

Pull Down StatusBar

adb shell service call statusbar 1

Pull Up StatusBar

adb shell service call statusbar 2

wakeup/Sleep device

adb shell input keyevent 26 

unlock device

adb shell input keyevent 82

others services

adb shell service list

 

 




 

Wednesday, 20 May 2015

How to create CircleDrawable in Android

 public class CircleDrawable extends Drawable { 
   float width; 
   float height; 
   Paint mPaint; 
   RectF mRectf; 
   Paint mPaintR; 
   public CircleDrawable(float width, float height, int color) { 
     this.width = width; 
     this.height = height; 
     mPaint = new Paint(Paint.ANTI_ALIAS_FLAG); 
     mPaint.setColor(color); 
     mPaint.setStyle(Paint.Style.FILL); 
     mPaintR = new Paint(Paint.ANTI_ALIAS_FLAG); 
     mPaintR.setColor(Color.RED); 
     mPaintR.setStyle(Paint.Style.STROKE); 
     mPaintR.setStrokeWidth(10f); 
     mRectf = new RectF(0, 0, width, height); 
     // mRectf.offset((getMinimumWidth() - width) / 2, (getMinimumHeight() - height) / 2); 
   } 
   @Override 
   public void draw(Canvas canvas) { 
     // canvas.drawRect(mRectf, mPaintR); 
     canvas.drawCircle(mRectf.centerX(), mRectf.centerY(), width / 2, mPaint); 
   } 
   @Override 
   public void setAlpha(int alpha) { 
   } 
   @Override 
   public void setColorFilter(ColorFilter cf) { 
   } 
   @Override 
   public int getOpacity() { 
     return 0; 
   } 
 } 

Thursday, 25 December 2014

How to Proguard Android APK

How to Proguard Android APK


-in jars: Specifies the input jars (or aars, wars, ears, zips, apks, or directories) of the application to be processed

-outjars:Specifies the names of the output jars (or aars, wars, ears, zips, apks, or directories). The processed input of the preceding -injars options will be written to the named jars.

-libraryjars: Specifies the library jars (or aars, wars, ears, zips, apks, or directories) of the application to be processed. The files in these jars will not be included in the output jars.

-dontskipnonpubliclibraryclassmembers: Specifies not to ignore package visible library class members (fields and methods).

-keep: Specifies classes and class members (fields and methods) to be preserved as entry points to your code.

Here  ReportingInteractionMode is a class in ACRA library. we have to keep this library in src to suppress Crash No such filed TOAST.
-keep class org.acra.ReportingInteractionMode { *; }  

Copy this contain and create file proguard.cfg and past into it.

 -injars   bin/classes  
 -injars   libs  
 -outjars   bin/classes-processed.jar  
 -libraryjars /home/.../adt-bundle-linux-x86-20140321/sdk/platforms/android-19/android.jar  
 -libraryjars /home/.../libs/android-query-full.0.26.7.jar  
 -libraryjars /home/.../libs/javassist.jar  
 -libraryjars /home/.../libs/joda-time-2.3.jar  
 -libraryjars /home/.../libs/libphonenumber-5.9.jar  
 -libraryjars /home/.../libs/nineoldandroids-2.4.0.jar  
 -optimizationpasses 1  
 -dontpreverify  
 -dontskipnonpubliclibraryclassmembers  
 -repackageclasses ''  
 -allowaccessmodification  
 -optimizations !code/simplification/arithmetic,!field  
 -keepattributes *Annotation*       
 -dontusemixedcaseclassnames  
 -dontskipnonpubliclibraryclasses  
 -dontpreverify  
 -verbose  
 -allowaccessmodification  
 -keepattributes *Annotation*  
 -dontwarn android.support.v7.**  
 -dontwarn in.android.Databases.**  
 -dontwarn in.android.PushNotification.**  
 -dontwarn in.andoroid.Utills.FileUtill  
 -dontwarn android.support.v4.**  
 -dontwarn com.androidquery.auth.**  
 -dontwarn javassist.**  
 -dontwarn org.brickred.socialauth.**  
 -dontwarn org.joda.time.**  
 -keep public class * extends android.app.Activity  
 -keep public class * extends android.app.Application  
 -keep public class * extends android.app.Service  
 -keep public class * extends android.content.BroadcastReceiver  
 -keep public class * extends android.content.ContentProvider  
 -keep public class com.android.vending.licensing.ILicensingService  
 -keepclasseswithmembernames class * {  
   native <methods>;  
 }  
 -keepclasseswithmembernames class * {  
   public <init>(android.content.Context, android.util.AttributeSet);  
 }  
 -keepclasseswithmembernames class * {  
   public <init>(android.content.Context, android.util.AttributeSet, int);  
 }  
 -keepclassmembers enum * {  
   public static **[] values();  
   public static ** valueOf(java.lang.String);  
 }  
 -keep class * implements android.os.Parcelable {  
  public static final android.os.Parcelable$Creator *;  
 }  
 # for minmize ACRA library Error we are using this ReportingInteractionMode   
 # otherwise you will get No Such field Toast   
 -keep class org.acra.ReportingInteractionMode { *; }  

In project.properties add this attribute and save it.

proguard.config=proguard.cfg 

then, export the project and create new keystore if you haven't created or use existing keystore and finish the wizard.

Monday, 22 December 2014

How to use Curl Library in Android


To compile Curl library for android, follow this post

Here is the simple Android Example using Curl Library.
Source Code:https://github.com/JohnnyIqbal/AndroidCurlEx

How to compile Curl Library for Android in Linux


1. Download the source code of curl library http://curl.haxx.se/download.html

2.Create a file build_andorid.sh and copy below content and save file into Curl folder.

 #!/bin/bash  
 NDK=<yourpath>/android-ndk-r9d  
 SYSROOT=$NDK/platforms/android-19/arch-arm/  
 CFLAGS="-fno-exceptions -Wno-multichar -mthumb -mthumb-interwork -nostdlib -lc -ldl -lm "  
 LDFLAGS="-Wl,--fix-cortex-a8"   
 export AR="$NDK/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86/bin/arm-linux-androideabi-ar"  
 export LD="$NDK/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86/bin/arm-linux-androideabi-ld"  
 export CC="$NDK/toolchains/arm-linux-androideabi-4.8/prebuilt/linux-x86/bin/arm-linux-androideabi-gcc --sysroot=$SYSROOT"  
 ./configure \  
 --host=arm-linux-androideabi \  
 --prefix=/<your output folder path where include,lib and bin will folder copy >/curllib/ \  
 --exec-prefix=/<your output folder path where include,lib and bin will folder copy >/curllib/  
 make clean  
 make  
 make install  

3.Change build_android.sh mode to executable mode,Open terminal and head(i,e. cd)  to curl directory and run below code.

 sudo chmod +x 777 build_android.sh  
 ./build_android.sh  

4. If you want to download compiled curl library  for android click below link
https://github.com/JohnnyIqbal/Curl_For_Android_Compiled

5. Android Example of Curl Library https://github.com/JohnnyIqbal/AndroidCurlEx

Tuesday, 16 December 2014

How to port C library to Android as a static library.

Hi,

How to port C library to Android as a static library.

We build the  C library as a static library(*.a) and build a shared library using static library. because Android packaged only shared library in apk.
SourceCode Link:https://github.com/JohnnyIqbal/PortStaticEx.git

How to port C library to Android as a shared library(.so)

Hi,

How to port C library to Android as a shared library(.so).

We build C library as a shared library for android because android packaged only shared library in apk.

SourceCode Link:https://github.com/JohnnyIqbal/PortSharedEx.git

Wednesday, 14 May 2014

HelloZMQ with Java

Hi,

This is ZMQ Java Client Example.
SourceCode Link:https://github.com/JohnnyIqbal/HelloZMQwithJava

1. Compile Server File First.
2. Then Compile Client File.

Thursday, 17 April 2014

NDKHello2 Tutorial

Hi,
This is my Second NDKHello2 Demo project for newbies

SourceCode Link:https://github.com/JohnnyIqbal/NDKHello2
Please add appcompat library to run this project

In this demo I added a folder src in jni folder and tried to compile.

I followed this process to make this project.

1. Create NativeLib.java file

2. Open terminal and head to project directory
  cd bin/classes   
and generate header files of NativeLib.java using this command
 javah -jni com.iqbal.ndkhello.ndk.NativeLib  
3. Copy NativeLib.h file in jni folder (Create if not exist in project root)
or you can use this command
 javah -jni -o ../../jni/NativeLib.h com.iqbal.ndkhello.ndk.NativeLib  

4. Create NativeLib.c file and copy method signature in NativeLib.c
and don't foreget to include NativeLib.h


 Method Signature eg:  
 JNIEXPORT jstring JNICALL Java_com_iqbal_ndkhello_ndk_NativeLib_getHello2  
this is the declared method in header files and change to method defination

 #include"NativeLib.h"  
 JNIEXPORT jstring JNICALL Java_com_iqbal_ndkhello_ndk_NativeLib_getHello (JNIEnv *env, jclass clz){ return (*env)->NewStringUTF(env,"Hello World2"); }  

Note:NewStringUTF sometimes this function shows error means red line to suppress this error please update your CDT.

5. Add new folder in jni called src add some c files and header files as I did main.c and main.h

6. Call main.h function in NativeLib.c by including main.h header files.
 #include"src/main.h"  
 JNIEXPORT jint JNICALL Java_com_iqbal_ndkhello2_ndk_NativeLib_getAdd(  
   JNIEnv *env, jclass clz, jint a, jint b) {  
 int c=add(a,b); //this function declared in main.h and defiened in main.c  
 return c;  
 }  

7.Now create Android.mk file and write these lines to build
 LOCAL_PATH:=$(call my-dir)  
 include $(CLEAR_VARS)   
 LOCAL_MODULE:=hello2   
 LOCAL_SRC_FILES:=NativeLib.c src/main.c  
 include $(BUILD_SHARED_LIBRARY)  

8.Create Application.mk to suppress the Warnning or error android-19 is larger than minsdkversion 8 and write this lines
 APP_PLATFORM:=android-8  
android-8 is my minsdkversion so be sure about this change according to minsdkversion in AndroidManifest.xml


9.Open terminal head to project root and fire this command
 ndk-build  

10. Now run your Android NDKHello Project.


How to sync contacts Android

Hi,

Source Code Link: https://github.com/JohnnyIqbal/ContactSyncBG

Please add appcomapt library to run this project.

This is ContactSyncBackground Demo as you see whatsapp,viber or other apps

I followed this process to achieve syncing in background

1. Create AuthenticatorService and ContactsSyncAdapter Service class.
AuthenticatorService Class is for when you create syncing account then this service run
so you can perform any operation during creating account or add account in setting.

2. To create account
SyncUtils.CreateAccount(instance, user, pass);

3. When account created successfully then you want to sync your contacts, ContactsSyncAdapterService is run when you perform syncing either manually(using setting) or automatically.

4. To perform syncing automatically
 AccountManager am = AccountManager.get(instance);  
  Account[] acclist = am.getAccounts();  
  for (Account acc : acclist) {  
   if (acc.type.equals(SyncUtils.ACCOUNT_TYPE)) {  
   // You need pass bundle to sync  
   Bundle b = new Bundle();  
   b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);  
   b.putBoolean(ContentResolver.SYNC_EXTRAS_EXPEDITED, true);  
   ContentResolver.requestSync(acc, SyncUtils.AUTHORITY, b);  
   Log.i("MainActivity", "Request to sync Contacts");  
   }  
  }  
5. After firing this operation onPerformSync() method called in ContactsSyncAdapterService
   Here you can perform network syncing operation. I poupulated the contacts in json and post to server
   and server returning me intersection of contacts.
 
6. You need to register this service in Manifiest

  <service  
       android:name="com.iqbal.contactsyncbg.sync.ContactsSyncAdapterService"  
       android:exported="true"  
       android:process=":contacts" >  
       <intent-filter>  
         <action android:name="android.content.SyncAdapter" />  
       </intent-filter>  
       <meta-data  
         android:name="android.content.SyncAdapter"  
         android:resource="@xml/sync_contacts" />  
       <meta-data  
         android:name="android.provider.CONTACTS_STRUCTURE"  
         android:resource="@xml/contacts" />  
     </service>  
     <service  
       android:name="com.iqbal.contactsyncbg.sync.AuthenticatorService"  
       android:exported="true"  
       android:process=":auth" >  
       <intent-filter>  
         <action android:name="android.accounts.AccountAuthenticator" />  
       </intent-filter>  
       <meta-data  
         android:name="android.accounts.AccountAuthenticator"  
         android:resource="@xml/authenticator" />  
     </service>  
 7. Be sure of Account Type what you defined in sync_contacts and ContactSyncAdapter must be same.
  Otherwise you will get this exception caller uid is different than the authenticator's uid to fix
  this exception you need to check account type.
     
 8. At last you need to add permission
 <uses-permission android:name="android.permission.READ_CONTACTS" />  
 <uses-permission android:name="android.permission.WRITE_CONTACTS" />  
 <uses-permission android:name="android.permission.GET_ACCOUNTS" />  
 <uses-permission android:name="android.permission.MANAGE_ACCOUNTS" />  
 <uses-permission android:name="android.permission.AUTHENTICATE_ACCOUNTS" />  
 <uses-permission android:name="android.permission.READ_SYNC_SETTINGS" />  
 <uses-permission android:name="android.permission.WRITE_SYNC_SETTINGS" />  

Wednesday, 16 April 2014

Hello NDK

Source Code Link: https://github.com/JohnnyIqbal/NDKHello
Please add appcompat library to run this project

This is my First NDKHello Demo project for newbies

Create Simple Android Application Project.
then

1. Create NativeLib.java file

2. Open terminal and head to project directory
 cd bin/classes and  
generate header files of NativeLib.java using this command
  javah -jni com.iqbal.ndkhello.ndk.NativeLib  

3. Copy NativeLib.h file in jni folder (Create if not exist in project root)
or you can use this command
  javah -jni -o ../../jni/NativeLib.h com.iqbal.ndkhello.ndk.NativeLib  

4. Create NativeLib.c file and copy method signature in NativeLib.c
and don't foreget to include NativeLib.h

Method Signature eg:
 JNIEXPORT jstring JNICALL Java_com_iqbal_ndkhello_ndk_NativeLib_getHello  
 (JNIEnv *, jclass);  

this is the declared method in header files and change to method defination
  #include"NativeLib.h"  
 JNIEXPORT jstring JNICALL Java_com_iqbal_ndkhello_ndk_NativeLib_getHello  
  (JNIEnv *env, jclass clz){  
  return (*env)->NewStringUTF(env,"Hello World");  
 }  

Note:NewStringUTF sometimes this function shows error means red line to suppress this error please update your CDT.

5.Now create Android.mk file and write these lines
 LOCAL_PATH := $(call my-dir)  
 include $(CLEAR_VARS)  
 LOCAL_MODULE := hello  
 LOCAL_SRC_FILES := NativeLib.c  
 include $(BUILD_SHARED_LIBRARY)  

6.Create Application.mk to suppress the Warnning or error android-19 is larger than minsdkversion 8....
and write this lines
 APP_PLATFORM:=android-8  

Note:android-8 is my minsdkversion so be sure about this change according to minsdkversion in AndroidManifest.xml

7.Open terminal head to project root and fire this command
 ndk-build  

8. Now run your Android NDKHello Project.

Reference:
http://www.ntu.edu.sg/home/ehchua/programming/android/Android_NDK.html

Wednesday, 15 January 2014

Java Regex for Indian Mobile Number

 public class RegExTest {  
   public static void main(String arg[]) {  
     String str = "0888"; //"+91989898" "9180709709"  
     String regex="^([\\+](91))+([0-9]+$)|(^(0))+([0-9]+$)"; //{10} if you want to give no limit  
     Pattern pat = Pattern.compile(regex);  
     Matcher mat= pat.matcher(str);  
     if (mat.matches()) {  
       System.out.println("String matched");  
     } else {  
       System.out.println("String not matched");  
     }  
   }  
 }  


To give number limit use this regex:

String regex="^([\\+](91))+([0-9]{10}$)|(^(0))+([0-9]{10}$)"; 

Here {10} means after 0 or +91 must be 10 number

Thursday, 21 November 2013

XMPP Client Android GTalk Sample



Before doing this app Download ASmack Library and Enable Internet permission in you manifiest.


 public class ASmackAsync extends AsyncTask<String, Void, String>{  
 private ProgressDialog pd;  
 private Context ctxt;  
 public ASmackAsync(Context ctxt) {  
 this.ctxt=ctxt;  
 }  
 @Override  
 protected void onPreExecute() {  
 super.onPreExecute();  
 pd=new ProgressDialog(ctxt);  
 pd.show();  
 pd.setContentView(new ProgressBar(ctxt), new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));  
 }  
 @Override  
 protected String doInBackground(String... params) {  
 return ASmack.connectGServer(params[0], params[1]);  
 }  
 @Override  
 protected void onPostExecute(String result) {  
 super.onPostExecute(result);  
 pd.dismiss();  
 if(result==ASmack.GCONNECT){  
 Toast.makeText(ctxt, "Connected",10).show();  
 }else{  
 Toast.makeText(ctxt, result,10).show();  
 }  
 }  
 }  
 public class ASmack {  
 public static String GCONNECT="GCONNECTED";  
 public static XMPPConnection gconn;  
 public static String connectGServer(String user,String pass){  
 String host="talk.google.com";  
 int port=5222;  
 String service="gmail.com";  
 ConnectionConfiguration config=new ConnectionConfiguration(host,port,service);  
 gconn=new XMPPConnection(config);  
 SASLAuthentication.supportSASLMechanism("PLAIN", 0);  
 config.setDebuggerEnabled(true);  
 try {  
 gconn.connect();  
 Log.i("Host", gconn.getHost());  
 gconn.login(user, pass);  
 } catch (XMPPException e) {  
 e.printStackTrace();  
 }  
 return GCONNECT;  
 }  
 }  



Thursday, 28 March 2013

3D Game Tutorial 1 Android

1. Set Activity as a Game View
GameView:- Here our game will be run.
 public class MainActivity extends Activity {  
 @Override  
 protected void onCreate(Bundle savedInstanceState) {  
 super.onCreate(savedInstanceState);  
 GLSurfaceView view=new GLSurfaceView(this);  
 view.setRenderer(new MyRender());  
 setContentView(view);  
 }  
  }  


GLSurfaceView: on Activity we are setting the game view. Using this class, we can set our game view.
So we are creating the object of GLSurfaceView and giving the reference of Activity class. Using GLSurfaceView object we can handle activity operations.
setRenderer(new MyRender): To render(drawing) on the screen we need one Render class(MyRender) which can perform render operations.
and at last we are setting the view of an activity.
2. Implementing the Renderer 
 public class MyRender implements Renderer {  
 Cube cb=new Cube();  
 @Override  
 public void onDrawFrame(GL10 gl) {  
 gl.glMatrixMode(GL10.GL_MODELVIEW);  
 gl.glLoadIdentity();  
 gl.glTranslatef(0, 0, -1);  
 cb.draw(gl);  
 }  
 @Override  
 public void onSurfaceChanged(GL10 gl, int width, int height) {  
 gl.glViewport(0, 0, width, height);  
 float ar=(float)width/height;  
 gl.glMatrixMode(GL10.GL_PROJECTION);  
 gl.glLoadIdentity();  
 //gl.glOrthof(-1, 1, -1, 1, 1, -1);  
 gl.glFrustumf(-ar, ar, -1, 1, 1, 10);  
 }  
 @Override  
 public void onSurfaceCreated(GL10 gl, EGLConfig config) {  
 }  
 }  

Our MyRender class implementing Renderer method. When we call set Render method in Activity.
First of all, our onSurfaceCreated method called and Its create the surface for an render.
After that,onSurfaceChanged method called and Its create our viewport to draw.
At Last, onDrawFrame called and this method is the game loop. It will execute continously like infinite loop.
if we want to draw any thing on the screen and want to perform any operation on it, we must write our code into onDrawFrame.

onSurfaceChanged()
we are going to project our view so we are setting projection matrix.
we will calculate the aspect ratio to correct the dispaly ( we can correct horizontal display or vertical display).
and setting on the frustum.
and Finally.
onDrawFrame()
It is a game loop. So here we transalting our view with respect to z. So we are setting ModelView matrix. and Translating with respect to z.

3.Creating Cube Class

 public class Cube {  
 float vertices1[]={  
 -1,-1,  
 1,-1,  
 1,1,  
 -1,1,  
 };  
 byte indices1[]={  
 0,1,2,0,2,3 };  
 FloatBuffer vb;  
 ByteBuffer ib;  
 Cube(){  
 ByteBuffer bb=ByteBuffer.allocateDirect(vertices1.length*4);  
 bb.order(ByteOrder.nativeOrder());  
 vb=bb.asFloatBuffer();  
 vb.put(vertices1);  
  vb.position(0);  
 ib=ByteBuffer.allocateDirect(indices1.length);  
 ib.put(indices1);  
 ib.position(0);  
 }  
 void draw(GL10 gl){  
 gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);  
 gl.glVertexPointer(2, GL10.GL_FLOAT, 0, vb);  
 gl.glDrawElements(GL10.GL_TRIANGLES, 6, GL10.GL_UNSIGNED_BYTE, ib);  
  gl.glDisableClientState(GL10.GL_VERTEX_ARRAY);  
 }  
  }  


vertices[]


First of all we will set vertices and set the indices.
vertices    indices
 -1,-1           0
  1,-1           1
  1,1            2
  -1,1           3
in indices we are setting 0,1,2 means first Triangle and 0,2,3 means second Triangle means complete square.

Cube()
In cube constructor we are preparing the buffer to store the arrays. for the FloatBuffer we have to calculate the byte to store in Float buffer. so we are calculating the bytes and storing into in and setting the proper order. indices already in bytes so we don't need to convert.
draw(GL10 gl)
In draw method,
First of all, we will enable client vertax array(becuase this operation happeing in client side not an opengl side) to store the data into it and using the VertexPointer method we will store vertex buffer into it.
After that using DrawElements methods we will set our indexbuffer and draw the square.

References:-
http://songho.ca/opengl/index.html
Books:-
Mathematics for 3D Game Programming and Computer Graphics, Eric Lengyel.
Pro OpengGL ES for Android, Mike Smithwick and Mayank Verma

Saturday, 4 August 2012

My First Game

I have created my first Game from this site www.edu4java.com and This site provided a very good tutorials for the beginners.

Things after Kotlin Android Extensions

Things after Kotlin Android Extensions(KTX) I remembered in MVVM when I have to declare ViewModel, I initialize View Model like this. p...