Search Google

Thursday, 9 April 2015

Android SOURCE CODE

 code for Android App Permissions

  http://geekonjava.blogspot.in/search/label/android%20projects

'

Test GPS location with Android Studio

This article shows you how to set the GPS location in your Android Studio.
 1. Menu ->Tools -> Android ->Monitor (DDMS included)


2. Input the Longitude and Latitude in Location Control

 

Android game development : Moving or scrolling background

 

In game development in android, before we go further let have a look what we had achieved

    1) Basic science of game programming
    2) Creating surface to draw
    3) Creating dynamic object on surface and moving them

But in general , every game does not move their character much . They moves their background. But when a person plays, its seems everything is moving around. In android we draw an background with one bitmap.  And we start slowly moving background. This is important part game development.

Suppose one's want to develop a game in which, one's have one actor who's running all the way. Then real game scenerio will be like that

  • Animate actor on same place
  • Move the background in opposite direction

Moving background is quite simple, we scroll one image to some position and same image's another instance to respective direction to cover the space left by first one. and so on.......
This process need same image to draw continueously two times to fill the gap and never ending scrolling or moving of background

Look at the respective code in which backGround bitmap is background of canvas.....

 /**
  * Draws current state of the game Canvas.
  */
 private int mBGFarMoveX = 0;
 private int mBGNearMoveX = 0;

 private void doDrawRunning(Canvas canvas) {
  // decrement the far background
  mBGFarMoveX = mBGFarMoveX - 1;
  // decrement the near background
  mBGNearMoveX = mBGNearMoveX - 4;
  // calculate the wrap factor for matching image draw
  int newFarX = backGround.getWidth() - (-mBGFarMoveX);
  // if we have scrolled all the way, reset to start
  if (newFarX <= 0) {
   mBGFarMoveX = 0;
   // only need one draw
   canvas.drawBitmap(backGround, mBGFarMoveX, 0, null);
  } else {
   // need to draw original and wrap
   canvas.drawBitmap(backGround, mBGFarMoveX, 0, null);
   canvas.drawBitmap(backGround, newFarX, 0, null);
  }
  }

 I. How to create simple surface
II. How draw some object
III. How to implement Touch event on View
IV.Drawing shape on touch dynamically

Start with basic step create one project Creating Surface.

Step 2). create another class called  OnsurfaceToDraw.java 

in this class , we create rectangle and circle and line. read little bit about Paint , View , Touch event


package com.ahmad;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.os.SystemClock;
import android.view.MotionEvent;
import android.view.View;

public class OurSurfaceTodraw extends View {
    private Context context;

    public OurSurfaceTodraw(Context context) {
        super(context);
        this.context = context;
        setWillNotDraw(false);
        setFocusableInTouchMode(true);

    }
    long timedelay = SystemClock.currentThreadTimeMillis();
    @Override
    protected void onDraw(Canvas canvas) {
        // Setting canvas background
        setBackgroundColor(Color.WHITE);
        Paint paint = new Paint();
        paint.setColor(Color.RED);
        // Drawing Line on canvas
        canvas.drawLine(50, 200, 0, 10, paint);
        if ((SystemClock.currentThreadTimeMillis() + 3) > timedelay) {
            paint.setColor(Color.BLACK);
            canvas.drawRect(100, 100, 140, 140, paint);
        }
        // Drawing Rectangle or square
        if ((SystemClock.currentThreadTimeMillis() + 6) > timedelay) {
            paint.setColor(Color.BLACK);
            canvas.drawRect(100, 100, 140, 140, paint);
        }
        // Drawing Rectangle or square
        if ((SystemClock.currentThreadTimeMillis() + 6) > timedelay) {
            paint.setColor(Color.BLACK);
            canvas.drawCircle(100, 250, 20, paint);
        }
        if (mDynamic.isEmpty()) {

        } else {
            paint.setColor(Color.RED);
            for (int i = 0; i < mDynamic.size(); i++) {
                canvas.drawRect(mDynamic.get(i), paint);
            }
        }
        super.onDraw(canvas);
      }

