android - Mock location not working on Google map


I have used code from this. I have changed it a bit. Below is my code snippet. The problem is Google Map is not showing proper location which i have mocked.

public class MockGpsProviderActivity extends Activity implements LocationListener {
public static final String LOG_TAG = "MockGpsProviderActivity";
private static final String MOCK_GPS_PROVIDER_INDEX = "GpsMockProviderIndex";

private MockGpsProvider mMockGpsProviderTask = null;
private Integer mMockGpsProviderIndex = 0;

/** Called when the activity is first created. */
 * (non-Javadoc)
 * @see
public void onCreate(Bundle savedInstanceState) {

    /** Use saved instance state if necessary. */
    if (savedInstanceState instanceof Bundle) {
        /** Let's find out where we were. */
        mMockGpsProviderIndex = savedInstanceState.getInt(MOCK_GPS_PROVIDER_INDEX, 0);

    /** Setup GPS. */
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);

    // if(locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
    // // use real GPS provider if enabled on the device
    // locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
    // }
    // else if(!locationManager.isProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER)) {
    // otherwise enable the mock GPS provider
    locationManager.addTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER, false, false, false, false, true, true, true, Criteria.POWER_LOW,
    locationManager.setTestProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER, true);
    locationManager.setTestProviderStatus(LocationManager.GPS_PROVIDER, LocationProvider.AVAILABLE, null, System.currentTimeMillis());

    // }

