Wednesday 10 October 2012

Read File by extension from memory in android


private static void searchFolderRecursive1(File folder) {
    if (folder != null) {
        if (folder.listFiles() != null) {
            for (File file : folder.listFiles()) {
                if (file.isFile()) {
                    if(file.getName().contains("file extension")){
                        Log.v("ooo", "path__="+file.getName());
                    }
                } else {
                    searchFolderRecursive1(file);
                }
            }
        }
    }
}

Friday 5 October 2012

Play Audio fron url or Server in android

try {
                MediaPlayer player = new MediaPlayer();
                player.setAudioStreamType(AudioManager.STREAM_MUSIC);
                player.setDataSource("server mp3 link" );
                player.prepare();
                            player.start();

            } catch (Exception e) {
                // TODO: handle exception
            }

Thursday 4 October 2012

What is push massage Service in Android (Cloud to device messaging )

Most mobile apps require data from the Internet. One approach for updating its data is that the apps periodically polls a server for new data (Polling). If no new data is available this approach uses unnecessary network bandwidth and consumes the battery of the mobile phone.
An alternative approach is that the server contacts the mobile app once new data is available (Push). If the data does not change constantly, Push is the preferred solution. 

As of Android 2.2 it is possible to push information to an Android app. This service is called Cloud to Device messaging or short C2DM.
In a C2DM you have three involved parties. The application server which wants to push messages to the Android device, Googles C2DM servers and the Android app. The program on the application server can be written in any programming language, e.g. Java, PHP, Python, etc.
When the application server needs to push a message to the Android application, it sends the message via an HTTP POST to Google’s C2DM servers.
The C2DM servers route the message to the device. If the device is not online, the message will be delivered once the device is available. Once the message is received, an Broadcast Intent is created. The mobile app has registered an Intent Receiver for this Broadcast. The app is started and processes the message via the defined Intent Receiver.
C2DM messages are limited in size to 1024 bytes and are intended to inform the device about new data not to transfer it. The typical workflow is that Googles C2DM servers notify the Android app that new data is available. Afterwards the Android app fetches the data from a different server.

Tuesday 2 October 2012

Display Text on User Define Path on android canvas

Path circle = new Path();
circle.addCircle(centerX, centerY, radius, Direction.CW);
// set the color and font size
Paint paint = new Paint();
paint.setColor(Color.BLUE);
paint.setTextSize(30);
paint.setAntiAlias(true);
// draw the text along the circle
canvas.drawTextOnPath(QUOTE, circle, 0, 30, paint);

Convert milliseconds to HH:MM:SS String in java


  1. long timeMillis = ...;  
  2. long time = timeMillis / 1000;  
  3. String seconds = Integer.toString((int)(time % 60));  
  4. String minutes = Integer.toString((int)((time % 3600) / 60));  
  5. String hours = Integer.toString((int)(time / 3600));  
  6. for (int i = 0; i < 2; i++) {  
  7. if (seconds.length() < 2) {  
  8. seconds = "0" + seconds;  
  9. }  
  10. if (minutes.length() < 2) {  
  11. minutes = "0" + minutes;  
  12. }  
  13. if (hours.length() < 2) {  
  14. hours = "0" + hours;  
  15. }  

Saturday 29 September 2012

Way to communicate with server in java

Many ways to communicate with a server

Socket class
• Lets you do general-purpose network programming
– Same as with desktop Java programming

HttpURLConnection
• Simplifies connections to HTTP servers
– Same as with desktop Java programming

HttpClient
• Simplest way to download entire content of a URL
– Not standard in Java SE, but standard in Android

JSONObject
• Simplifies creation and parsing of JSON data
– Not standard in Java SE, but standard in Android

Thursday 27 September 2012

Diffrent input-type value in EditText Android

  • none
  • text
  • textCapCharacters
  • textCapWords
  • textCapSentences
  • textAutoCorrect
  • textAutoComplete
  • textMultiLine
  • textImeMultiLine
  • textNoSuggestions
  • textUri
  • textEmailAddress
  • textEmailSubject
  • textShortMessage
  • textLongMessage
  • textPersonName
  • textPostalAddress
  • textPassword
  • textVisiblePassword
  • textWebEditText
  • textFilter
  • textPhonetic
  • textWebEmailAddress
  • textWebPassword
  • number
  • numberSigned
  • numberDecimal
  • numberPassword
  • phone
  • datetime
  • date
  • time

Friday 21 September 2012

Android Dialog Box with item select

final CharSequence[] items = {"Add Note", "Add Anniversary", "Add Event","View All"};
        AlertDialog.Builder builder = new
        AlertDialog.Builder(MyCalendar.this);
        builder.setTitle("Add Details");
        //builder.setIcon(R.drawable.calendarmonth);
        builder.setItems(items, new    DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int item)
        {
         if(item==0)
         {
             Intent in=new Intent(MyCalendar.this, AddNote.class);
                startActivity(in);
         }
         else if(item==1)
         {
             Intent in=new Intent(MyCalendar.this, AddAnnivarsory.class);
                startActivity(in);
         }
         else if(item==2)
         {
             Intent in=new Intent(MyCalendar.this, AddEvent.class);
                startActivity(in);
         }
         else if(item==3)
         {
             Intent in=new Intent(MyCalendar.this, ViewAll.class);
                startActivity(in);
         }
        }
        });
        AlertDialog alert = builder.create();
        alert.show();