    private ArrayList<Rect> mDynamic = new ArrayList<Rect>();

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        // TODO Auto-generated method stub
        int x = Math.round(event.getX());
        int y = Math.round(event.getY());
        Rect rect = new Rect(x, y, x + 30, y + 20);
        mDynamic.add(rect);
        invalidate();
        return super.onTouchEvent(event);
    }
}

Notable Line in above code are

 Drawing a circle,Rectangle and Line

 canvas.drawCircle(100, 250, 20, paint);
 canvas.drawRect(100, 100, 140, 140, paint);
 canvas.drawLine(50, 200, 0, 10, paint);

If we want to draw Rectangle dynamically then store all rectangle into one ArrayList and then draw by getting each element.

invalidate(); This will ensure that while you change something on touch it will draw to canvas
 Video will show how this out put will work
                             

 You can download complete source from below given link

                                  Download Source Code

package com.thelikes.thegot2run;



import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;


public class MainActivity extends Activity {
                protected void onCreate(Bundle savedInstanceState) {
                                super.onCreate(savedInstanceState);
                                setContentView(R.layout.activity_main);
                               
                }

                public void play(View v)
                {
                                Intent i=new Intent(this,Game.class);
                                startActivity(i);
                }
               
                public void highscore(View v)
                {
                                Intent i=new Intent(this,Highscore.class);
                                startActivity(i);
                }
               
                public void setting(View v)
                {
                                Intent i=new Intent(this,Setting.class);
                                startActivity(i);
                }
               
                public void exit(View v)
                {
                                System.exit(0);
                }
               
                }

Game.java

package com.thelikes.thegot2run;



import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Align;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.Window;
import android.view.WindowManager;

public class Game extends Activity {
        MediaPlayer mp1,jump,takecoin;
        gameloop gameLoopThread;
       protected void onCreate(Bundle savedInstanceState) {
              super.onCreate(savedInstanceState);
              //phone state
              TelephonyManager TelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
              TelephonyMgr.listen(new TeleListener(),PhoneStateListener.LISTEN_CALL_STATE);
              //for no title
              this.requestWindowFeature(Window.FEATURE_NO_TITLE);
              this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
              setContentView(new GameView(this));            
       }
      
       public class GameView extends SurfaceView{
             Bitmap bmp,pause;
             Bitmap background,kinfe,note1,powerimg,note2;
             Bitmap run1;
             Bitmap run2;
             Bitmap run3;
             Bitmap coin;
             Bitmap exit;
            
             private SurfaceHolder holder;
             private int x = 0,y=0,z=0,delay=0,getx,gety,sound=1;
             int show=0,sx,sy;
             int cspeed=0,kspeed=0,gameover=0;
             int score=0,health=100,reset=0;
             int pausecount=0,volume,power=0,powerrun=0,shieldrun=0;
            
            
           @SuppressWarnings("deprecation")
              @SuppressLint("NewApi")
              public GameView(Context context)
             {
                super(context);
                
                gameLoopThread = new gameloop(this);
                holder = getHolder();

                    holder.addCallback(new SurfaceHolder.Callback() {
                           @SuppressWarnings("deprecation")
                           @Override
                public void surfaceDestroyed(SurfaceHolder holder)
                {
                                   //for stoping the game
                                  gameLoopThread.setRunning(false);
                                  gameLoopThread.getThreadGroup().interrupt();
                    }
               
                @SuppressLint("WrongCall")
                           @Override
                public void surfaceCreated(SurfaceHolder holder)
                {
                       gameLoopThread.setRunning(true);
                       gameLoopThread.start();
                       
                    }
                @Override
                public void surfaceChanged(SurfaceHolder holder, int format,int width, int height)
                           {
                           }
                    });
                   
                    //getting the screen size
                    Display display = getWindowManager().getDefaultDisplay();
                                 
                                  sx = display.getWidth();
                                  sy = display.getHeight();;
                                  cspeed=sx/2;
                                  kspeed=sx/2;
                                  powerrun=(3*sx/4);
                                  shieldrun=sx/8;
                background = BitmapFactory.decodeResource(getResources(), R.drawable.back);
                run1=BitmapFactory.decodeResource(getResources(), R.drawable.run1);
                run2=BitmapFactory.decodeResource(getResources(), R.drawable.run2);
                run3=BitmapFactory.decodeResource(getResources(), R.drawable.run3);
                coin=BitmapFactory.decodeResource(getResources(), R.drawable.coin);
                exit=BitmapFactory.decodeResource(getResources(), R.drawable.exit);
                kinfe=BitmapFactory.decodeResource(getResources(), R.drawable.kinfe);
                note1=BitmapFactory.decodeResource(getResources(), R.drawable.note1);
                pause=BitmapFactory.decodeResource(getResources(), R.drawable.pause);
                powerimg=BitmapFactory.decodeResource(getResources(), R.drawable.power);
                note2=BitmapFactory.decodeResource(getResources(), R.drawable.note2);
                
                exit=Bitmap.createScaledBitmap(exit, 25,25, true);
                pause=Bitmap.createScaledBitmap(pause, 25,25, true);
                powerimg=Bitmap.createScaledBitmap(powerimg, 25,25, true);
                note2=Bitmap.createScaledBitmap(note2, sx,sy, true);
                run1=Bitmap.createScaledBitmap(run1, sx/9,sy/7, true);
                run2=Bitmap.createScaledBitmap(run2, sx/9,sy/7, true);
                run3=Bitmap.createScaledBitmap(run3, sx/9,sy/7, true);
                coin=Bitmap.createScaledBitmap(coin, sx/16,sy/24, true);
                background=Bitmap.createScaledBitmap(background, 2*sx,sy, true);
                //health dec
                note1=Bitmap.createScaledBitmap(note1, sx,sy, true);
                
                mp1=MediaPlayer.create(Game.this,R.raw.game);
                jump=MediaPlayer.create(Game.this,R.raw.jump);
                takecoin=MediaPlayer.create(Game.this,R.raw.cointake);
             }
            
