Rectangle 27 4

You should implement an LRU cache manager when dealing with bitmap

Use a tier library like Universal Image Loader :

Now when dealing with images and most of the time with bitmap I use Glide which let you configure a Glide Module and a LRUCache

bitmap - How to solve java.lang.OutOfMemoryError trouble in Android - ...

android bitmap out-of-memory bitmapfactory setbackground
Rectangle 27 7

There's a simpler way to implement @jglouie 's solution. Basically, if you use a SSLContext and initialize it with null for the trust manager parameter, you should get a SSL context using the default trust manager. Note that this is not documented in the Android documentation, but the Java documentation for SSLContext.init says

Either of the first two parameters may be null in which case the installed security providers will be searched for the highest priority implementation of the appropriate factory.

Here's what the code would look like:

// This can be any protocol supported by your target devices.
// For example "TLSv1.2" is supported by the latest versions of Android
final String SSL_PROTOCOL = "TLS";

try {               
   sslContext = SSLContext.getInstance(SSL_PROTOCOL);

   // Initialize the context with your key manager and the default trust manager 
   // and randomness source
   sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
} catch (NoSuchAlgorithmException e) {
   Log.e(TAG, "Specified SSL protocol not supported! Protocol=" + SSL_PROTOCOL);
   e.printStackTrace();
} catch (KeyManagementException e) {
   Log.e(TAG, "Error setting up the SSL context!");
   e.printStackTrace();
}

// Get the socket factory
socketFactory = sslContext.getSocketFactory();

I remember reading this while I was searching for the solution two years ago. I'm pretty sure that under the particular flavor of Android at the time it didn't work correctly when passed null, but I agree it should have and that it is a better solution.

java - HTTPS connection with client certificate in an android app - St...

java android ssl https certificate
Rectangle 27 7

There's a simpler way to implement @jglouie 's solution. Basically, if you use a SSLContext and initialize it with null for the trust manager parameter, you should get a SSL context using the default trust manager. Note that this is not documented in the Android documentation, but the Java documentation for SSLContext.init says

Either of the first two parameters may be null in which case the installed security providers will be searched for the highest priority implementation of the appropriate factory.

Here's what the code would look like:

// This can be any protocol supported by your target devices.
// For example "TLSv1.2" is supported by the latest versions of Android
final String SSL_PROTOCOL = "TLS";

try {               
   sslContext = SSLContext.getInstance(SSL_PROTOCOL);

   // Initialize the context with your key manager and the default trust manager 
   // and randomness source
   sslContext.init(keyManagerFactory.getKeyManagers(), null, null);
} catch (NoSuchAlgorithmException e) {
   Log.e(TAG, "Specified SSL protocol not supported! Protocol=" + SSL_PROTOCOL);
   e.printStackTrace();
} catch (KeyManagementException e) {
   Log.e(TAG, "Error setting up the SSL context!");
   e.printStackTrace();
}

// Get the socket factory
socketFactory = sslContext.getSocketFactory();

I remember reading this while I was searching for the solution two years ago. I'm pretty sure that under the particular flavor of Android at the time it didn't work correctly when passed null, but I agree it should have and that it is a better solution.

java - HTTPS connection with client certificate in an android app - St...

java android ssl https certificate
Rectangle 27 93

