Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8432905
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T06:14:45+00:00 2026-06-10T06:14:45+00:00

How can I cancel a thread from another class fetching/refreshing location. I am able

  • 0

How can I cancel a thread from another class fetching/refreshing location. I am able to cancel a thread from within the same class. But I am unable to do this across classes. Declaring the GPSThread static did not help. Can anyone please guide?

Class1:

public class GPSListener {
    /* Other instantiation code */
    Dialog busyDialog1 = new Dialog("Refreshing Location...",
                                    new String [] { "Cancel" },
                                    new int [] { Dialog.CANCEL},
                                    Dialog.CANCEL,
                                    Bitmap.getPredefinedBitmap(Bitmap.HOURGLASS))
    {
        public void fieldChanged(Field field1, int context1)
        {
            GPSHandler.requestStop();
            busyDialog1.cancel();
        }
    };

    public String refreshCoordinates() {
        String test = "nothing";
        if (GPSHandler.isStopRequested())
        {
            GPSHandler.stopRequested = false;
            return null;
        }
        GPSHandler.getInstance().setListener(this);
        GPSHandler.getInstance().requestLocationUpdates();
        if (GPSHandler.isStopRequested())
        {
            GPSHandler.stopRequested = false;
            return null;
        }
        busyDialog1.setEscapeEnabled(false);
        busyDialog1.show();
        return test;
    }

    public void onLocationReceived(Coordinates location) {
        lblLatitude.setText(Double.toString(location.getLatitude()));
        lblLongitude.setText(Double.toString(location.getLongitude()));
        busyDialog1.cancel();
    }
}

Class 2:

public class GPSHandler {
    private GPSThread _gpsThread;
    private Coordinates _location;
    private boolean _gotLocation;
    private GPSListener _listener;

    /** this class will be a Singleton, as the device only has one GPS system */
    private static GPSHandler _instance;

    /** @return the Singleton instance of the GPSHandler */
    public static GPSHandler getInstance() {
        if (_instance == null) {
            _instance = new GPSHandler();
        }
        return _instance;
    }

    public static boolean stopRequested = false;
    public synchronized static void requestStop() {
        stopRequested = true;
    }
    public synchronized static boolean isStopRequested() {
        return stopRequested;
    }

    /** not publicly accessible ... use getInstance() */
    private GPSHandler() {
    }

    /** call this to trigger a new location fix */
    public void requestLocationUpdates() {
        if (_gpsThread == null || !_gpsThread.isAlive()) {
            _gpsThread = new GPSThread();
            _gpsThread.start();
        }
    }

    public void setListener(GPSListener listener) {
        // only supports one listener this way
        _listener = listener;
    }

    private void setLocation(final Coordinates value) {
        _location = value;
        if (value.getLatitude() != 0.0 || value.getLongitude() != 0.0) {
            _gotLocation = true;
            if (_listener != null) {
                // this assumes listeners are UI listeners, and want callbacks on the UI thread:
                UiApplication.getUiApplication().invokeLater(new Runnable() {
                    public void run() {
                        _listener.onLocationReceived(value);
                    }
                });
            }
        }
    }

    private class GPSThread extends Thread {
        private void getLocationFromGoogle() {
            try {
                int cellID = GPRSInfo.getCellInfo().getCellId();
                int lac = GPRSInfo.getCellInfo().getLAC();
                String urlString2 = "http://www.google.com/glm/mmap";

                // Open a connection to Google Maps API
                ConnectionFactory connFact = new ConnectionFactory();
                ConnectionDescriptor connDesc;
                connDesc = connFact.getConnection(urlString2);
                HttpConnection httpConn2;
                httpConn2 = (HttpConnection)connDesc.getConnection();
                httpConn2.setRequestMethod("POST");

                // Write some custom data to Google Maps API
                OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream();
                writeDataGoogleMaps(outputStream2, cellID, lac);

                // Get the response
                InputStream inputStream2 = httpConn2.openInputStream();//getInputStream();
                DataInputStream dataInputStream2 = new DataInputStream(inputStream2);

                // Interpret the response obtained
                dataInputStream2.readShort();
                dataInputStream2.readByte();
                final int code = dataInputStream2.readInt();

                UiApplication.getUiApplication().invokeLater(new Runnable() {
                    public void run() {
                        Dialog.alert(code + "");
                    }
                });
                if (code == 0) {
                    final double latitude = dataInputStream2.readInt() / 1000000D;
                    final double longitude = dataInputStream2.readInt() / 1000000D;
                    setLocation(new Coordinates(latitude, longitude, 0.0f));

                    UiApplication.getUiApplication().invokeLater(new Runnable() {
                        public void run() {
                            Dialog.alert(latitude+"-----"+longitude);
                        }
                    });

                    dataInputStream2.readInt();
                    dataInputStream2.readInt();
                    dataInputStream2.readUTF();
                } else {
                    System.out.println("Error obtaining Cell Id ");
                }
                outputStream2.close();
                inputStream2.close();
            } catch (Exception e) {
                System.out.println("Error: " + e.getMessage());
            }
        }