             // on touch method
            
             @Override
                     public boolean onTouchEvent(MotionEvent event) {
                          
                     if(event.getAction()==MotionEvent.ACTION_DOWN)
                     {
                            show=1;
                           
                            getx=(int) event.getX();
                            gety=(int) event.getY();
                            //exit
                            if(getx<25&&gety<25)
                            {
                                   //high score
                                   SharedPreferences pref = getApplicationContext().getSharedPreferences("higher", MODE_PRIVATE);
                                Editor editor = pref.edit();
                                  editor.putInt("score", score);
                                editor.commit();
                                   System.exit(0);
                    
                            }
                            // restart game
                            if(getx>91&&gety<25)
                            {
                                   if(health<=0)
                                   {
                                         gameLoopThread.setPause(0);
                                                health=100;
                                                score=0;
                                  
                                   }
                            }
                            //pause game
                            if((getx>(sx-25)&&gety<25&&pausecount==0))
                            {
                                  
                                   gameLoopThread.setPause(1);
                                   mp1.stop();
                                   pausecount=1;
                            }
                            else if(getx>(sx-25)&&gety<25&&pausecount==1)
                            {
                                   gameLoopThread.setPause(0);
                                   mp1.start();
                                   pausecount=0;
                            }
                     }
                           
                            return true;
                     }
                    
            
               @SuppressLint("WrongCall")
                     @Override
                    protected void onDraw(Canvas canvas)
                    {
                
                //volume
                     SharedPreferences pref = getApplicationContext().getSharedPreferences("higher", MODE_PRIVATE);
                     Editor editor = pref.edit();
                     volume=pref.getInt("vloume", 0);
                     if(volume==0)
                     {
                            sound=0;
                     }
                  
                     canvas.drawColor(Color.BLACK);
                    
                     //background moving
                     z=z-10;
                     if(z==-sx)
                     {
                            z=0;
                            canvas.drawBitmap(background, z, 0, null);
                           
                     }
                     else
                     {
                            canvas.drawBitmap(background, z, 0, null);     
                     }
                    
                     //running player
                    
                             x+=5;
                             if(x==20)
                             {
                                    x=5;
                             }
                             
                              if(show==0)
                              {
                                     if(x%2==0)
                                     {
                                           canvas.drawBitmap(run3, sx/16, 15*sy/18, null);
                                          
                                     }
                                     else
                                     {
                                           canvas.drawBitmap(run1, sx/16, 15*sy/18, null);
                                          
                                     }
                                     
                                     
                                    //kinfe hit
                                   if(kspeed==20)
                                    {
                                           kspeed=sx;
                                           health-=25;
                                           canvas.drawBitmap(note1, 0, 0, null);
                                    }
                                    
                                   //power take
                                   if(powerrun==30)
                                         {
                                           powerrun=3*sx;
                                           health+=25;
                                           canvas.drawBitmap(note2, 0, 0, null);
                                         }
                              }
                            //power
                                    powerrun=powerrun-10;
                                    canvas.drawBitmap(powerimg, powerrun, 15*sy/18, null);
                                    
                                    if(powerrun<0)
                                    {
                                           powerrun=3*sx/4;
                                    }
                              
                            //kinfe
                                    kspeed=kspeed-20;
                                    canvas.drawBitmap(kinfe, kspeed, 15*sy/18, null);
                                    if(kspeed<0)
                                    {
                                           kspeed=sx;
                                    }
                                    
                            // for jump
                             if(show==1)
                             {
                                    if(sound==1)
                                    {
                                    jump.start();
                                    }
                                    
                                           canvas.drawBitmap(run2, sx/16, 3*sy/4, null);
                                           //score
                                           if(cspeed<=sx/8&&cspeed>=sx/16)
                                            {
                                                  if(sound==1)
                                                  {
                                                         takecoin.start();
                                                         
                                                  }
                                                  cspeed=sx/2;
                                                  score+=10;
                                               
                                           }
                                          
                                    
                                        
                                   // jump-hold
                                    delay+=1;
                                    if(delay==3)
                                    {
                                    show=0;
                                    delay=0;
                                    }
                             }
                             
                              //for coins
                              cspeed=cspeed-5;
                                  if(cspeed==-sx/2)
                                  {
                                         cspeed=sx/2;
                                         canvas.drawBitmap(coin, cspeed, 3*sy/4, null);
                             
                                  }
                                  else
                                  {
                                         canvas.drawBitmap(coin, cspeed, 3*sy/4, null); 
                                  }
                                 
                                 
                                    
                                    
                                  //score
                                         Paint paint = new Paint();
                                      paint.setColor(Color.BLUE);
                                      paint.setAntiAlias(true);
                                      paint.setFakeBoldText(true);
                                      paint.setTextSize(15);
                                      paint.setTextAlign(Align.LEFT);
                                      canvas.drawText("Score :"+score, 3*sx/4, 20, paint);
                                   //exit
                                      canvas.drawBitmap(exit, 0, 0, null);
                                           if(sound==1)
                                           {
                                           mp1.start();
                                           mp1.setLooping(true);
                                           }
                                           else
                                           {
                                                 mp1.stop();
                                           }
                              //health
                                      Paint myPaint = new Paint();
                                       myPaint.setColor(Color.RED);
                                       myPaint.setStrokeWidth(10);
                                       myPaint.setAntiAlias(true);
                                       myPaint.setFakeBoldText(true);
                                      canvas.drawText("Health :"+health, 0, (sy/8)-5, myPaint);
                                      canvas.drawRect(0, sy/8, health, sy/8+10, myPaint);
                                     
                                    //game over
                                      if(health<=0)
                                      {
                                         gameover=1;
                                         mp1.stop();
                                        
                                         //high score
                                         editor.putInt("score", score);
                                      editor.commit();
                                      
                                         canvas.drawText("GAMEOVER OVER", sx/2, sy/2, myPaint);
                                         canvas.drawText("YOUR SCORE : "+score, sx/2, sy/4, myPaint);
                                         canvas.drawText("Restart", 91, 25, myPaint);
                                         gameLoopThread.setPause(1);
                                         canvas.drawBitmap(background, sx, sy, null);
                                      }
                                     // restart
                                     
                                         if(reset==1)
                                         {
                                                gameLoopThread.setPause(0);
                                                health=100;
                                                score=0;
                                         }
                                        
                                         canvas.drawBitmap(pause, (sx-25), 0, null);
                       }
                 
                    }
      
