0

ユーザーの場所を取得するメソッドを実行し、alarmManager を使用して特定の間隔でサーバーに送信するサービスがあります。正常に動作していますが、2 回実行されることもあり、データベースに二重のエントリが表示されたり、タイムスタンプに 1 秒の差があったり、完全に重複したデータがあったり、LogCat にあったりします。私はそれを検索しましたが、私の問題に似たものは見つかりませんでした。

my サービスのコードは次のとおりです。

  package com.mgtphil.mibackground;

 import java.util.ArrayList;
 import java.util.Date;
 import java.util.List;

 import org.apache.http.HttpResponse;
 import org.apache.http.NameValuePair;
 import org.apache.http.client.HttpClient;
 import org.apache.http.client.entity.UrlEncodedFormEntity;
 import org.apache.http.client.methods.HttpPost;
 import org.apache.http.message.BasicNameValuePair;

 import com.mgtphil.mibackground.MyLocation.*;
 import android.app.Service;
 import android.content.Context;
 import android.content.Intent;
 import android.location.Location;

 import android.net.ConnectivityManager;
 import android.net.NetworkInfo;

import android.os.IBinder;
import android.util.Log;


// the service that runs in background
public class MIService2 extends Service{

private final Context context = this;

GPSTracker gps;
HttpPost httppost;
HttpResponse response;
HttpClient httpclient;
List<NameValuePair> nameValuePairs;

MyLocation myLocation = new MyLocation();

DatabaseHandler db = new DatabaseHandler(this);
UserDatabase udb = new UserDatabase(this);

static double latitude;
static double longitude;
String userid;
String timeType;
String lat;
String lon;
Date dt;

@Override
public void onCreate() {
    Log.v("onCreate","MIService2 Service Created");
}

//MyLocation class
LocationResult locationResult = new LocationResult(){
    @Override
    public void gotLocation(Location location){
        //Got the location!
        Log.v("MI Service","MI Service gotLocation()");
        latitude = location.getLatitude();
        longitude = location.getLongitude();
        if(!myLocation.gps_enabled && !myLocation.network_enabled){
            Log.v("No Provider Enabled.", "No Provider Enabled. Do nothing.");
        } else {
            if(latitude == 0 && longitude == 0) {
                //TODO                  
            } else {
                sendData();

            }
        }
    }
};
//end

@Override
public int onStartCommand(Intent intent, int flags, int startId){

Log.v("onStartCommand","MIService2 Service Started");

myLocation.getLocation(this, locationResult);

List<User> user = udb.getAllUser();
for(User ur : user) {
    userid = ur.getUserID();
    timeType = ur.getTimeType();
}
return START_STICKY;
} //end onstartcommand

@Override
public IBinder onBind(Intent arg0) {

    return null;
}


@Override   
public void onDestroy() {
    //Toast.makeText(this, "MI Service Stopped", Toast.LENGTH_LONG).show();
    db.close();
    udb.close();
    Log.d("onDestroy","Service Stopped");

}

public void sendData() {
    long dtMili = System.currentTimeMillis();
    dt = new Date(dtMili);

    ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();

    if (netInfo != null && netInfo.isConnected())
    {

        try {
            //check db first, and send it's data first
            sendSavedData();

            lat = String.valueOf(latitude);
            lon = String.valueOf(longitude);
            //code to send data to server
            //httpclient=new DefaultHttpClient();
            httpclient = new MyHttpClient().getNewHttpClient();
            httppost= new HttpPost(Config.serverAdd); // make sure the url is correct.
            //add your data
            nameValuePairs = new ArrayList<NameValuePair>(7);
            // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
            nameValuePairs.add(new BasicNameValuePair("cmd","tracking"));
            nameValuePairs.add(new BasicNameValuePair("userid",userid));  // $userid = $_POST['userid'];
            nameValuePairs.add(new BasicNameValuePair("operationType","track"));
            nameValuePairs.add(new BasicNameValuePair("timeType",timeType));
            nameValuePairs.add(new BasicNameValuePair("time",dt.toString()));
            nameValuePairs.add(new BasicNameValuePair("latitude",lat));
            nameValuePairs.add(new BasicNameValuePair("longitude",lon));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //Execute HTTP Post Request
            response=httpclient.execute(httppost);

            Log.v("Service Tracker Send Data", "MI Tracker\nUser: " + MI_Tracker.user + "\nTime: " + dt.toString() + "\nLat: " + latitude + "\nLong: " + longitude + "\n");

        } catch(Exception e){
            Log.e("Exception","Exception : " + e.getMessage());
        }   



    } else {

        Log.v("Sending Failed.","Sending Failed, no Internet.");
        saveData();

    }

} //end sendData

public void saveData() {
    Log.v("Insert: ","Inserting ...");
    db.addTrack(new Track(MI_Tracker.userid, "track", MI_Tracker.timeType, dt.toString(),lat,lon));
}

public void sendSavedData(){
    List<Track> tracks = db.getAllTracks();

    for(Track tr : tracks) {
        boolean del = false;
        try {
            //send data to server

            httpclient = new MyHttpClient().getNewHttpClient();
            httppost= new HttpPost(Config.serverAdd); // make sure the url is correct.

            nameValuePairs = new ArrayList<NameValuePair>(7);
            // Always use the same variable name for posting i.e the android side variable name and php side variable name should be similar,
            nameValuePairs.add(new BasicNameValuePair("cmd","tracking"));
            nameValuePairs.add(new BasicNameValuePair("userid",tr.getUserID()));  // $userid = $_POST['userid'];
            nameValuePairs.add(new BasicNameValuePair("operationType","track"));
            nameValuePairs.add(new BasicNameValuePair("timeType",tr.getTimeType()));
            nameValuePairs.add(new BasicNameValuePair("time",tr.getTime()));
            nameValuePairs.add(new BasicNameValuePair("latitude",tr.getLatitude()));
            nameValuePairs.add(new BasicNameValuePair("longitude",tr.getLongitude()));
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            //Execute HTTP Post Request
            response=httpclient.execute(httppost);

            Log.v("Service Send Saved Data: ", "MI Tracker\nUser: " + tr.getUserID()+ "\nTime: " + tr.getTime() + "\nLat: " + tr.getLatitude() + "\nLong: " + tr.getLatitude());
            //Toast.makeText(getApplicationContext(), "MI Tracker Sending Data\nUser: " + MI_Tracker.user + "\nTime: " + dt.toString() + "\nLat: " + latitude + "\nLong: " + longitude + "\n", Toast.LENGTH_LONG).show();
            //delete data after sending it 05-27
            Log.v("Deleting Data","Deleting Data with ID: " + tr.getID());
            del = true;

        } catch(Exception e){
            del = false;
            Log.e("Exception on sendSaveData","Exception : " + e.getMessage());
        }   
        //delete the data when there's no error in sending the data
        if(del){
            db.deleteTrack(tr);
        } else {
            Log.v("Service Send Saved Data:","There's an error. Data retained");
        }
    }
  } //end sendSavedData()

} //end class

