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();
      }
  });
}


Friday, April 12, 2013

Disable screen lock in android


KeyguardManager keyguardManager = (KeyguardManager)getSystemService(Activity.KEYGUARD_SERVICE);
KeyguardLock lock = keyguardManager.newKeyguardLock(KEYGUARD_SERVICE);
lock.disableKeyguard();


 androidmanifest:
<uses-permission android:name="android.permission.DISABLE_KEYGUARD"></uses-permission>

Simple Alert Popup with Title, Message, Icon and Button

AlertDialog alertDialog = new AlertDialog.Builder(this).create();
 alertDialog.setTitle("Title");
 alertDialog.setMessage("Message");
 alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
 public void onClick(DialogInterface dialog, int which) {
 // TODO Add your code for the button here.
 } });
 // Set the Icon for the Dialog
 alertDialog.setIcon(R.drawable.icon);
alertDialog.show();

Android- Embed Google Map in Web View

 package com.example.androidwebmap;
import android.os.Bundle;
import android.app.Activity;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class TestActivity extends Activity {

 WebView myWebView;

 String mapPath = "https://maps.google.com/?ll=37.0625,-95.677068&spn=29.301969,56.513672&t=h&z=4";

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);
  myWebView = (WebView)findViewById(R.id.mapview);
  myWebView.getSettings().setJavaScriptEnabled(true);
  myWebView.setWebViewClient(new WebViewClient());

  myWebView.loadUrl(mapPath);
 }

}

XML File


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:orientation="vertical"
    tools:context=".MainActivity" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
    <WebView
        android:id="@+id/mapview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</LinearLayout>



Important:
- Permission of "android.permission.INTERNET" is need.








Wednesday, April 10, 2013

Autostart our application when android device start from bootup


when you power on the device open our application starts.
through receiver we can achieve this one .

Androidmenifest.xml
 <receiver android:enabled="true" android:name=".Startourapp"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

        <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>

Startourapp.class

public class Startourapp extends BroadcastReceiver{
    @Override
    public void onReceive(Context context, Intent intent) {
            Intent i = new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
               context.startActivity(i);  

    }

}

Thursday, February 7, 2013

Trick to get source code from APK file


Required software's and Tools

Get APK source code files for Windows
or
Get APK source code files for Mac OS X
or
Get APK source code files for Linux







Step 1. Rename the .apk file you wish to retrieve and change the extension to .zip. Then extract the file that it creates.
Step 2. Copy the contents of the dex2jar folder to the extracted folder to make it easier for yourself, and run:
dex2jar classes.dex
and copy the resulting “classes.dex.dex2jar.jar” into a new folder.
Step 3. Open up the Java Decompiler and drag “classes.dex.dex2jar.jar” into the window and then go to File > Save and save the source in a .zip file.
Step 4. Extract the saved .zip and copy the contents to a new folder somewhere. This will be where we keep your source code.
Step 5. Now, copy “framework-res.apk” and “yourapk.apk” to the APKTool folder. Then open a command prompt or Terminal window and type:
apktool if framework-res.apk
apktool d <yourapk.apk>
Step 6. Now just copy the contents of the resulting folder to the same place you copied the contents of “classes.dex.dex2jar.jar” earlier and voila, you have your source code. You may need to remove a couple of things as shown in the video, but your entire code should be there!

Import project into eclipse

Step By step

1. Navigate to Import section
2. Select ‘Existing Android project into workshop’ option under ‘Android’ section and click on ‘Next’
3. In the next screen browse and select the app folder, check the option ‘Copy project into workspace’.
4.App is imported successfully.

Hope this help you guys:)





Thursday, January 31, 2013

Android-Remote Debugging in chrome

You can debug mobile web sites with the full suite of Chrome Developer Tools running on a desktop browser that's connected to your phone via USB. View and change HTML code and styles until you get a bug-free page that behaves perfectly on the phone or tablet.

Know more: https://developers.google.com/chrome/mobile/docs/debugging 

Wednesday, January 2, 2013

