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 Answers1

0

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.

ρяσѕρєя K
  • 132,198
  • 53
  • 198
  • 213