ログキャット:

05-31 10:02:06.375: D/dalvikvm(2945): GC_EXPLICIT freed 56K, 49% free 3584K/6919K, external 1503K/1811K, paused 48ms
05-31 10:02:22.890: V/MIServiceReceiver onReceive(2945): MIServiceReceiver Started
05-31 10:02:22.898: V/onStartCommand(2945): MIService2 Service Started
05-31 10:02:22.898: V/getLocation(2945): MyLocation getLocation
05-31 10:02:24.734: V/locationListenerNetwork(2945): Network onLocationChanged
05-31 10:02:24.734: V/MI Service(2945): MI Service gotLocation()
05-31 10:02:25.359: V/Service Tracker Send Data(2945): MI Tracker
05-31 10:02:25.359: V/Service Tracker Send Data(2945): User: clint
05-31 10:02:25.359: V/Service Tracker Send Data(2945): Time: Fri May 31 10:02:24 GMT+08:00 2013
05-31 10:02:25.359: V/Service Tracker Send Data(2945): Lat: 14.5804712
05-31 10:02:25.359: V/Service Tracker Send Data(2945): Long: 121.0599356
05-31 10:02:25.406: V/locationListenerNetwork(2945): Network onLocationChanged
05-31 10:02:25.406: V/MI Service(2945): MI Service gotLocation()
05-31 10:02:26.289: V/Service Tracker Send Data(2945): MI Tracker
05-31 10:02:26.289: V/Service Tracker Send Data(2945): User: clint
05-31 10:02:26.289: V/Service Tracker Send Data(2945): Time: Fri May 31 10:02:25 GMT+08:00 2013
05-31 10:02:26.289: V/Service Tracker Send Data(2945): Lat: 14.5806383
05-31 10:02:26.289: V/Service Tracker Send Data(2945): Long: 121.0591553
05-31 10:05:22.890: V/MIServiceReceiver onReceive(2945): MIServiceReceiver Started
05-31 10:05:22.890: V/onStartCommand(2945): MIService2 Service Started
05-31 10:05:22.890: V/getLocation(2945): MyLocation getLocation
05-31 10:05:24.570: V/locationListenerNetwork(2945): Network onLocationChanged
05-31 10:05:24.570: V/MI Service(2945): MI Service gotLocation()
05-31 10:05:25.234: D/dalvikvm(2945): GC_CONCURRENT freed 514K, 46% free 3803K/6919K, external 1503K/1811K, paused 3ms+3ms
05-31 10:05:25.234: D/Cursor(2945): Database path: trackingDB
05-31 10:05:25.234: D/Cursor(2945): Table name   : null
05-31 10:05:25.234: D/Cursor(2945): Database path: userDB
05-31 10:05:25.234: D/Cursor(2945): Table name   : null
05-31 10:05:25.234: D/Cursor(2945): Database path: trackingDB
05-31 10:05:25.234: D/Cursor(2945): Table name   : null
05-31 10:05:25.257: D/Cursor(2945): Database path: trackingDB
05-31 10:05:25.257: D/Cursor(2945): Table name   : null
05-31 10:05:25.257: D/Cursor(2945): Database path: userDB
05-31 10:05:25.257: D/Cursor(2945): Table name   : null
05-31 10:05:25.390: V/Service Tracker Send Data(2945): MI Tracker
05-31 10:05:25.390: V/Service Tracker Send Data(2945): User: clint
05-31 10:05:25.390: V/Service Tracker Send Data(2945): Time: Fri May 31 10:05:24 GMT+08:00 2013
05-31 10:05:25.390: V/Service Tracker Send Data(2945): Lat: 14.580513
05-31 10:05:25.390: V/Service Tracker Send Data(2945): Long: 121.0596886
05-31 10:05:31.875: D/dalvikvm(2945): GC_EXPLICIT freed 214K, 48% free 3604K/6919K, external 1503K/1811K, paused 39ms
05-31 10:08:22.890: V/MIServiceReceiver onReceive(2945): MIServiceReceiver Started
05-31 10:08:22.890: V/onStartCommand(2945): MIService2 Service Started
05-31 10:08:22.890: V/getLocation(2945): MyLocation getLocation
05-31 10:08:24.609: V/locationListenerNetwork(2945): Network onLocationChanged
05-31 10:08:24.609: V/MI Service(2945): MI Service gotLocation()
05-31 10:08:25.531: V/Service Tracker Send Data(2945): MI Tracker
05-31 10:08:25.531: V/Service Tracker Send Data(2945): User: clint
05-31 10:08:25.531: V/Service Tracker Send Data(2945): Time: Fri May 31 10:08:24 GMT+08:00 2013
05-31 10:08:25.531: V/Service Tracker Send Data(2945): Lat: 14.5805303
05-31 10:08:25.531: V/Service Tracker Send Data(2945): Long: 121.0598834
05-31 10:08:32.015: D/dalvikvm(2945): GC_EXPLICIT freed 255K, 48% free 3598K/6919K, external 1503K/1811K, paused 40ms
05-31 10:08:32.015: D/Cursor(2945): Database path: trackingDB
05-31 10:08:32.015: D/Cursor(2945): Table name   : null
05-31 10:08:32.015: D/Cursor(2945): Database path: userDB
05-31 10:08:32.015: D/Cursor(2945): Table name   : null
05-31 10:11:22.890: V/MIServiceReceiver onReceive(2945): MIServiceReceiver Started
05-31 10:11:22.898: V/onStartCommand(2945): MIService2 Service Started
05-31 10:11:22.898: V/getLocation(2945): MyLocation getLocation
05-31 10:11:24.625: V/locationListenerNetwork(2945): Network onLocationChanged
05-31 10:11:24.625: V/MI Service(2945): MI Service gotLocation()
05-31 10:11:25.343: V/Service Tracker Send Data(2945): MI Tracker
05-31 10:11:25.343: V/Service Tracker Send Data(2945): User: clint
05-31 10:11:25.343: V/Service Tracker Send Data(2945): Time: Fri May 31 10:11:24 GMT+08:00 2013
05-31 10:11:25.343: V/Service Tracker Send Data(2945): Lat: 14.5805254
05-31 10:11:25.343: V/Service Tracker Send Data(2945): Long: 121.0595373

私のアクティビティでのalarmManagerの私の方法:したがって、プロセス全体は、私のアクティビティはalarmmanagerを起動し、servicereceiverを開始する意図があり、servicereceiverにはサービスの意図があります。

public void processTimeOn() {
   Intent intent = new Intent(this, MIServiceReceiver.class);
   pendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), 234324243, intent, 0);
   AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
   alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), interval * 1000, pendingIntent);
    Log.v("AlarmManager","Alarm starts in " + interval + " seconds.");
}

今日のログは少し異なります。サービス onStartCommand が1回呼び出されることを確認してください. gotLocation() は2回呼び出されることがあります。

どんなフィードバックでも大歓迎です。ありがとう。

4

0 に答える 0