We had to implement exactly that same behaviour that you describe for an app recently. The screens and overall flow of the application were already defined so we had to stick with it (it's an iOS app clone...). Luckily, we managed to get rid of the on-screen back buttons :)

We hacked the solution using a mixture of TabActivity, FragmentActivities (we were using the support library for fragments) and Fragments. In retrospective, I'm pretty sure it wasn't the best architecture decision, but we managed to get the thing working. If I had to do it again, I'd probably try to do a more activity-based solution (no fragments), or try and have only one Activity for the tabs and let all the rest be views (which I find are much more reusable than activities overall).

So the requirements were to have some tabs and nestable screens in each tab:

tab 1
  screen 1 -> screen 2 -> screen 3
tab 2
  screen 4
tab 3
  screen 5 -> 6

So say: user starts in tab 1, navigates from screen 1 to screen 2 then to screen 3, he then switches to tab 3 and navigates from screen 4 to 6; if the switched back to tab 1, he should see screen 3 again and if he pressed Back he should return to screen 2; Back again and he is in screen 1; switch to tab 3 and he's in screen 6 again.

The main Activity in the application is MainTabActivity, which extends TabActivity. Each tab is associated with an activity, lets say ActivityInTab1, 2 and 3. And then each screen will be a fragment:

MainTabActivity
  ActivityInTab1
    Fragment1 -> Fragment2 -> Fragment3
  ActivityInTab2
    Fragment4
  ActivityInTab3
    Fragment5 -> Fragment6

Each ActivityInTab holds only one fragment at a time, and knows how to replace one fragment for another one (pretty much the same as an ActvityGroup). The cool thing is that it's quite easy to mantain separate back stacks for each tab this way.

The functionality for each ActivityInTab was quite the same: know how to navigate from one fragment to another and maintain a back stack, so we put that in a base class. Let's call it simply ActivityInTab:

abstract class ActivityInTab extends FragmentActivity { // FragmentActivity is just Activity for the support library.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_in_tab);
    }

    /**
     * Navigates to a new fragment, which is added in the fragment container
     * view.
     * 
     * @param newFragment
     */
    protected void navigateTo(Fragment newFragment) {
        FragmentManager manager = getSupportFragmentManager();
        FragmentTransaction ft = manager.beginTransaction();

        ft.replace(R.id.content, newFragment);

        // Add this transaction to the back stack, so when the user presses back,
        // it rollbacks.
        ft.addToBackStack(null);
        ft.commit();
    }

}
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/content"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:isScrollContainer="true">
</RelativeLayout>

As you can see, the view layout for each tab was the same. That's because it's just a FrameLayout called content that will hold each fragment. The fragments are the ones that have each screen's view.

Just for the bonus points, we also added some little code to show a confirm dialog when the user presses Back and there are no more fragments to go back to:

// In ActivityInTab.java...
@Override
public void onBackPressed() {
    FragmentManager manager = getSupportFragmentManager();
    if (manager.getBackStackEntryCount() > 0) {
        // If there are back-stack entries, leave the FragmentActivity
        // implementation take care of them.
        super.onBackPressed();
    } else {
        // Otherwise, ask user if he wants to leave :)
        showExitDialog();
    }
}

That's pretty much the setup. As you can see, each FragmentActivity (or just simply Activity in Android >3) is taking care of all the back-stacking with it's own FragmentManager.

public class ActivityInTab1 extends ActivityInTab {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        navigateTo(new Fragment1());
    }
}

Then, if a fragment needs to navigate to another fragment, it has to do a little nasty casting... but it's not that bad:

// In Fragment1.java for example...
// Need to navigate to Fragment2.
((ActivityIntab) getActivity()).navigateTo(new Fragment2());

So that's pretty much it. I'm pretty sure this is not a very canonical (and mostly sure not very good) solution, so I'd like to ask seasoned Android developers what would be a better approach to acheive this functionality, and if this is not "how it's done" in Android, I'd appreciate if you could point me to some link or material that explains which is the Android way to approach this (tabs, nested screens in tabs, etc). Feel free to tear apart this answer in the comments :)

As a sign that this solution is not very good is that recently I had to add some navigation functionality to the application. Some bizarre button that should take the user from one tab into another and into a nested screen. Doing that programmatically was a pain in the butt, because of who-knows-who problems and dealing with when are fragments and activities actually instantiated and initialized. I think it would have been much easier if those screens and tabs were all just Views really.

Finally, if you need to survive orientation changes, it's important that your fragments are created using setArguments/getArguments. If you set instance variables in your fragments' constructors you'll be screwed. But fortunately that's really easy to fix: just save everything in setArguments in the constructor and then retrieve those things with getArguments in onCreate to use them.

Great answer but I think very few will see this. I choosed exactly the same path (as you can see from conversation in previous answer) and I'm not happy with it just like you. I think Google really screwed up with this fragments since this API doesn't cover major use cases. Another issue you may run into is impossibility to embed fragment into another fragment.