              //phone state
              public class TeleListener extends PhoneStateListener
              {
             public void onCallStateChanged(int state,String incomingNumber)
             {
               if(state==TelephonyManager.CALL_STATE_RINGING)
               {
                     mp1.stop();
                     System.exit(0); 
               }
              }
            
           }
}


Android make activity as Fullscreen (Removing Title Bar or Action Bar)

 http://developer.android.com/guide/topics/ui/actionbar.html

................

If want to make an activity to fullscreen in some cases like playing video in fullscreen mode, playing game etc., you can do that by following one of the methods.
Method 1


One way is using Theme.Holo.Light.NoActionBar.Fullscreen value in AndroidManifest.xml file. (Use the appropriate theme name whichever you used in your application)
<activity android:name=".MainActivity"
    android:label="@string/app_name"
    android:theme="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen">
</activity>
Method 2


Another way is, do this through code in the activity. In your activity do the following before calling setContentView() function
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                                WindowManager.LayoutParams.FLAG_FULLSCREEN);       
setContentView(R.layout.activity_main);

 

Android Reading Inbox SMS

Sample source code for reading inbox sms

import android.app.Activity;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.widget.TextView;

public class SMSRead extends Activity {

  @Override
  public void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      TextView view = new TextView(this);
      Uri uriSMSURI = Uri.parse("content://sms/inbox");
      Cursor cur = getContentResolver().query(uriSMSURI, null, null, null,null);
      String sms = "";
      while (cur.moveToNext()) {
          sms += "From :" + cur.getString(2) + " : " + cur.getString(11)+"\n";         
      }
      view.setText(sms);
      setContentView(view);
  }
}


