0

サービスに2つのタスクを定期的に実行させるのが好きですが、可能ですか?次のような構造で本当ですか?実際にテストしましたが、エラーが発生します...またはすべてのタスクをタイマータスクに埋め込む必要がありますか?

私が聞きたいもう1つの質問は、サービスからユーザーのユーザー名を取得するにはどうすればよいですか?これは、タスクから何かを確認して更新するためにユーザーのユーザー名が必要なためです。ユーザーのユーザー名は、ユーザーIDを認証するlogin.javaで取得できますが、ユーザーがアプリケーションにアクセスする前にサービスが実行されているため、ユーザーのユーザー名を取得するにはどうすればよいですか。サービスから?

MyService.classを実行すると、Timer.classが突然ポップアップし、エラーが発生します。

コードを実行したときの結果

エラー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)

前もって感謝します..

これが私のコードです:

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();
}

  }
4

1 に答える 1

0

アクティビティまたはサービス間でデータを共有する方法は2つあります。

1. SharedPreferencesを 使用してユーザー名をサービスに保存するか、アクティビティ内で読み取ります

2.サービスとアクティビティ間の通信にBroadcastReceiverを 使用します(サービスからアクティビティにユーザー名を送信します)

サービスとアクティビティ間の通信については、このチュートリアルを参照してください

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/

logcatを投稿した場合、最初の質問は明確ではありません。最初の問題を解決するのは簡単です。

于 2012-11-28T18:45:04.010 に答える