Friday 14 September 2012

Open Android Market App using url in Android

Intent intent = new Intent(Intent.ACTION_VIEW); 
intent.setData(Uri.parse("market://search?q=pname:MyApp")); 
startActivity(intent);

Wednesday 12 September 2012

Upload Image from Android to Server using PHP

Android Activity for upload image on Server:--
package com.santosh.geo_map_social_app;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import android.os.AsyncTask;
import android.os.Bundle;
import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;

public class MainActivity extends Activity {

 InputStream is;

 @Override

 public void onCreate(Bundle icicle) {
  super.onCreate(icicle);
  setContentView(R.layout.activity_main);
  new  AddTask().execute();
 }
 class AddTask extends AsyncTask<Void,Void, Void> {

  private ProgressDialog dialog;
  protected void onPreExecute() {
   dialog = new ProgressDialog(MainActivity.this);
   dialog.setMessage("Retrieving data ...");
   dialog.setIndeterminate(true);
   dialog.setCancelable(false);
   dialog.show();
  }

  protected Void doInBackground(Void... unused) {
   Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher);
   ByteArrayOutputStream bao = new ByteArrayOutputStream();
   bitmapOrg.compress(Bitmap.CompressFormat.JPEG, 90, bao);
   byte [] ba = bao.toByteArray();
   String ba1=Base64.encodeBytes(ba);
   ArrayList<NameValuePair> nameValuePairs = new
     ArrayList<NameValuePair>();
   nameValuePairs.add(new BasicNameValuePair("image",ba1));
   try{
    HttpClient httpclient = new DefaultHttpClient();
    HttpPost httppost = new
      HttpPost("http://192.168.1.10:80/GK/ImageUpload.php");
    httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
    HttpResponse response = httpclient.execute(httppost);
    HttpEntity entity = response.getEntity();
    is = entity.getContent();
   }catch(Exception e){
    Log.e("log_tag", "Error in http connection "+e.toString());
   }
   return(null);
  }

  protected void onProgressUpdate(Void... unused) {
   // grid_main.setAdapter(imgadp);
  }

  protected void onPostExecute(Void unused) {
   dialog.dismiss();

  }
 }


}

Thursday 6 September 2012

Find Your CURRENT Location In Android

package com.santosh.map;

import android.app.Activity;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.Toast;

public class FindMyLocation extends Activity implements LocationListener{

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        LocationManager locationmanger=(LocationManager)getSystemService(Context.LOCATION_SERVICE);
        Criteria c=new Criteria();
        c.setAccuracy(Criteria.ACCURACY_FINE);
        c.setAltitudeRequired(false);
        c.setBearingRequired(false);
        c.setCostAllowed(true);
        c.setPowerRequirement(Criteria.POWER_LOW);
        String provider=locationmanger.getBestProvider(c, true);
        Location location=locationmanger.getLastKnownLocation(provider);
      
        locationmanger.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,
                0, 0, this);
      
    }


    @Override
    public void onLocationChanged(Location location) {
        if (location != null) {
            double lat = location.getLatitude();
            double lng = location.getLongitude();
            System.out.println("Lat:"+location.getLatitude());
            System.out.println("Lat:"+location.getLongitude());
            System.out.println("Lat:"+location.getAccuracy());
            System.out.println("Lat:"+location.getAltitude());
            System.out.println("Lat:"+location.getBearing());
            System.out.println("Lat:"+location.getProvider());
            System.out.println("Lat:"+location.getSpeed());
            System.out.println("Lat:"+location.getTime());
             }

        Toast.makeText(FindMyLocation.this, "onLocationChanged", 1).show();
    }

    @Override
    public void onProviderDisabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText(FindMyLocation.this, "onProviderDisabled", 1).show();
    }

    @Override
    public void onProviderEnabled(String provider) {
        // TODO Auto-generated method stub
        Toast.makeText(FindMyLocation.this, "onProviderEnabled", 1).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        // TODO Auto-generated method stub
        Toast.makeText(FindMyLocation.this, "onStatusChanged", 1).show();
    }
 
   
   
}