        private void tryGetLocationFromDevice() {
            _gotLocation = false;
            try {
                Criteria myCriteria = new Criteria();
                myCriteria.setCostAllowed(false);
                LocationProvider myLocationProvider = LocationProvider.getInstance(myCriteria);
                try {
                    Location myLocation = myLocationProvider.getLocation(300);
                    setLocation(myLocation.getQualifiedCoordinates());
                } catch ( InterruptedException iex ) {
                    System.out.println(iex.getMessage());
                } catch ( LocationException lex ) {
                    System.out.println(lex.getMessage());
                }
            } catch ( LocationException lex ) {
                System.out.println(lex.getMessage());
            }
            if (!_gotLocation) {
                getLocationFromGoogle();
            }
        }

        public void run() {
            int bbMapsHandle = CodeModuleManager.getModuleHandle("net_rim_bb_lbs"); // OS 4.5 - 6.0
            int bbMapsHandle60 = CodeModuleManager.getModuleHandle("net_rim_bb_maps"); // OS 6.0
            if (bbMapsHandle > 0 || bbMapsHandle60 > 0) {
                tryGetLocationFromDevice();
            } else {
                getLocationFromGoogle();
            }
        }
    }

    private void writeDataGoogleMaps(OutputStream out, int cellID, int lac) throws IOException {
        DataOutputStream dataOutputStream = new DataOutputStream(out);
        dataOutputStream.writeShort(21);
        dataOutputStream.writeLong(0);
        dataOutputStream.writeUTF("en");
        dataOutputStream.writeUTF("Android");
        dataOutputStream.writeUTF("1.0");
        dataOutputStream.writeUTF("Web");
        dataOutputStream.writeByte(27);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(3);
        dataOutputStream.writeUTF("");
        dataOutputStream.writeInt(cellID);
        dataOutputStream.writeInt(lac);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.writeInt(0);
        dataOutputStream.flush();
    }
} 
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T06:14:47+00:00Added an answer on June 10, 2026 at 6:14 am

    There’s two groups of changes you should make.

    Change the Stop Requested Flag

    First, remember that encapsulation is a good thing in Object-Oriented languages. The isStopRequested() method, or stopRequested variable of the GPSHandler should not be used outside of that class. Your UI’s GPSListener should not attempt to use either of those. I would change your GPSHandler to use this:

    private static boolean stopRequested = false;
    
    public synchronized static void requestStop() {
       stopRequested = true;
    }
    
    private synchronized static boolean isStopRequested() {
       return stopRequested;
    }
    

    Only requestStop() should be public. It looks like you made stopRequested public to allow the GPSListener to reset it. If it needs resetting, let the class that owns that variable do the resetting. For example, in GPSHandler:

       /** call this to trigger a new location fix */
       public void requestLocationUpdates() {
           if (_gpsThread == null || !_gpsThread.isAlive()) {
              // reset this stop flag:
              stopRequested = false;
              _gpsThread = new GPSThread();
              _gpsThread.start(); 
           }
       }
    

    requestLocationUpdates() is really the method that starts the thread, so it should be where stopRequested gets reset to false.

    Also, another reason that you should not make stopRequested public and allow other classes to use it is that this is not generally thread-safe. One of the reasons to wrap stopRequested with the requestStop() and isStopRequested() methods is to add thread-safety. There’s many ways to do that, but those two methods achieve thread-safety by being marked with the synchronized keyword.

    Change How/Where You Check the Flag

    After you make these fixes, you need to change where you check if a stop has been requested. You don’t really want to check isStopRequested() in the refreshCoordinates() method. That method involves almost no work. Even though it starts the process of getting a location fix, that only starts a thread, but the actual work of getting the location is done on a background thread (your GPSThread). If requestStop() is called, it’s very unlikely that it will be called in the middle of refreshCoordinates(), so that’s not where you should check it.

    Check isStopRequested() multiple times within the GPSHandler class’s methods tryGetLocationFromDevice() and getLocationFromGoogle(). Those are the methods that perform slow processing. Those are the ones you might want to interrupt in the middle. So, something like this:

         private void getLocationFromGoogle() {
             try { 
                int cellID = GPRSInfo.getCellInfo().getCellId(); 
                int lac = GPRSInfo.getCellInfo().getLAC(); 
    
                String urlString2 = "http://www.google.com/glm/mmap"; 
    
                if (isStopRequested()) return;
    
                // Open a connection to Google Maps API  
                ConnectionFactory connFact = new ConnectionFactory(); 
                ConnectionDescriptor connDesc; 
                connDesc = connFact.getConnection(urlString2); 
    
                HttpConnection httpConn2; 
                httpConn2 = (HttpConnection)connDesc.getConnection(); 
                httpConn2.setRequestMethod("POST"); 
    
                // Write some custom data to Google Maps API  
                OutputStream outputStream2 = httpConn2.openOutputStream();//getOutputStream(); 
                writeDataGoogleMaps(outputStream2, cellID, lac); 
    
                if (isStopRequested()) return;
    
                // Get the response   
                InputStream inputStream2 = httpConn2.openInputStream();//getInputStream(); 
                DataInputStream dataInputStream2 = new DataInputStream(inputStream2); 
    
                // Interpret the response obtained  
                dataInputStream2.readShort(); 
                dataInputStream2.readByte(); 
    
                if (isStopRequested()) return;
    
                final int code = dataInputStream2.readInt(); 
                UiApplication.getUiApplication().invokeLater(new Runnable() {
                   public void run() {
                      Dialog.alert(code + "");   
                   }
                });                        
    

    And in tryGetLocationFromDevice(), you could do this (make sure to add the member variable and new method below):

          private LocationProvider _locationProvider;  // must be a member variable!
    
          public void requestStop() {
             if (_locationProvider != null) {
                 // this will interrupt the _locationProvider.getLocation(300) call
                 _locationProvider.reset();
             }
          }
    
          private void tryGetLocationFromDevice() {
             _gotLocation = false;
             try {
                Criteria myCriteria = new Criteria(); 
                myCriteria.setCostAllowed(false); 
                _locationProvider = LocationProvider.getInstance(myCriteria); 
    
                try { 
                   Location myLocation = _locationProvider.getLocation(300); 
                   setLocation(myLocation.getQualifiedCoordinates()); 
                } catch ( InterruptedException iex ) { 
                   // this may be caught if stop requested!!!!
                   System.out.println(iex.getMessage());
                } catch ( LocationException lex ) { 
                   System.out.println(lex.getMessage());
                } 
             } catch ( LocationException lex ) { 
                System.out.println(lex.getMessage());
             }
    
             if (!_gotLocation && !isStopRequested()) { 
                getLocationFromGoogle();
             } 
          }
    

    Then, call the GPSThread.requestStop() method from the outer GPSHandler.requestStop() method:

    public synchronized static void requestStop() {
       stopRequested = true;
       if (_gpsThread != null) {
           _gpsThread.requestStop();
       }
    }
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

The JDBC java.sql.Statement class has a cancel() method. This can be called in another
I have a cancel button on a page. But this page can be opened
An app I'm working on can't meaningfully launch until it has a Location from
I need to use a popup window from within a sub thread. Looking around
I was using cancelRequest() from within my SyncAdapter, just before it exits its thread,
I need to send a piece of code from another thread (Excel Interop) to
I'm trying to figure out how I can listen to the Cancel button that
I have a modelless dialog that creates a thread, and if the cancel button
I've successfully connected to XMPP server (from android XMPP client), and I can send
All the functions mentioned in this block are library functions. How can I rectify

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.