Thanks for the comment boulder. Yeah, I couldn't agree more about the fragments API. I have already run into the problem of nested fragments (that's why we went for the "replace one fragment with another one" approach hehe).

I have implemented this via ALL activities. I didn't like what I got and I'm going to try Fragments. That's the opposite of your experience! There's a lot of implementation with Activities to handle the lifecycle of child views in each tab and also to implement your own back button. Also, you can't just keep a reference to all views or you will blow up memory. I hope Fragments will: 1) Support the lifecycle of the Fragments with clear separation of memory and 2) help implement the back button functionality Plus, if you use fragments for this process won't it be easier to run on Tablets?

What happens when the user switches tabs? Does the Fragment backstack get deleted? How to make sure the backstack remains?

@gregm If you go 1 tab <-> 1 activity like I did, the backstack for each tab will remain when tabs are switched because the activities are actually kept alive; they are only paused and resumed. I don't know if there is a way to make the activities be destroyed and re-created when tabs are switched in a TabActivity. However, if you make the fragments inside the activities be replaced like I suggested, they are destroyed (and re-created when the backstack is popped). So you will have at most one fragment alive per tab at any time.

Separate Back Stack for each tab in Android using Fragments - Stack Ov...

android tabs android-fragments
Rectangle 27 1

A couple of things are wrong there.

1- You dont have to create the marker as before, just adding 'MyItem' to the cluster manager is enough.

2- The marker's title, snippet, position and any data you want to show should be inside of your 'MyItem' class.

public class MyItem implements ClusterItem{
private final LatLng position;
private final String status;
private final String name;
private final String email;

public MyItem(LatLng position2, String status2, String name2, String email2) {

    position = position2;
    status = status2;
    name = name2;
    email = email2;

}

@Override
public LatLng getPosition() {
    return position;
}
public String getStatus() {
    return status;
}
public String getName() {
    return name;
}
public String getEmail() {
    return email;
}
}

Then in you activity create the items like

clusterManager.addItem(new MyItem(......));

And finally in the class where you extend DefaultClusterRenderer< MyItem >

@Override
    protected void onBeforeClusterItemRendered(MyItem item, MarkerOptions markerOptions) {
        super.onBeforeClusterItemRendered(item, markerOptions);

markerOptions.position(item.getPosition()).title(item.getName()).snippet(item.getStatus);

}

and you would get the same as before.

If you want to create a custom info window it gets a little bit more complicated.

How to implement InfoWindow with android map utils library in google m...

android google-maps google-maps-android-api-2
Rectangle 27 8

Go to windows. Android sdk manager. Scroll down choose google play services under extras and install

Copy the google-play services_lib library project to your workspace. The library project can be found under the following path.

<android-sdk-folder>/extras/google/google_play_services/libproject/google-play-services_lib library project .

Click File > Import, select Android > Existing Android Code into Workspace, and browse the workspace import the library project.

To check if its a library project. Right click got properties choose android. You see Is Library checked as below.

Next refer the library project in your android map project.

Right click on your android map project goto properties. choose android. click add browse the library project and click add and apply.

Make sure your api is 12 and above. If not you should use support fragment which requires support library.

My main problem is i cannot download the google play service lib

code.google.com/p/android/issues/detail?id=41231. Check the solutions in the link. If nothing works reinstall eclipse and download fresh copy of android sdk.stackoverflow.com/questions/3808167/. search on stackoverflow. lots of similar posts

Add Google Maps to Android app - Stack Overflow

android google-maps android-maps-v2
Rectangle 27 48

Here is another approach. It will work with any layout manager.

  • In onBindViewHolder check the position if last and call load()
  • Override the load() function while creating the adapter object in your activity or fragment.
  • In the overided load function implement your loadmore call
public abstract class MyAdapter extends RecyclerView.Adapter<ViewHolder>{

        @Override
        public void onBindViewHolder(ViewHolder holder, int position) {
            //check for last item
            if ((position >= getItemCount() - 1))
                load();
        }

        public abstract void load();
}
public class MainActivity extends AppCompatActivity {
    List<Items> items;
    MyAdapter adapter;

