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

  • Home
  • SEARCH
  • 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 8914989
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 15, 20262026-06-15T04:52:01+00:00 2026-06-15T04:52:01+00:00

I like to make services execute two task in a regular time, is it

  • 0

I like to make services execute two task in a regular time, is it possible? By the structure following, is it true? Actually I has tested it and it give me error…or I should embedded all task into a timer task??

Another question I like to ask is how could I get user’s username from Service? This is because I need user’s username to check and update something from the tasks.The user’s username can be obtained in login.java which authenticate user identity, but the Service has run before user access into the application, then how could I get user’s username from Service?

When MyService.class is run, a Timer.class is pop-up suddenly and error given..

the result when runs over the codes

The error logcat:

 11-29 03:21:44.102: E/AndroidRuntime(15496): FATAL EXCEPTION: Timer-0
 11-29 03:21:44.102: E/AndroidRuntime(15496): java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
 11-29 03:21:44.102: E/AndroidRuntime(15496):   at android.os.Handler.<init>(Handler.java:121)
 11-29 03:21:44.102: E/AndroidRuntime(15496):   at android.location.LocationManager$ListenerTransport$1.<init>(LocationManager.java:173)
 11-29 03:21:44.102: E/AndroidRuntime(15496):   at android.location.LocationManager$ListenerTransport.<init>(LocationManager.java:173)
 11-29 03:21:44.102: E/AndroidRuntime(15496):   at android.location.LocationManager._requestLocationUpdates(LocationManager.java:579)
 11-29 03:21:44.102: E/AndroidRuntime(15496):   at android.location.LocationManager.requestLocationUpdates(LocationManager.java:446)
 11-29 03:21:44.102: E/AndroidRuntime(15496):   at com.example.android.project.MyService$2.run(MyService.java:107)
 11-29 03:21:44.102: E/AndroidRuntime(15496):   at java.util.Timer$TimerImpl.run(Timer.java:284)

Thanks in advance..

here is my code:

public class MyService extends Service{

int counter = 0;
static final int UPDATE_INTERVAL = 15000;
private Timer timer = new Timer();
DefaultHttpClient httpclient;
HttpPost httppost;
String line,result;
HttpResponse response;
InputStream is;
BufferedReader reader;
StringBuilder sb;
final static String MY_ACTION = "MY_ACTION";
LocationManager lm;
LocationListener locationListener;

@Override
public IBinder onBind(Intent arg0) {
    // TODO Auto-generated method stub
    return null;
}


public int onStartCommand(Intent intent, int flags, int startId){
    doSomethingRepeatedly();
    doUpdateLocation();
    return START_STICKY;        
}

private void doSomethingRepeatedly(){
    timer.scheduleAtFixedRate(new TimerTask(){
        public void run(){
        //  Log.d("MyService", String.valueOf(++counter));
            try{
             httpclient = new DefaultHttpClient();
                httppost = new HttpPost("http://www.kryptoquest.com/testing/checking.php");
                response = httpclient.execute(httppost);
                is = response.getEntity().getContent();
        }catch(Exception e){
            Log.e("log_tag", "Error:"+e.toString());
        }

        //convert response to string
        try{
                    reader = new BufferedReader(new InputStreamReader(is,"iso-8859-1"),8);
                sb = new StringBuilder();
                line = null;
                while ((line = reader.readLine()) != null) {

                        sb.append(line + "\n");

                }
                Log.d("test",sb.toString());
                is.close();

                result = sb.toString();

             Intent intent = new Intent();
             intent.setAction(MY_ACTION);

             intent.putExtra("DATAPASSED", result);

             sendBroadcast(intent);

        }catch(Exception e){
                Log.e("log_tag", "Error converting result "+e.toString());
        }
        }
    },10000,UPDATE_INTERVAL);
}

private void doUpdateLocation(){
    timer.scheduleAtFixedRate(new TimerTask(){
        public void run(){
         lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
            locationListener = new MyLocationListener();
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 60000, 1000, locationListener);   
        }
    },10000,UPDATE_INTERVAL);
}


 private class MyLocationListener implements LocationListener{

        @Override
        public void onLocationChanged(Location arg0) {
            if(arg0!=null){
                final String lat = String.valueOf(arg0.getLatitude());
                final String lon = String.valueOf(arg0.getLongitude());

                new Thread(){
                    public void run(){
                        try{ 
                            DefaultHttpClient httpclient = new DefaultHttpClient();
                            HttpPost httppost = new HttpPost("http://www.kryptoquest.com/tracker/getLocation.php");
                            ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
                            nameValuePairs.add(new BasicNameValuePair("Latitude", lat));
                            nameValuePairs.add(new BasicNameValuePair("Longitude", lon));
                            Log.d("Latitude",lat);
                            Log.d("Longitude",lon);
                            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
                            httpclient.execute(httppost);
                        }catch(Exception e){
                            Log.e("log_tag", "Error:"+e.toString());
                        }   
                    }
                }.start();

                lm.removeUpdates(locationListener);
            }       
        }

        @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

        }

    }

public void onDestroy(){
    super.onDestroy();

    if(timer != null){
        timer.cancel();
    }

    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
}

  }
  • 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-15T04:52:02+00:00Added an answer on June 15, 2026 at 4:52 am

    We have two way to share data between Activity or Service :

    1.
    Use SharedPreferences for Storing username in Service or read it within Activity

    2.
    use BroadcastReceiver for Communication between service and activity(Send username from Service to Activity)

    See this tutorial for Communication between service and activity

    http://androidexperinz.wordpress.com/2012/02/14/communication-between-service-and-activity-part-1/

    http://blog.philippheckel.com/2012/06/10/android-example-communication-between-activity-and-service-using-messaging/

    your first Question is not clear if you post logcat then it’s easy to solve first issue.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

When I use make command, like make mica2, in TinyOS. The following problem will
Hello there i would like to know if it is possible to make a
I would like make a script using PHP (probably need JS) to send POST
I need something like make i.e. dependencies + executing shell commands where failing command
I would like make an extension method for the generic class A which takes
Would like to make anapplication in Java that will not automatically parse parameters used
I would like to make sure my classes are robust - even if they
I would like to make a password and username entry field. And a submit
I would like to make a JSF inputText field into upper case when the
I'd like to make a JFreeChart Histogram that maintains a constant number of bins

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.