Hi Friends, if you like my blog please give your valuable comments it will help to improve my blog content and enthusiasm to write a lot in android World.

Tuesday, November 18, 2014

Check Network Connection Using BroadcastReceiver

BroadCastSampleActivity.java

public class BroadCastSampleActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        this.registerReceiver(this.mConnReceiver,
                new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
    }
    private BroadcastReceiver mConnReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            boolean noConnectivity = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
            String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
            boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);

            NetworkInfo currentNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
            NetworkInfo otherNetworkInfo = (NetworkInfo) intent.getParcelableExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO);

            if(currentNetworkInfo.isConnected()){
                Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
            }else{
                Toast.makeText(getApplicationContext(), "Not Connected", Toast.LENGTH_LONG).show();
            }
        }
    };
}

Add uses-permission in  AndroidManifest


    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Friday, April 4, 2014

Android - How to Get activity from context

Sometimes we pass context of an activity as a parameter to some other function and later we might want the activity too. So instead of passing the activity also to that function, we can get the activity from context itself.

You can get the activity from the context by type casting the context to activity.

Activity activity = (Activity) _context;

Monday, December 23, 2013

How to check if an APK has the flag set as true

Using the aapt tool you can check lots of things inside an apk. Use the following command:

aapt list -v -a myfile.apk

this shows hundreds of lines, but you must search the following text "android:debuggable"

this flag can have the values:

0x0: debuggable false
0xffffffff: debugabble true

in my case the entire line is the following

A: android:debuggable(0x0101000f)=(type 0x12)0xffffffff

Oops! My release build had the flag enabled ;) 

Wednesday, August 21, 2013

Detect Current Location in Android Using GPS/NETWORK Provider


Using the Location Manager class, we can obtain periodic updates of the device's geographical locations as well as fire an intent when it enters the proximity of a certain location.


1. Obtain a reference to the LocationManager class using the getSystemService() method.
    LocationManager lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


2. Create a LocationListener Class for notify the location changes.
Our MyLocationListener class should implements the LocationListener abstract class. There are four methods that you need to override in this implementation:
    * onLocationChanged(Location location): This method is called when the location has changed.
    * onProviderDisabled(String provider): This method is called when the provider is disabled by the user.
    * onProviderEnabled(String provider): This method is called when the provider is enabled by the user.
    * onStatusChanged(String provider, int status, Bundle extras): This method is called when the provider status changes.


3. To be notified whenever there is a change in location, you need to register for a request for changes in locations so that your program can be notified periodically. This is done via the requestLocationUpdates() method (see Listing 1).

This method takes in four parameters:
    * provider: The name of the provider with which you register
    * minTime: The minimum time interval for notifications, in milliseconds.
    * minDistance: The minimum distance interval for notifications, in meters.
    * listener: An object whose onLocationChanged() method will be called for each location update.

4. Set the following User-Permission  in androidmanifest.xml
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"></uses-permission>


Sample Code :
package com.cureent;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;

public class TestActivity extends Activity implements OnClickListener, android.content.DialogInterface.OnClickListener {

    private EditText editTextShowLocation;
    private Button buttonGetLocation;
    private ProgressBar progress;

    private LocationManager locManager;
    private LocationListener locListener = new MyLocationListener();

    private boolean gps_enabled = false;
    private boolean network_enabled = false;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        editTextShowLocation = (EditText) findViewById(R.id.editText1);

        progress = (ProgressBar) findViewById(R.id.progressBar1);
        progress.setVisibility(View.GONE);

        buttonGetLocation = (Button) findViewById(R.id.button1);
        buttonGetLocation.setOnClickListener(this);

        locManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    }

    @Override
    public void onClick(View v) {
        progress.setVisibility(View.VISIBLE);
        // exceptions will be thrown if provider is not permitted.
        try {
            gps_enabled = locManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        } catch (Exception ex) {
        }
        try {
            network_enabled = locManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        } catch (Exception ex) {
        }

        // don't start listeners if no provider is enabled
        if (!gps_enabled && !network_enabled) {
            AlertDialog.Builder builder = new Builder(this);
            builder.setTitle("Attention!");
            builder.setMessage("Sorry, location is not determined. Please enable location providers");
            builder.setPositiveButton("OK", this);
            builder.setNeutralButton("Cancel", this);
            builder.create().show();
            progress.setVisibility(View.GONE);
        }

        if (gps_enabled) {
            locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locListener);
        }
        if (network_enabled) {
            locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0, 0, locListener);
        }
    }

    class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location location) {
            if (location != null) {
                // This needs to stop getting the location data and save the battery power.
                locManager.removeUpdates(locListener);

                String londitude = "Londitude: " + location.getLongitude();
                String latitude = "Latitude: " + location.getLatitude();
                String altitiude = "Altitiude: " + location.getAltitude();
                String accuracy = "Accuracy: " + location.getAccuracy();
                String time = "Time: " + location.getTime();

                editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
                progress.setVisibility(View.GONE);
            }
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub

        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // TODO Auto-generated method stub

        }
    }

    @Override
    public void onClick(DialogInterface dialog, int which) {
        if(which == DialogInterface.BUTTON_NEUTRAL){
            editTextShowLocation.setText("Sorry, location is not determined. To fix this please enable location providers");
        }else if (which == DialogInterface.BUTTON_POSITIVE) {
            startActivity(new Intent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS));
        }
    }

}

 Reverse geocoding:


package com.exercise.AndroidFromLocation;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import android.app.Activity;
import android.location.Address;
import android.location.Geocoder;
import android.os.Bundle;
import android.widget.TextView;