   @Override
    protected void onCreate(Bundle savedInstanceState) {
    ...
    adapter=new MyAdapter(items){
            @Override
            public void load() {
                //implement your load more here
                Item lastItem=items.get(items.size()-1);
                loadMore();
            }
        };
   }
}

Like the solution, you don't have to make your adapter abstract, instead you can create an interface in your adapter and make your activity implement it keeping it flexible and elegant, ex: ItemDisplayListener=>onItemDisplayed(int position). This way you can load at any position: at N, N-1, N-2..

@mcwise add a boolean finished=false; when you reach the end make finished=true.. change the current if condition to if ((position >= getItemCount() - 1) && (!finished))

This should be marked as the correct answer. This is elegant and simple.

@mcwise it'd only endlessly call if the user actively scrolls away and back to the last item. onBindViewHolder is only called once each time the view enters the screen and would not constantly call it.

android - How to implement endless list with RecyclerView? - Stack Ove...

android listview android-recyclerview material-design onscrolllistener
Rectangle 27 7

This can be done using ShareGPS App available in Google Play Market and Franson GPSgate Client. You will have to redirect the android GPS NMEA signal to COM ports using these tools. In addition you will require to download AndroidSDK manager.

How to get GPS data from Android phone? - Stack Overflow

android gps gpsd
Rectangle 27 15

In the Android SDK Manager, you must install "Google APIs (x86 System Image)" under "Android 4.4.2 (API 19)". Quit Eclipse and restart it.

Then create a new android virtual device in AVD manager and choose "Google APIs x86 (Google Inc.) - API Level 19" as target. Check "Use Host GPU" to ensure the drawing of the map will be accelerated.

That's it, this new emulator will have Play Services preinstalled and it will run faster because it's a x86 image.

Any idea how to get an emulator with Play installed using the ADK? It should be possible, but I do not see it....

android - This app won't run unless you update Google Play services er...

android google-maps android-emulator google-play google-play-services
Rectangle 27 14

In the Android SDK Manager, you must install "Google APIs (x86 System Image)" under "Android 4.4.2 (API 19)". Quit Eclipse and restart it.

Then create a new android virtual device in AVD manager and choose "Google APIs x86 (Google Inc.) - API Level 19" as target. Check "Use Host GPU" to ensure the drawing of the map will be accelerated.

That's it, this new emulator will have Play Services preinstalled and it will run faster because it's a x86 image.

Any idea how to get an emulator with Play installed using the ADK? It should be possible, but I do not see it....

android - This app won't run unless you update Google Play services er...

android google-maps android-emulator google-play google-play-services
Rectangle 27 1

I have used the fused location provider API's in our project and it's was really helpful to improve battery usage.Earlier We were using Android's Location framework APi's .

Please read below article which I have prepared ,you can refer the information to implement it in your project.

In simple words, its the best way to get location data in Android platform as of now.
GooglePlay Services provide many location APis to get the location data(e.g. Users current location or you can say devices last known location).

The Fused Location Provider is one of the location APIs in Google Play services.
Prerequisite is that:
1-        Google Play services sdk is used as library project(and also Google PlayService is properly installed in your device)
Download and install the Google Play services component from  the SDK Manager and add the library to your project.
Import GooglePlayServices lib from android google-play-services_lib in  your development  project as  Library project.
2-      You should have an actual device as this APi wont work in Emulator.

The Fused Location Provider intelligently manages the underlying location technology (GPS/Wi-Fi/Network providers connection) and gives us the best location according to our needs.

Why to use
============= 
We could choose one of the location providers (network or GPS) and request location updates or set up proximity alert. But there were two main issues with this approach:
1. In case we need to define precise location, we had to switch between network and GPS location providers (as GPS doesnt work indoors).
2. Proximity alerts were used to notify a user about proximity to a location, and this took its toll on the battery life.

Benefits
 ==========
1. Simple APIs: Lets us specify high-level needs like high accuracy or low power, instead of having to worry about location providers.
2. Battery efficient: Minimizes out apps use of power. Based on all incoming location requests and available sensors, fused location provider chooses the most efficient way to meet those needs.

