0

我有一个在活动中工作的应用程序 - 它从电话接收器调用 GPS 数据并将其发送到我的 php 站点,从 sqlite 过滤线程中的最后一个位置,它看起来像这样

final Handler handler = new Handler();
        final Runnable runnable = new Runnable() {
            public void run() {

                if(indikator != 0)
                {
                    Cursor c=db.rawQuery("select * from lokacije", null);
                c.moveToLast();

                try{
                    w.loadUrl(c.getString(c.getColumnIndex("lokacija")));
                    db.execSQL("delete from lokacije where id <"+c.getString(c.getColumnIndex("id")));
                    }
                    catch (Exception e) {
                        // TODO: handle exception
                    }


                }
                indikator=1;
                handler.postDelayed(this, 90000);

            }
        };


    //b.setBackgroundColor(Color.RED);

    b.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub



             if(b.getText().equals("SLOBODAN"))
             {


                 b.setText("ZAUZET");
                 b.setTextColor(Color.GREEN);
             }
             else
             {

                 b.setText("SLOBODAN");
                 b.setTextColor(Color.RED);

             }
        }
    });
    //deo koji naknadno ubacujem za kriterijum
    Criteria criteria = new Criteria();
    criteria.setAccuracy(Criteria.ACCURACY_FINE);
    criteria.setPowerRequirement(Criteria.POWER_LOW);



    //kraj dela koji sam naknadno ubacio

final   LocationManager m=(LocationManager) MainActivity.this.getSystemService(Context.LOCATION_SERVICE);
    //deo koji sam takodje ubacio naknadno
String locationprovider =m.getBestProvider(criteria,true);
//deo koji sam takodje ubacio naknadno kraj


        LocationListener l=new LocationListener() {


                @Override
                public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onProviderEnabled(String arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onProviderDisabled(String arg0) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void onLocationChanged(Location arg0) {

                    String url=new String();
                    String zauzetost=new String();
                    zauzetost=b.getText().toString();

                    String format="MM/dd/yyyy";
                    SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.US);
                    String date= sdf.format(new Date());


                t.setToNow();   

                ed1.setText("");
                ed2.setText("");
                String longitude=new String();
                String latitude=new String();
                String speed=new String();

                if((int)arg0.getSpeed()==0)
                {
                    speed="0";
                }
                else
                {
                speed=""+(((int)arg0.getSpeed()*3600)/1000);
                }
                longitude=""+  arg0.getLongitude();
                latitude=""+ arg0.getLatitude();
                ed1.setText(longitude);
                ed2.setText(latitude);
                ed3.setText(speed);
                Calendar cal=Calendar.getInstance();



                url="http://www.compensatemeonline.com/truckmeonline/TruckMeOnline/UnosLokacijaSaTelefona.php?id="+mojsadrzaj+"&longitude="+longitude+"&latitude="+latitude+"&brzina="+speed+"&vreme="+cal.getTime()+"&datum="+date+"&zauzetost="+zauzetost;    

                db.execSQL("insert into lokacije (lokacija) values ('"+url+"');");


                    // TODO Auto-generated method stub

                }

            };


            // TODO Auto-generated method stub
            //pozivanje threada
             runnable.run();
            //pozivanje threada
            m.requestLocationUpdates(locationprovider, 60000, 0, l);

    //      zamenio sam m.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000, 0, l); sa m.requestLocationUpdates(locationprovider, 120000, 0, l);
        }

现在我想做的就是把它全部放在一个服务中,这样它就可以在后台运行。我应该将代码放入onCreate()还是放入onStart()方法中,Service因为我还使用了处理程序和另一个线程。当我现在使用 URL 或 HttpClient 调用网站时,因为我无法使用它WebViewActivity所以我的 logcat 中出现了如下错误:

  02-12 22:24:32.569: E/AndroidRuntime(1204): java.lang.IllegalStateException: Target host must not be null, or set in parameters. scheme=null, host=null, path=2
02-12 22:24:32.569: E/AndroidRuntime(1204):     at org.apache.http.impl.client.DefaultRequestDirector.determineRoute(DefaultRequestDirector.java:591)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:293)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at com.example.serviceswithactivity.MyService$1.run(MyService.java:127)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at android.os.Handler.handleCallback(Handler.java:725)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at android.os.Handler.dispatchMessage(Handler.java:92)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at android.os.Looper.loop(Looper.java:137)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at android.app.ActivityThread.main(ActivityThread.java:5039)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at java.lang.reflect.Method.invokeNative(Native Method)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at java.lang.reflect.Method.invoke(Method.java:511)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
02-12 22:24:32.569: E/AndroidRuntime(1204):     at dalvik.system.NativeStart.main(Native Method)

如何从服务中调用 gps 位置,这样我就不会得到 10-15 分,而只能得到一个?我在 Activity 中通过将数据放入 sqlite 数据库中,然后在线程中获取最后一行并删除其他行,以此类推。有没有更好的方法来调用 gps 位置并将其在后台发送到网站?

这是我的全部Service