Wednesday 5 September 2012

Delect Incoming Call in Android

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();
  }
  
 }
 
 
//////////////////////////////////////
 
interface ITelephony {

   
    boolean endCall();

  
    void answerRingingCall();

   
    void silenceRinger();

  }
 
/////////////////////////////////////////////
 
   android:name="android.permission.MODIFY_PHONE_STATE" />
     android:name="android.permission.CALL_PHONE" />
     android:name="android.permission.READ_PHONE_STATE" />
  

Delect Outgoing Call in android

public class OutgoingCallReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
                Bundle bundle = intent.getExtras();
               
                if(null == bundle)
                        return;
               
                String phonenumber = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);

                Log.i("OutgoingCallReceiver",phonenumber);
                Log.i("OutgoingCallReceiver",bundle.toString());
               
                String info = "Detect Calls sample application\nOutgoing number: " + phonenumber;
               
                Toast.makeText(context, info, Toast.LENGTH_LONG).show();
        }
}

Friday 31 August 2012

Custom DialogBox in Android

Context mContext = getApplicationContext();
Dialog dialog = new Dialog(mContext);
dialog.setContentView(R.layout.custom_dialog);
dialog.setTitle("Custom Dialog");
TextView text = (TextView) dialog.findViewById(R.id.text);
text.setText("Hello, this is a custom dialog!");
ImageView image = (ImageView) dialog.findViewById(R.id.image);
image.setImageResource(R.drawable.android);

Thursday 30 August 2012

Customize Header in Andorid


Use this in oncreate Mathod
requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE,R.layout.topheader);

Read CSV file In Android

    public String[] Read(Context c)
    {
       
           InputStream is = c.getResources().openRawResource (R.raw.list);
           BufferedReader buff= new BufferedReader(new InputStreamReader(is),4*1024);
           int count=0;
             // get the quote as a csv string
             try {
                 String line;
                 while((line=buff.readLine())!=null)
                 {
                    System.out.println(line);
                    StringTokenizer tokenizer = new StringTokenizer(line, ",");
                    id[count]=Integer.toString(count);
                    company[count]=tokenizer.nextToken();
                    symbols[count]=tokenizer.nextToken();
                    from[count]=tokenizer.nextToken();
                    count++;
                 }
               
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    return company;
    }

Tuesday 28 August 2012

Create DataBase in Android using SQL Lite


public class DatabaseHandler extends SQLiteOpenHelper {
 
    // All Static variables
    // Database Version
    private static final int DATABASE_VERSION = 1;
 
    // Database Name
    private static final String DATABASE_NAME = "contactsManager";
 
    // Contacts table name
    private static final String TABLE_CONTACTS = "contacts";
 
    // Contacts Table Columns names
    private static final String KEY_ID = "id";
    private static final String KEY_NAME = "name";
    private static final String KEY_PH_NO = "phone_number";
 
    public DatabaseHandler(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);
    }
 
    // Creating Tables
    @Override
    public void onCreate(SQLiteDatabase db) {
        String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
                + KEY_ID + " INTEGER PRIMARY KEY," + KEY_NAME + " TEXT,"
                + KEY_PH_NO + " TEXT" + ")";
        db.execSQL(CREATE_CONTACTS_TABLE);
    }
 
    // Upgrading database
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // Drop older table if existed
        db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
 
        // Create tables again
        onCreate(db);
    }
 
    /**
     * All CRUD(Create, Read, Update, Delete) Operations
     */
 
    // Adding new contact
    void addContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
 
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName()); // Contact Name
        values.put(KEY_PH_NO, contact.getPhoneNumber()); // Contact Phone
 
        // Inserting Row
        db.insert(TABLE_CONTACTS, null, values);
        db.close(); // Closing database connection
    }
 
    // Getting single contact
    Contact getContact(int id) {
        SQLiteDatabase db = this.getReadableDatabase();
 
        Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
                KEY_NAME, KEY_PH_NO }, KEY_ID + "=?",
                new String[] { String.valueOf(id) }, null, null, null, null);
        if (cursor != null)
            cursor.moveToFirst();
 
        Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
                cursor.getString(1), cursor.getString(2));
        // return contact
        return contact;
    }
 
    // Getting All Contacts
    public List getAllContacts() {
        List contactList = new ArrayList();
        // Select All Query
        String selectQuery = "SELECT  * FROM " + TABLE_CONTACTS;
 
        SQLiteDatabase db = this.getWritableDatabase();
        Cursor cursor = db.rawQuery(selectQuery, null);
 
        // looping through all rows and adding to list
        if (cursor.moveToFirst()) {
            do {
                Contact contact = new Contact();
                contact.setID(Integer.parseInt(cursor.getString(0)));
                contact.setName(cursor.getString(1));
                contact.setPhoneNumber(cursor.getString(2));
                // Adding contact to list
                contactList.add(contact);
            } while (cursor.moveToNext());
        }
 
        // return contact list
        return contactList;
    }
 
    // Updating single contact
    public int updateContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
 
        ContentValues values = new ContentValues();
        values.put(KEY_NAME, contact.getName());
        values.put(KEY_PH_NO, contact.getPhoneNumber());
 
        // updating row
        return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
    }
 
    // Deleting single contact
    public void deleteContact(Contact contact) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
                new String[] { String.valueOf(contact.getID()) });
        db.close();
    }
 
    // Getting contacts Count
    public int getContactsCount() {
        String countQuery = "SELECT  * FROM " + TABLE_CONTACTS;
        SQLiteDatabase db = this.getReadableDatabase();
        Cursor cursor = db.rawQuery(countQuery, null);
        cursor.close();
 
        // return count
        return cursor.getCount();
    }
 
}