Add below permission to AndroidManifest.xml
   
<uses-permission name="android.permission.READ_SMS" />
 
..................................

Blocking Incoming call - Android

Step 1:
Create Broadcast receiver class for incoming call

package com.javaorigin.android.sample;

import java.lang.reflect.Method;

import com.android.internal.telephony.ITelephony;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent
import android.telephony.TelephonyManager;
import android.util.Log;

public class PhoneCallReceiver extends BroadcastReceiver {
 Context context = null;
 private static final String TAG = "Phone call";
 private ITelephony telephonyService;

 @Override
 public void onReceive(Context context, Intent intent) {
  Log.v(TAG, "Receving....");
  TelephonyManager telephony = (TelephonyManager) 
  context.getSystemService(Context.TELEPHONY_SERVICE);  
  try {
   Class c = Class.forName(telephony.getClass().getName());
   Method m = c.getDeclaredMethod("getITelephony");
   m.setAccessible(true);
   telephonyService = (ITelephony) m.invoke(telephony);
   //telephonyService.silenceRinger();
   telephonyService.endCall();
  } catch (Exception e) {
   e.printStackTrace();
  }
  
 }

 
}


Step 2:
Create IDL interface for getting core Telephony service
package name must be com.android.internal.telephony

FileName : ITelephony.aidl
  package com.android.internal.telephony;

  interface ITelephony {

   
    boolean endCall();

  
    void answerRingingCall();

   
    void silenceRinger();

  }


Step 3:
AndroidManifest.xml configuration
  <?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="com.javaorigin.android.sample"
      android:versionCode="1"
      android:versionName="1.0">  
    <application android:icon="@drawable/icon" android:label="@string/app_name">

        <receiver  android:name=".PhoneCallReceiver">
            <intent-filter  android:priority="100" >
                <action android:name="android.intent.action.PHONE_STATE" />
            </intent-filter>
        </receiver>

    </application>
    <uses-sdk android:minSdkVersion="5" />
    <uses-permission android:name="android.permission.MODIFY_PHONE_STATE" />
    <uses-permission android:name="android.permission.CALL_PHONE" />
    <uses-permission android:name="android.permission.READ_PHONE_STATE" />

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

</manifest>
 
...............................................

Android Home And Lock Screen Widget - (Temperature Widget)

Create TemperatureWidget class and register with Temperature sensor intend
Download Source 
 

Android Device/Battery Temperature Sensor Sample

Create Temperature activity and create instance for android.intent.action.BATTERY_CHANGED intend  and register with Temperature Broadcast Receiver
Download Source
 

 

No comments:

Post a Comment