我喜欢让服务定期执行两个任务,可以吗?通过下面的结构,是真的吗?实际上我已经测试过它并且它给了我错误......或者我应该将所有任务嵌入到计时器任务中?
我想问的另一个问题是如何从服务中获取用户的用户名?这是因为我需要用户的用户名来检查和更新任务中的某些内容。用户的用户名可以在 login.java 中获得,它验证用户身份,但是服务在用户访问应用程序之前已经运行,那么我怎么能得到用户的用户名从服务?
运行 MyService.class 时,突然弹出 Timer.class 并给出错误..
错误日志:
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)
提前致谢..
这是我的代码:
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();
}
}