public class MyService extends Service {

public int indikator=0;
public String mojsadrzaj=new String();
public String pib=new String();
public String username=new String();
public String password=new String();
public Cursor c;
public Cursor d;
 URL myURL;
@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public void onCreate() {
super.onCreate();

Toast.makeText(this,"Service created ...",Toast.LENGTH_LONG).show();

final SQLiteDatabase db=openOrCreateDatabase("TruckMe", MODE_PRIVATE, null);
db.execSQL("create table if not exists lokacije (id INTEGER  PRIMARY KEY AUTOINCREMENT NOT NULL, lokacija VARCHAR(600));");

//regulisanje podataka za logovanje samo prvi put


String idvozaca=new String();
db.execSQL("create table if not exists vozac (id INTEGER  PRIMARY KEY AUTOINCREMENT NOT NULL, idvozaca VARCHAR(15));");
d=db.rawQuery("select idvozaca from vozac", null);

//db.execSQL("delete from vozac;");

if(d.getCount() > 0)
{
    d.moveToLast();
    idvozaca=d.getString(d.getColumnIndex("idvozaca"));
    mojsadrzaj=idvozaca;
    Toast t=Toast.makeText(this, "Id vozaca je : " + mojsadrzaj, Toast.LENGTH_LONG);
    t.setGravity(Gravity.CENTER, 0, 0);
    t.show();

}
else
{
    //ubacivanje forme za dijalog




            //unos vozacid u bazu 
            db.execSQL("insert into vozac (idvozaca) values ('"+mojsadrzaj+"');");
            //unos vozacid u bazu

            //String resString = sb.toString(); // Result is here
            Toast t=Toast.makeText(this, "Aplikacija je aktivirana sa kodom : "+mojsadrzaj, Toast.LENGTH_LONG);
            t.setGravity(Gravity.CENTER, 0, 0);
            t.show();


        }





//regulisanje podataka za logovanje samo prvi put

final Time t=new Time();



 //deo za thread

 final Handler handler = new Handler();

    final Runnable runnable = new Runnable() {
        public void run() {

            if(indikator != 0)
            {

               //w.loadUrl(c.getString(c.getColumnIndex("lokacija")));

                    final SQLiteDatabase db=openOrCreateDatabase("TruckMe", MODE_PRIVATE, null);
                    c=db.rawQuery("select * from lokacije", null);
                    c.moveToLast();

                    try {
                        HttpClient client=new DefaultHttpClient();
                        URI website=new URI(c.getString(c.getColumnIndex("id")));
                        Log.e("Message", website.toString());
                        HttpGet request=new HttpGet();
                        request.setURI(website);
                        try {
                            client.execute(request);
                        } catch (ClientProtocolException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        } catch (IOException e) {
                            // TODO Auto-generated catch block
                            e.printStackTrace();
                        }



                    } catch (URISyntaxException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    /*
                    URL url = null;
                    try {
                        url = new URL(c.getString(c.getColumnIndex("id")));
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    URLConnection urlConnection = null;
                    try {
                        urlConnection = url.openConnection();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    try {
                        urlConnection.connect();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    */
                    /*
                    try {
                        myURL = new URL(c.getString(c.getColumnIndex("id")));
                    } catch (MalformedURLException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                    URLConnection myURLConnection = null;
                    try {
                        myURLConnection = myURL.openConnection();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
                    try {
                        myURLConnection.connect();
                    } catch (IOException e) {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }

                  */


                db.execSQL("delete from lokacije where id <"+c.getString(c.getColumnIndex("id")));


                    // TODO: handle exception
                  }
            indikator=1;

            handler.postDelayed(this, 15000);

        }
    };


//deo koji naknadno ubacujem za kriterijum
Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setPowerRequirement(Criteria.POWER_LOW);



//kraj dela koji sam naknadno ubacio

final   LocationManager m=(LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
    //deo koji sam takodje ubacio naknadno
String locationprovider =m.getBestProvider(criteria,true);
//deo koji sam takodje ubacio naknadno kraj


    LocationListener l=new LocationListener() {


            @Override
            public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderEnabled(String arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProviderDisabled(String arg0) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onLocationChanged(Location arg0) {

                String url=new String();
                String zauzetost=new String();
                zauzetost="ZAUZET";

                String format="MM/dd/yyyy";
                SimpleDateFormat sdf = new SimpleDateFormat(format,Locale.US);
                String date= sdf.format(new Date());


            t.setToNow();   


            String longitude=new String();
            String latitude=new String();
            String speed=new String();

            if((int)arg0.getSpeed()==0)
            {
                speed="0";
            }
            else
            {
            speed=""+(((int)arg0.getSpeed()*3600)/1000);
            }
            longitude=""+  arg0.getLongitude();
            latitude=""+ arg0.getLatitude();

            Calendar cal=Calendar.getInstance();



            url="http://www.compensatemeonline.com/truckmeonline/TruckMeOnline/UnosLokacijaSaTelefona.php?id="+mojsadrzaj+"&longitude="+longitude+"&latitude="+latitude+"&brzina="+speed+"&vreme="+cal.getTime()+"&datum="+date+"&zauzetost="+zauzetost;    
            Toast.makeText(MyService.this, url,Toast.LENGTH_LONG).show();
            db.execSQL("insert into lokacije (lokacija) values ('"+url+"');");


                // TODO Auto-generated method stub

            }

        };


        // TODO Auto-generated method stub
        //pozivanje threada
         runnable.run();
        //pozivanje threada
        m.requestLocationUpdates(locationprovider, 10000, 0, l);

//      zamenio sam m.requestLocationUpdates(LocationManager.GPS_PROVIDER, 120000, 0, l); sa m.requestLocationUpdates(locationprovider, 120000, 0, l);




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

    Toast.makeText(this, "Service started onstartcommand ...",Toast.LENGTH_LONG).show();










   return START_STICKY;

}

@Override
public void onStart(Intent intent, int startId) {
    Toast.makeText(this, "Service started onstart...",Toast.LENGTH_LONG).show();

}


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

Toast.makeText(this, "Service destroyed ...",Toast.LENGTH_LONG).show();

}


}
4

1 回答 1

1

问题不在于您的 GPS 代码,问题在于您尝试从光标中加载的 URL 不正确。

我会重新检查 的论点w.loadUrl是否正确。

于 2013-02-18T20:26:34.240 回答