Steps to use this Api:
 =====================
1-      Declare the location related permission in the manifest file.

<uses-permission android:name="android.permission.ACCESS_COURSE_LOCATION"/>
  Or
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>


2. Implement related interfaces and callbacks.

  Before we request location updates, we must first implement the interfaces that Location Services uses to communicate connection status to our app:
2.1 com.google.android.gms.common.GooglePlayServicesClient.ConnectionCallbacks: Specifies methods that Location Services calls when a location client is connected or disconnected.
2.2
com.google.android.gms.common.GooglePlayServicesClient.OnConnectionFailedListener
3 Connect to Google Play Services

Connecting LocationClient to Google api.To do this , create a LocationClient object (its actually instance of GoogleApiClient object)  as below:

mLocationClient = new GoogleApiClient.Builder(getApplicationContext())
                                                 .addApi(LocationServices.API).addConnectionCallbacks(this)
                                                 .addOnConnectionFailedListener(this).build();

and then call connect() :
mLocationClient.connect();

4- Create an instance of FusedLocationProviderApi by using LocationServices class as below:

private FusedLocationProviderApi fusedLocationProviderApi = LocationServices.FusedLocationApi;

5- Retrieve the current location

 Inside onConnected(Bundle bundle){

Location currentLocation = fusedLocationProviderApi                                  .getLastLocation(mLocationClient);
                 if (mCurrentLocation != null) {
                                 Log.d(TAG, "last location =" +           mCurrentLocation.getLatitude()
                                                                 + " - " + mCurrentLocation.getLongitude());
 }              
 }

6-  Receive periodic location updates

 Create and setup LocationRequest object:
mLocationRequest = new LocationRequest();

private void setLocationParameter() {
                 // Set the update interval
                 mLocationRequest.setInterval(Constants.SECONDS_TO_UP);
                 // Use high accuracy
                 mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
                 // Set the interval ceiling to one minute
                 mLocationRequest.setFastestInterval(Constants.SECONDS_TO_UP);
                 // Set the distance to 10 meters.
                 mLocationRequest.setSmallestDisplacement(Constants.METERS_TO_UP);
   }


6- Request for periodic Location updates: To get periodic location updates from Location Services, we send a request using a location client.

LocationListener listener =  new LocationListener() {
           @Override
   public void onLocationChanged(Location location) {    
                                 Utils.locationUpdates = Utils.locationUpdates + 1;
                                 if (Utils.locationUpdates == 1) {
                                                 mLocationRequest
                                                                                 .setPriority(LocationRequest.PRIORITY_LOW_POWER);
LocationServices.FusedLocationApi.requestLocationUpdates(
                                                 mLocationClient, mLocationRequest, listener);

                                                    }
                 }
          }
       };

We analyzed and finally thought of using Android SDK provided location manager to get the location information. Even if u use the Google play services to get the location information the drawbacks are you can not support most of end user this is because most of the device is not having google play store installed. And another one is the accuracy is not that much good when compared with location api.

Hi Vignesh, Yes ,the device should have Google PlayStore installed on the device. But I am not sure if using Fused Location Provider is less accurate than using Location manager API's.How would you confirm this point?

No I have plotted both the results. The Location Manager points are getting plotted in the road path. But Fused Api points are slightly away from road path.

If you are using location manager then you have to define your own logic which will impact the battery. We have defined an logic such away that the logic consumes only less power.

gps - Android Location Update Clarification - Stack Overflow

android gps location
Rectangle 27 2

The Samsung watch communicates with the phone over Bluetooth. Only ONE such radio link can be established at the time, and in case of the Samsung product that connection is in use by the existing firmware that connects to a peer Samsung "Gear Manager" app on the phone side. For now that solution monopolizes use of the established Bluetooh session and implements and controls what can occur over the link. Gear Manager acts as a server that responds to and serves the set of apps that it supports on the watch side. Gear Manager checks on what phone model it runs and will at time of writing only allow to run on select Samsung phone models. Multiple apps on the watch can register with an arbiter mechanism in watch firmware to share the link (API not disclosed) but the kind of traffic that is allowed to occur is controlled by the firmware in cooperation with the phone side Gear Manager app. Typically a developer could come up with the idea "I want my own app on the watch to communicate with MY own developed app on the phone". For now one can only wait for what kind of Gear SDK Samsung will release for public use. It could be restrictive (my assuption) or actually provide for general sharing of the Bluetooth session to allow unleashing of the fantastic combined possibilities with camera,mic,audio,display,internet to the imagination of third parties. The future will tell. For now Samsung run an invite-only scheme where selected ISVs develop apps and these are the only ones with access to expanding the existing set of apps and producing new Gear apps that Samsung approve for entry into their app store.