Calling system settings from an Android app - GPS example



This tutorial shows how to redirect the user to a system settings screen asking to modify some settings the application depends on. We will make a specific example with Gps: The application can be used only if gps is available.
The android system gps setting screen can be called just like any other Activities:
  1. startActivityForResult(newIntent(android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS), 0);
To check GPS availability use the code code below: (the Activity must implement LocationListener)
  1. LocationManager locationManager = (LocationManager)getSystemService(LOCATION_SERVICE);
  2. locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L,1.0f, this);
  3. boolean isGPS = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
The example application will do the following:
1. On application start check if gps is available. If it is on the application can proceed.
2. If GPS is turned off, display a dialog asking the user to turn it on, and 2 buttons, one to go to GPS settings screen, and a cancel button to exit the application.
3. When the dialog is displayed we must store in a variable that the user was already asked once to turn on GPS
4. If the user leaves to the GPS option screen, it is not sure that he will turn on the GPS!
5. When the user returns to  application we recheck the GPS. If its available we can proceed, otherwise we close the application. (in order to check that it is a returm to the activity or is it its first start we check the variable we set in step 3)
So we will have the code in the applications starting Activity's on Resume method, where we will detect GPS availability, use a dialog to ask the user, an Intent to go to options screen, and a variable to indicate the state of the GPS turn on process. The code for this example application is available here. Turn off your GPS and try running it.

Friday, December 14, 2012

5 tips for converting iOS UI to Android


5 tips for converting iOS UI to Android

Making your app look like it belongs into an Android phone

Many companies are converting their iOS apps to Android nowadays. However, simple one-to-one conversion of the UI might cause problems to the potential users. 

I don't believe that inter-platform consistency between an app's different versions is as important than consistency between apps on a single platform. Not many users use multiple different phones at the same time. This post describes five simple rules how an iOS app can be made to fit into the growing Android app crowd.

1. Use top tabs
Google recommends that tabs in Android apps placed on top part of the UI instead of the very bottom.
a slide from Roman Nurik's GDD 2010 presentation


There's a very good reason for that recommendation. Take a look at the following pictures.Both of them features app called runtastic. Their Android port keeps the UI virtually unchanged and causes problems to big portion of Android users. Many Android phones have the 4 (or some 3) required Android buttons right on the screens bottom edge. Having your app's navigation immediately adjacent to the buttons will inevitably cause users to tap the navigation buttons from time to time.


Foursquare port does a good work moving the navigation tabs to higher and avoiding the same problems as runtastic has.

On the left: iOS version. On the right: Android version.


2. No back button in UI

All Android devices are required to have a back button and user's have used in using it. There's no need to add a back button to the UI. 
Don't do this:
A bit embarrassingly this example is
 from Android Central (an awesome source
for Android news) app. 

3. Use Android platform icons

Android platform provides icons for most common actions. One of them is share. Allrecepies uses an iOS icon (top right corner). There's a well established "share" icon for Android seen for example in the default gallery app. It is freely available to use in every app.

On the left: Wrong. On the right: Correct.


4. Use Android's intent APIs

One of the most powerful features of Android platform is the intent API. It allows apps to extend other apps' functionality by offering access to their features. Probably the most common way of doing this is the share function on various apps. An app can chose to share text, URL, image etc. Other apps can then register to listen to intents that they can handle. 

Apps should not implement their own interface for sharing through Facebook, twitter etc. If the app just let's the Android handle the share intent user can use their twitter etc app of choice. This way is much more convenient to users.

On the left: Wrong. On the right: Correct.


5. Consider using Action Bar

Action bar has become a single most easily identifiable feature in Android apps. Using it will instantly brand the app as an Android app. Users are used to the concept and it can improve app's usability. However, as always UI components should only be used if it makes sense.

Evernote uses Action Bar
pattern successfully

Conclusion

Simple one-to-one conversion from iOS design is usually not enough to create good user experience. However, the changed required might not require too huge amount of effort and will be rewarded by much better user satisfaction.