public class AndroidFromLocation extends Activity {

double LATITUDE = 37.42233;
double LONGITUDE = -122.083;

   /** Called when the activity is first created. */
   @Override
   public void onCreate(Bundle savedInstanceState) {
       super.onCreate(savedInstanceState);
       setContentView(R.layout.main);
       TextView myLatitude = (TextView)findViewById(R.id.mylatitude);
       TextView myLongitude = (TextView)findViewById(R.id.mylongitude);
       TextView myAddress = (TextView)findViewById(R.id.myaddress);
      
       myLatitude.setText("Latitude: " + String.valueOf(LATITUDE));
       myLongitude.setText("Longitude: " + String.valueOf(LONGITUDE));
      
       Geocoder geocoder = new Geocoder(this, Locale.ENGLISH);

       try {
  List<Address> addresses = geocoder.getFromLocation(LATITUDE, LONGITUDE, 1);
 
  if(addresses != null) {
   Address returnedAddress = addresses.get(0);
   StringBuilder strReturnedAddress = new StringBuilder("Address:\n");
   for(int i=0; i<returnedAddress.getMaxAddressLineIndex(); i++) {
    strReturnedAddress.append(returnedAddress.getAddressLine(i)).append("\n");
   }
   myAddress.setText(strReturnedAddress.toString());
  }
  else{
   myAddress.setText("No Address returned!");
  }
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
  myAddress.setText("Canont get Address!");
 }

   }
}


Main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:orientation="vertical"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   >
<TextView 
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="@string/hello"
   />
<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Location"
   android:background="#505050"
   />
<TextView
   android:id="@+id/mylatitude"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView
   android:id="@+id/mylongitude"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
<TextView
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   android:text="Address"
   android:background="#505050"
   />
<TextView
   android:id="@+id/myaddress"
   android:layout_width="fill_parent"
   android:layout_height="wrap_content"
   />
</LinearLayout>



Tuesday, July 30, 2013

Supporting apps in different screen sizes

Screen characteristicQualifier        Description
SizesmallResources for small size screens.
normalResources for normal size screens. (This is the baseline size.)
largeResources for large size screens.
xlargeResources for extra large size screens.
DensityldpiResources for low-density (ldpi) screens (~120dpi).
mdpiResources for medium-density (mdpi) screens (~160dpi). (This is the baseline density.)
hdpiResources for high-density (hdpi) screens (~240dpi).
xhdpiResources for extra high-density (xhdpi) screens (~320dpi).
nodpiResources for all densities. These are density-independent resources. The system does not scale resources tagged with this qualifier, regardless of the current screen's density.
tvdpiResources for screens somewhere between mdpi and hdpi; approximately 213dpi. This is not considered a "primary" density group. It is mostly intended for televisions and most apps shouldn't need it—providing mdpi and hdpi resources is sufficient for most apps and the system will scale them as appropriate. If you find it necessary to provide tvdpi resources, you should size them at a factor of 1.33*mdpi. For example, a 100px x 100px image for mdpi screens should be 133px x 133px for tvdpi.
OrientationlandResources for screens in the landscape orientation (wide aspect ratio).
portResources for screens in the portrait orientation (tall aspect ratio).
Aspect ratiolongResources for screens that have a significantly taller or wider aspect ratio (when in portrait or landscape orientation, respectively) than the baseline screen configuration.
notlongResources for use screens that have an aspect ratio that is similar to the baseline screen configuration.




You need to create different layout for diff screen size. Support all screen you need to create following layout:
  1. Low density Small screens QVGA 240x320 (120dpi):
    layout-small-ldpi (240x320)  
    layout-small-land-ldpi (320x240)
  2. Low density Normal screens WVGA400 240x400 (x432) (120dpi):
    layout-ldpi  (240 x 400 )
    layout-land-ldpi  (400 x 240 )
  3. Medium density Normal screens HVGA 320x480 (160dpi):
    layout-mdpi (320 x 480 )
    layout-land-mdpi (480 x 320 )
  4. Medium density Large screens HVGA 320x480 (160dpi):
    layout-large-mdpi (320 x 480 )
    layout-large-land-mdpi (480 x 320)
  5. Galaxy Tab ( 240 dpi ):
    layout-large  (600 x 1024) 
    layout-large-land  (1024 x 600)
  6. High density Normal screens WVGA800 480x800 (x854) (240 dpi):
    layout-hdpi (480 x 800)
    layout-land-hdpi (800 x 480)
  7. Xoom (medium density large but 1280x800 res) (160 dpi):
    layout-xlarge (800 x 1280)
    layout-xlarge-land (1280 x 800)
Also add following code in .manifest file:

<supports-screens                                 
    android:smallScreens="true"                    
    android:normalScreens="true"         
    android:largeScreens="true"            
    android:xlargeScreens="true"             
    android:anyDensity="true" />
 

Toast show in center of screen

Toast mostly visible in bottom of screen. In bottom if we have any design then that toast will appear in front of our design. It's very irritating and annoying. so, Here i gave solution for that.



Toast toast = Toast.makeText(test.this,"www.arunkumarpd.blogspot.com", Toast.LENGTH_LONG);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();

Tuesday, May 21, 2013

Display the path of selected Picture in gallery

public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Gallery click = (Gallery) findViewById(R.id.gallery);

  final List<String> sdcard = ReadSDCard();
  click.setAdapter(new ImageAdapter(this, sdcard));
    
  click.setOnItemClickListener(new OnItemClickListener()
 {
      public void onItemClick(AdapterView<?> parent,
           View v, int position, long id) {
         Toast.makeText(Galleryy.this,
    (CharSequence)sdcard.get(position),
    Toast.LENGTH_LONG).show();
      }
  });
}