+1 for your answer, thanks but that is not the answer.

android - Internet Connection over Samsung Galaxy Gear - Stack Overflo...

android samsung-mobile samsung-mobile-sdk samsung-galaxy-gear
Rectangle 27 6

|-root
  |-app
     |-assets
     |-static
     |-templates
     |settings.py
     |urls.py
     |views.py
     |wsgi.py
  |manage.py
  |bower.json
  |.bowerrc
.bowerrc
{
    "directory": "app/static/bower_components"
}
<script src="{{ STATIC_URL }}bower_components/angular/angular.js"></script>
settings.py
STATIC_URL = '/static/'
STATIC_ROOT = join(BASE_DIR, 'assets')
STATICFILES_DIRS = [join(BASE_DIR, 'static')]
urls.py
urlpatterns += patterns('',
                        (r'^static/(?P<path>.*)$', 'django.views.static.serve',
                         {'document_root': settings.STATIC_ROOT}),)

@juho has the proper way of using django-bower. Your use of {{ STATIC_URL }} & lack of BOWER_INSTALLED_APPS almost completely defeats the purpose of using django-bower.

@jazzpi Yes, I totally jumped the gun on my previous comment. I saw the title my django bower project and assumed they were referring to the django-bower package. At the time, It did not occur to me that they simply meant Django + bower... duh

python - How to use bower package manager in Django App? - Stack Overf...

python django bower
Rectangle 27 191

Adding this as an answer since it seemed to help quite a few people.

Create a new directory

Add a new package

  • Locate your sdk location and go to "sdk\extras\google\play_billing". Default location for the sdk is "C:\Program Files (x86)\Android\android-sdk". If you custom changed it, then you will have to figure out the location through the sdk manager.
  • Copy 'IInAppBillingService.aidl' into the package created above. In the end, it should look similar to the image below.
  • Rebuild project and it should be good to go.

Note: Make sure you include the necessary import if your reference isn't working

import com.android.vending.billing.IInAppBillingService;

Just to be clear: read this thoroughly! I didn't...to emphasize again: It IS a good addition...PUT THE com.android.vending.billing IN THE NEW 'main/aidl' directory!

After I did this, the references to IInAppBillingService in my code were still highlighted as errors, but after rebuilding the app, the class was recognized.

Spent 20 minutes trying to solve this problem until I came to your answer. Then I tried to upvote it to get the error "You last voted on this answer..." I guess some people never learn :)

works a dream :)

how can I add the aidl file to Android studio (from the in-app billing...

android android-studio gradle android-gradle aidl
Rectangle 27 2

// the listener to listen to the locations
private LocationListener listener = null;
// a location manager
private LocationManager lm  = null;
// locations instances to GPS and NETWORk
private Location myLocationGPS, myLocationNetwork;

// instantiates fields
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
myLocationNetwork = lm.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
myLocationGPS = lm.getLastKnownLocation(LocationManager.GPS_PROVIDER);
listener = new myLocationListener();

// the listener that gonna notify the activity about location changes
public class myLocationListener implements LocationListener {
    @Override
    public void onLocationChanged(Location location) {
        // "location" is the RECEIVED locations and its here that you should proccess it

        // check if the incoming position has been received from GPS or network
        if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            lm.removeUpdates(this);
        } else {
            lm.removeUpdates(listener);
        }
    }
    @Override
    public void onProviderDisabled(String provider) {
        lm.removeUpdates(this);
        lm.removeUpdates(listener);         
    }
    @Override
    public void onProviderEnabled(String provider) {
    }
    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
    }
}