Install and Uninstall Application using intent

Install APK using Intent:-

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(apkUri, "application/vnd.android.package-archive");
startActivity(intent);
 
Uninstall APK using Intent:
 
Intent intent = new Intent(Intent.ACTION_DELETE, Uri.fromParts("package",
getPackageManager().getPackageArchiveInfo(apkUri.getPath(), 0).packageName,null));
startActivity(intent);

Monday 20 August 2012

Find All Circle point in android

 for (int d = 0; d < 360; d++)
     {
            for(int r = 0; r < (int)(diameter/2); r++)
            {
            double x = r * Math.cos(Math.toRadians(d));
            double y = r * Math.sin(Math.toRadians(d));
              }
         }

Friday 17 August 2012

Set Height,Width and weight of view In Android

    LinearLayout.LayoutParams= new LinearLayout.LayoutParams(
                        LayoutParams.MATCH_PARENT,
                        LayoutParams.MATCH_PARENT, 0.5f);

Thursday 16 August 2012

Draw Transprent Bitmap on Android Canvas

Bitmap bitmap2 =Bitmap.createBitmap(bmp.getWidth(), bmp.getHeight(), Bitmap.Config.ARGB_8888);
        int width = bmp.getWidth();
        int height = bmp.getHeight();
        for(int x = 0; x < width; x++)
        {
            for(int y = 0; y < height; y++)
            {
              
                    bitmap2.setPixel(x, y, Color.TRANSPARENT);
             }
        }
        canvas.drawBitmap( bitmap2, 10, 10, p);

Draw And Move watch Needle on android canvas


import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;

public class MeterInAndroid {
    private int height;
    private int width;  
    int y=0;
    private int radius=100;
    public MeterInAndroid(Context context,int h,int w)
    {
        height=h;
        width=w;
    }
    public void Draw(Canvas canvas)
    {
        Paint p=new Paint();
        p.setColor(Color.WHITE);  
        double Number = Math.PI * 2 / 10;
        double Number2=Number*y;
        y++;
        float endX = (float) (width/2+(radius*(Math.cos(Number2))));
        float  endY = (float) (height/2+(radius*(Math.sin(Number2))));
        canvas.drawLine(width/2, height/2, endX, endY, p);
    }

}

Friday 10 August 2012


PHP Page for create and generate XML and JSON Object from DataBase

<?php
/* require the user as the parameter */
if(isset($_GET['user']) && intval($_GET['user'])) {

  /* soak in the passed variable or set our own */
  $number_of_posts = isset($_GET['num']) ? intval($_GET['num']) : 10; //10 is the default
  $format = strtolower($_GET['format']) == 'json' ? 'json' : 'xml'; //xml is the default
  $user_id = intval($_GET['user']); //no default

  /* connect to the db */
  $link = mysql_connect('localhost','root','') or die('Cannot connect to the DB');
  mysql_select_db('test',$link) or die('Cannot select the DB');

  /* grab the posts from the db */
  $query = "SELECT post_title, guid FROM wp_posts ";
  $result = mysql_query($query,$link) or die('Errant query:  '.$query);

  /* create one master array of the records */
  $posts = array();
  if(mysql_num_rows($result)) {
    while($post = mysql_fetch_assoc($result)) {
      $posts[] = array('post'=>$post);
    }
  }

  /* output in necessary format */
  if($format == 'json') {
    header('Content-type: application/json');
    echo json_encode(array('posts'=>$posts));
  }
  else {
    header('Content-type: text/xml');
    echo '<posts>';
    foreach($posts as $index => $post) {
      if(is_array($post)) {
        foreach($post as $key => $value) {
          echo '<',$key,'>';
          if(is_array($value)) {
            foreach($value as $tag => $val) {
              echo '<',$tag,'>',htmlentities($val),'</',$tag,'>';
            }
          }
          echo '</',$key,'>';
        }
      }
    }
    echo '</posts>';
  }

  /* disconnect from the db */
  @mysql_close($link);
}

