Sunday, 21 September 2014

Network Availability check in Android

public static boolean isNetworkAvailable(Context act) {
        ConnectivityManager connectivityManager
              = (ConnectivityManager) act.getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;
    }

if(isNetworkAvailable(MainActivity.this)
{
//connection avilable
}
else{
//no connection

}

GPS Tracker in Android

class GPSTracker extends Service implements LocationListener {

    private final Context mContext;

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location
    double latitude; // latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute

    // Declaring a Location Manager
    protected LocationManager locationManager;

    public GPSTracker(Context context) {
        this.mContext = context;
        getLocation();
    }

    public Location getLocation() {
        try {
            locationManager = (LocationManager) mContext
                    .getSystemService(LOCATION_SERVICE);

            // getting GPS status
            isGPSEnabled = locationManager
                    .isProviderEnabled(LocationManager.GPS_PROVIDER);

            // getting network status
            isNetworkEnabled = locationManager
                    .isProviderEnabled(LocationManager.NETWORK_PROVIDER);

            if (!isGPSEnabled && !isNetworkEnabled) {
                // no network provider is enabled
            } else {
                this.canGetLocation = true;
                // First get location from Network Provider
                if (isNetworkEnabled) {
                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                    Log.d("Network", "Network");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                        if (location != null) {
                            latitude = location.getLatitude();
                            longitude = location.getLongitude();
                        }
                    }
                }
                // if GPS Enabled get lat/long using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, this);
                        Log.d("GPS Enabled", "GPS Enabled");
                        if (locationManager != null) {
                            location = locationManager
                                    .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                            if (location != null) {
                                latitude = location.getLatitude();
                                longitude = location.getLongitude();
                            }
                        }
                    }
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return location;
    }
   
    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
    public void stopUsingGPS(){
        if(locationManager != null){
            locationManager.removeUpdates(GPSTracker.this);
        }    
    }
   
    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }
       
        // return latitude
        return latitude;
    }
   
    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }
       
        // return longitude
        return longitude;
    }
   
    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }
   
    /**
     * Function to show settings alert dialog
     * On pressing Settings button will lauch Settings Options
     * */
    public void showSettingsAlert(){
        AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);
     
        // Setting Dialog Title
        alertDialog.setTitle("GPS is settings");
 
        // Setting Dialog Message
        alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");
 
        // On pressing Settings button
        alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
//                Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
//                mContext.startActivity(intent);
            }
        });
 
        // on pressing cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            dialog.cancel();
            }
        });
 
        // Showing Alert Message
        alertDialog.show();
    }

    @Override
    public void onLocationChanged(Location location) {
   
   
   
    }

    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }

}



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

Calling in Activity


GPSTracker gPSTracker;

        gPSTracker=new GPSTracker(getActivity());
//Locate current location
if (gPSTracker.canGetLocation())
{
stringLatitude = String.valueOf(gPSTracker.getLatitude());
stringLongitude = String.valueOf(gPSTracker.getLongitude());
//String place=gPSTracker.getLocality(getApplicationContext());
Double locationLatitude=Double.parseDouble(stringLatitude);
Double locationLongitude=Double.parseDouble(stringLongitude);
}

Thursday, 3 April 2014

To provide animation to each radio button in a radioburron  group in android.

Here I am creating  RadioGroup Dynamicaly
int numAnswer=5;
RadioGroup radioGroupd=new RadioGroup(getApplicationContext());
                int numAnswer=Integer.valueOf(questions.get(showedNum).questions_answers_count);
                for(int i=0;i<numAnswer;i++)
                {
                    button=new  RadioButton(getApplicationContext());
                    button.setTextColor(Color.GREEN);
                    button.setId(i);
                    button.setTextSize(subtextSize);
                    button.setText(questions.get(showedNum).answer_list[i]);
                    radioGroupd.addView(button);
                }
             //imp  
                radioGroupd.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
                {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        // TODO Auto-generated method stub
/
                     int id=   group.getCheckedRadioButtonId();//get id
                        RadioButton b = (RadioButton) findViewById(id);
                                   b.startAnimation(myanimateItems);
                    }
                  
                });

How can I add Animation to RadioGroup in android

To provide animation to each radio button in a radioburron  group in android.

Here I am creating  RadioGroup Dynamicaly
int numAnswer=5;
RadioGroup radioGroupd=new RadioGroup(getApplicationContext());
                int numAnswer=Integer.valueOf(questions.get(showedNum).questions_answers_count);
                for(int i=0;i<numAnswer;i++)
                {
                    button=new  RadioButton(getApplicationContext());
                    button.setTextColor(Color.GREEN);
                    button.setId(i);
                    button.setTextSize(subtextSize);
                    button.setText(questions.get(showedNum).answer_list[i]);
                    radioGroupd.addView(button);
                }
             //imp  
                radioGroupd.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener()
                {
                    @Override
                    public void onCheckedChanged(RadioGroup group, int checkedId) {
                        // TODO Auto-generated method stub
/
                     int id=   group.getCheckedRadioButtonId();//get id
                        RadioButton b = (RadioButton) findViewById(id);
                                   b.startAnimation(myanimateItems);
                    }
                  
                });

Thursday, 3 January 2013

TimePicker View in Android

The TimePicker view enables users to select a time of the day, in either 24 Hour mode or AM/PM mode.For this you can use "android.widget.TimePicker" class in android.

You can create TimePicker View using <TimePicker> xml element like this -
 <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
       

The TimePicker view displays a standard UI to enable user to set a time. By default, it displays time in the AM/PM format. If you want to change time in the 24 hour format, then you can use the setIs24HourView() method. There are two other important methods of TimePicker -
  • getCurrentHour()
  • getCurrentMinute()
Please note that getCurrentHour() method always returns the hour in 24-hour format i.e. value from 0 to 23.
   

activity_main.xml

(res/layout/activity_main.xml)


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

      <TimePicker
        android:id="@+id/timePicker"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
    
    <Button
        android:id="@+id/btn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="
Display Time" />
 </LinearLayout>
 

 
TimePickerDemoActivity
(File: TimePickerDemoActivity.java)

package com.example.timepickerdemosimple;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
   
    TimePicker timepicker;
   
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
       
        timepicker = (TimePicker) findViewById(R.id.timePicker);
        timepicker.setIs24HourView(true);
       
      
        // Button View
       Button button = (Button) findViewById(R.id.btn);
       button.setOnClickListener(new View.OnClickListener() {
       
     //   @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
       
        Toast.makeText(getBaseContext(),"Time Selected : "+timepicker.getCurrentHour()+":"
                +timepicker.getCurrentMinute(), Toast.LENGTH_SHORT).show();

        }
    });
    }


Output

 


 

Saturday, 1 September 2012

Java Constuctor


  • The constructor in Java have same name as name of class in which they belong.
  • The constructor in java does not have any return type, science never return anything.
  • The main use of constructor is to initialize the value of the reference variable to instance variable. 
  • Java provide a default constructor which takes no arguments and performs no special actions or initializations,when no explicit constructor are provided.