As you can see, there's not so much trickys. At the time that you instantiates the listener, you should see the GPS icon on the top of your Android device. Also, whenever your position changes (i.e. as you walk with your device), the OnLocationChanged method will be called.

Also, it is interesting to say that if you want to just get you locations, there are several ways to do it, all of then with different speeds of return and different acurracies. Please, check also GoogleGLM (a request to http://www.google.com/glm/mmap, that returns a json encoded strign with your position) services, triangulations and location by network. In the above snippets I've showed how to get location by either GPS and network. Hope that it has been of some help... :)

if (lm.isProviderEnabled(LocationManager.GPS_PROVIDER)  && (isNetOrGPs%4 == 0)) {
isNetOrGPs%4 == 0

You can just ignore it. Sorry for that: I've copy/paste the snippet from my project and missed this little thing. :)

The most important part is to override OnLocationChanged. You can put a Toast.makeText method to toast your position as feedback. ;)

Please see my longer version of the code ^ (link in updated question and also in comment above (PasteBin link)). I will be trying the code on a different device tommorow..lets hope it works fine. :|

If you are getting hard-times to make this implementation then please, email me: hama.marcelo.ti@gmail.com. I can send you a little runnable example with location fetch.

android - How to get User's Current GPS Location From Google Maps App?...

android google-maps android-maps google-maps-mobile
Rectangle 27 2

Since GTM still doesn't support AdWords call tracking skript from the box, it's easy to do yor own implementation, just add it as Custom HTML Tag and be sure to check Support document.write

This is working fine. I was worried about putting script in between head tags. However, it is not bothering me, GTM is handling it well.

javascript - Google tag manager: Is it possible to put CUSTOM HTML cod...

javascript html google-tag-manager google-adwords
Rectangle 27 2

If you're afraid of the bower.json being included, the collectstatic command has an --ignore option that you can use to exclude whatever you want.

python - How to use bower package manager in Django App? - Stack Overf...

python django bower
Rectangle 27 2

You should list the installed bower packages in the settings.py using key BOWER_INSTALLED_APPS.

Now, in your development server, using the {% static %} templatetag finds them from their installed directory. In production server, the collectstatic will collect the correct static files from the installed directory (bower_components).

python - How to use bower package manager in Django App? - Stack Overf...

python django bower
Rectangle 27 2

There is no recommended way - it depends on your project. If you are using bower, node for more than the django project, it might make sense to place it in your project root (above django) so that it may be reused elsewhere.

If it's purely for django's static files, then it might make sense to place it in a src/ outside of the staticfiles system which builds to the static directory which is exported via collectstatic.

python - How to use bower package manager in Django App? - Stack Overf...

python django bower
Rectangle 27 2

public class LocationTracker 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


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

/**
 * Function to get latitude
 * */
public double getLatitude(){
    if(location != null){
        latitude = location.getLatitude();
        Log.d("lat", latitude+"");
    }

    // return latitude
    return latitude;
}

/**
 * Function to get longitude
 * */
public double getLongitude(){
    if(location != null){
        longitude = location.getLongitude();
        Log.d("long :", longitude+"");
    }

    // 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 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;
}

and in your activity create the object of it and fetch location like as follows ....

LocationTracker locationTracker = new LocationTracker(StreamActivity.this);
if (!locationTracker.canGetLocation()) {
            locationTracker.showSettingsAlert();
        } else {

            latitude = locationTracker.getLatitude;
            longitude = locationTracker.getLongitude;


            locationTracker.stopUsingGPS();

        }

and add all the permissions in manifest file ....

<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

It keeps throwing this source not found exception. Earlier it was throwing this exception while executing "requestlocationupdates()" and now after implementing the code provided by you, I am getting the same exception while "isProviderEnabled()" is getting executed. What could be the reason behind it? Am I missing out some libraries or something?? @Sachin

have you enable the location service from your device ???

hey you go through above link . Check this demo is working in your device or not . It is successfully working for me . test it on device not on emulator @zstart

geolocation - Getting "Source not found" error while trying to detect ...

android geolocation latitude-longitude