?>

Create Round Corner ImageView in Android

Create Drawable xml for round corner ImageView just like below:-

<?xml version="1.0" encoding="UTF-8" ?>
  <shape xmlns:android="http://schemas.android.com/apk/res/android">
  <solid android:color="#000000" />
  <stroke android:width="3dp" android:color="#776da8" />
  <corners android:bottomRightRadius="5dp" android:bottomLeftRadius="5dp" android:topLeftRadius="5dp" android:topRightRadius="5dp" />
  <padding android:left="2dp" android:top="2dp" android:right="2dp" android:bottom="2dp" />
  </shape>

Now Set This into ImageView Background resource .....

Monday 23 July 2012

Add Integation


DisplayMetrics dm = new DisplayMetrics();
activity.getWindowManager().getDefaultDisplay().getMetrics(dm);
int screenWidth = dm.widthPixels;
String myAdId = "MY_LEADBOLT_SECTIONID_320";
if(screenWidth >= 720) {
myAdId = "MY_LEADBOLT_SECTIONID_720";
}
else if(screenWidth >= 640) {
myAdId = "MY_LEADBOLT_SECTIONID_640";
}
else if(screenWidth >= 468) {
myAdId = "MY_LEADBOLT_SECTIONID_468";
}
AdController myController = new AdController(activity, myAdId);
myController.setAsynchTask(true);
myController.loadAd();

Friday 6 July 2012

Move Object on Android Canvas 5

5:- Now Create Activity which call surfaceview :-




import java.io.IOException;
import java.util.HashMap;
import android.app.Activity;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Window;
import android.view.WindowManager;
import android.widget.LinearLayout;


public class Aarti extends Activity {

SoundPool soundPool;
HashMap<Integer, Integer> soundPoolMap;
int soundID = 1;
int width;
int height;
 
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
   super.onCreate(savedInstanceState);
  
   //soundPoolMap.put(soundID, soundPool.load(this, R.raw.adaon, 1));
   requestWindowFeature(Window.FEATURE_NO_TITLE);
   getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
   Display display = getWindowManager().getDefaultDisplay(); 
    width = display.getWidth();//get width
    height = display.getHeight();//get height
   setContentView(new ArtiView(this,width,height));
 
}   

@Override
protected void onDestroy() {
//Log.d(TAG, "Destroying...");
super.onDestroy();
}


@Override
protected void onStop() {
// Log.d(TAG, "Stopping...");
super.onStop();

 
}


}

Move Object on Android Canvas 4

4:- Now Create Class Speed :-



public class Speed {


public static final int DIRECTION_RIGHT = 1;
public static final int DIRECTION_LEFT = -1;
public static final int DIRECTION_UP = -1;
public static final int DIRECTION_DOWN = 1;

private int[] tt={100,500};
private float xv = 1; // velocity value on the X axis
private float yv = 1; // velocity value on the Y axis

private int xDirection = DIRECTION_RIGHT;
private int yDirection = DIRECTION_DOWN;

public Speed() {
this.xv = 2;
this.yv = 2;
}


public Speed(float xv, float yv) {
this.xv = xv;
this.yv = yv;
}


public float getXv() {
return xv;
}
public void setXv(float xv) {
this.xv = xv;
}
public float getYv() {
return yv;
}
public void setYv(float yv) {
this.yv = yv;
}


public int getxDirection() {
return xDirection;
}
public void setxDirection(int xDirection) {
this.xDirection = xDirection;
}
public int getyDirection() {
return yDirection;
}
public void setyDirection(int yDirection) {
this.yDirection = yDirection;
}


// changes the direction on the X axis
public void toggleXDirection() {
xDirection = xDirection * -1;
}


// changes the direction on the Y axis
public void toggleYDirection() {
yDirection = yDirection * -1;
}


}