    if (locationManager.isProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER)) {
        locationManager.requestLocationUpdates(MockGpsProvider.GPS_MOCK_PROVIDER, 0, 0, this);

        /** Load mock GPS data from file and create mock GPS provider. */
        try {
            // create a list of Strings that can dynamically grow
            List<String> data = new ArrayList<String>();

             * read a CSV file containing WGS84 coordinates from the 'assets' folder (The website offers downloadable
             * tracks. Select a track and download it as a CSV file. Then add it to your assets folder.)
            InputStream is = getAssets().open("mock_gps_data.csv");
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));

            // add each line in the file to the list
            String line = null;
            while ((line = reader.readLine()) != null) {

            // convert to a simple array so we can pass it to the AsyncTask
            String[] coordinates = new String[data.size()];

            // create new AsyncTask and pass the list of GPS coordinates
            mMockGpsProviderTask = new MockGpsProvider();
        } catch (Exception e) {

public void onDestroy() {

    // stop the mock GPS provider by calling the 'cancel(true)' method
    try {
        mMockGpsProviderTask = null;
    } catch (Exception e) {

    // remove it from the location manager
    try {
        LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    } catch (Exception e) {

public void onSaveInstanceState(Bundle savedInstanceState) {
    // store where we are before closing the app, so we can skip to the location right away when restarting
    savedInstanceState.putInt(MOCK_GPS_PROVIDER_INDEX, mMockGpsProviderIndex);

public void onLocationChanged(Location location) {
    // show the received location in the view
    TextView view = (TextView) findViewById(;
    view.setText("index:" + mMockGpsProviderIndex + "\nlongitude:" + location.getLongitude() + "\nlatitude:" + location.getLatitude()
            + "\naltitude:" + location.getAltitude());

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

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

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

/** Define a mock GPS provider as an asynchronous task of this Activity. */
private class MockGpsProvider extends AsyncTask<String, Integer, Void> {
    public static final String LOG_TAG = "GpsMockProvider";
    public static final String GPS_MOCK_PROVIDER = LocationManager.GPS_PROVIDER;

    /** Keeps track of the currently processed coordinate. */
    public Integer index = 0;

    protected Void doInBackground(String... data) {
        // process data
        for (String str : data) {
            // skip data if needed (see the Activity's savedInstanceState functionality)
            if (index < mMockGpsProviderIndex) {

            // let UI Thread know which coordinate we are processing

            // retrieve data from the current line of text
            Double latitude = null;
            Double longitude = null;
            Double altitude = null;
            try {
                String[] parts = str.split(",");
                latitude = Double.valueOf(parts[0]);
                longitude = Double.valueOf(parts[1]);
                altitude = Double.valueOf(parts[2]);
            } catch (NullPointerException e) {
            } // no data available
            catch (Exception e) {
            } // empty or invalid line

            // translate to actual GPS location
            Location location = new Location(GPS_MOCK_PROVIDER);

            // show debug message in log
            Log.d(LOG_TAG, location.toString());

            // provide the new location
            LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
            locationManager.setTestProviderLocation(GPS_MOCK_PROVIDER, location);

            // sleep for a while before providing next location
            try {

                // gracefully handle Thread interruption (important!)
                if (Thread.currentThread().isInterrupted())
                    throw new InterruptedException("");
            } catch (InterruptedException e) {

            // keep track of processed locations

        return null;

    protected void onProgressUpdate(Integer... values) {
        Log.d(LOG_TAG, "onProgressUpdate():" + values[0]);
        mMockGpsProviderIndex = values[0];

4 Answers: 

Try adding:


I think you can call mock location also in your permissions (Manifest.xml), in order to work. Do you have that,in your permissions?

Because when I used it with this,it worked.

(Sorry I couldn't leave it as a comment because I don't have enough reputation)


Did you turn on Allow_Mock_Location in the setting of your physical device? It's under developer options.


Also add for your mock location location.setSpeed(5); speed more than 1, like 5 or 10


More Articles

rust - How do I move multiple values out of a boxed value without calling clone?

This question already has an answer here: How to bind multiple fields of a boxed struct without getting “use moved value” error? 2 answers

c++ - Boost.Asio SSL thread safety

Do I create one strand that all of my SSL sockets share, or one strand per SSL context (shared by any associated sockets)?Boost.Asio SSL documentation states this, but it doesn't mention contexts. I assume that this means I must use only one strand for everything, but I think this was written before

data structures - Is there any practical usage of Doubly Linked List, Queues and Stacks?

I've been coding for quite sometime now. And my work pertains to solving real-world business scenarios. However, I have not really come across any practical usage of some of the data structures like the Linked List, Queues and Stacks etc.Not even at the business framework level. Of course, there is

php - Using json_decode on cURL result

I have got the following code that retrieves data about a company.function getSSLPage($url) { $ch = curl_init(); curl_setopt($ch, CURLOPT_HEADER, false); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_SSLVERSION,1); curl_setopt($ch, CURLOPT_SSL_VERI

c - Bypass default rule for make

I'm trying to compile several .c files through assembler:%.S: %.c $(XCC) -S -o $@ $(XCFLAGS) -c $<%.o: %.S $(XCC) -o $@ $(XCFLAGS) -c $<test.a: test.o foo.o $(LD) -o $@ $^ $(XLDFLAGS) $(XCC) is a cross-compile tool.Actually, I see: cc -c -o test0.o test0.ccc -c -o f

php - Laravel openssl_private_encrypt(): key param is not a valid private key

I am trying to connect to Chef API with Laravel using PHP-Chef. I have tried to set up my chef config with the data that I got from knife.rb in .chef folder. I have setup client and a key according to the instructions from Knife.rb. But I get:openssl_private_encrypt(): key param is not a valid priva

parsing - Parse JQ output through external bash function?

I want to parse out data out of a log file which consist of JSON sting and I wonder if there's a way for me to use a bash function to perform any custom parsing instead of overloading jq command.Command:tail errors.log --follow | jq --raw-output '. | [.server_name, .server_port, .request_file] | @ts

Know of any setup tutorials for SQL Server Express and C#?

I'm a C# and MySQL developer, but I'm looking into Microsoft's SQL Server for a new project. I'm familiar with MySQL syntax and the .NET connector. Does anyone know of any decent tutorials that just cover the code to interact with SQL Server? No C# basics or SQL basics, just how to get the two tec

libgit2sharp: how to set multiple values with same key

how do I set multiple values for a config-key? Some sections supports multiple values:[remote "origin"] url = fetch = +refs/heads/master:refs/remotes/origin/master fetch = +refs/heads/qa/*:refs/remotes/origin/qa/*Something like this is not working in

r - split string at every character

I want to split every character in a string and output it as comma or tab separated characters:I need to use file_in and file_out since I have very many lines.inputTTTGGCTTTGTGCAATGG........outputT,T,T,G,G,CT,T,T,GT,G,C,A,A,T,G,GI have used this, but it prints every character vertically: /usr/bin/p