English 中文(简体)
履历:
原标题:Android Tracking App, posting http

The main idea is to track friends in the background and every 3 minutes to update their places and to send the location on http; When I run it on the emulator it gives me force close. I want you to have in mind that I m a beginner in Android and I am stuck on this for month and half, but I don t know how to connect the Android Service with httpPost.

public class Tracker extends Service {

    private LocationManager locManager;
    private LocationListener locListener;
    private TelephonyManager mTelephonyMgr;


    // creating and starting the service
    public void onCreate() {
        super.onCreate();
        startService();
        Toast.makeText(getApplicationContext(), "Service created", Toast.LENGTH_LONG);
    }
    /*public void onStart(){
        super.onStart(intent, startId)
        startService();
    }*/

    // shutting down the service
    public void onDestroy() {
        super.onDestroy();
        shutDownService();
        Toast.makeText(getApplicationContext(), "Service is destroyed", Toast.LENGTH_LONG);

    }

    public void shutDownService() {
        locManager.removeUpdates(locListener);
    }

    private final IBinder mBinder = new LocalBinder();

    public IBinder onBind(Intent intent) {

        return mBinder;
    }

    public class LocalBinder extends Binder {
        Tracker.getService() {
            return Tracker.this;
        }
    }

    public void startService() {

        locManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        locListener = new MyLocationListener();
        locManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, 0,
                0, locListener);
        locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
                locListener);
        postData(null, null);   //  return START_STICKY;
    }

    public void postData(String currLat, String currLon) {

        String Text2 = "String is" + "Latitude = " + currLat + "Longitude = "
                + currLon;
        String Text3 = "Phone number is: " + getMyDigitsPhoneNumber();
        // showing implicit intent 
        Toast.makeText(getApplicationContext(), Text2, Toast.LENGTH_LONG); 
        Toast.makeText(getApplicationContext(), Text3, Toast.LENGTH_LONG);

        HttpPost httppost = new HttpPost(
                "http://87.88.0.178/firm/logger.php");
        // Add the data
        List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
        nameValuePairs.add(new BasicNameValuePair("PhoneNumber", getMyDigitsPhoneNumber()));
        nameValuePairs.add(new BasicNameValuePair("Latitude", currLat));
        nameValuePairs.add(new BasicNameValuePair("Longitude", currLon));
        HttpClient client = new DefaultHttpClient();
        try {
            httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
            HttpResponse response = client.execute(httppost);
            HttpEntity entity = response.getEntity();
            String responseText = EntityUtils.toString(entity);
            responseText = responseText.trim();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String getMyPhoneNumber() {

        mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
        return mTelephonyMgr.getLine1Number();
    }

    public String getMyDigitsPhoneNumber() {
        String phoneNum = getMyPhoneNumber();
        return phoneNum.substring(2);
    }



    // retrieving location
    public class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location loc) {
            if (loc != null)
                loc.getLatitude();
            loc.getLongitude();

            double lat = loc.getLatitude()*1E6;
            double lon = loc.getLongitude()*1E6;

            String curr_lat = Double.toString(lat);
            String curr_lon = Double.toString(lon);

            postData(curr_lat, curr_lon);

            String Text = "My current location is: " + "Latitud = "
                    + loc.getLatitude()*1E6 +

                    "Longitud = " + loc.getLongitude()*1E6;

            Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT);
        }

                            //took from android website
        private static final int THREE_MINUTES = 1000 * 60 * 3; // three minutes

        protected boolean isBetterLocation(Location loc,
                Location currentBestLocation) {
            if (currentBestLocation == null) {
                // A new location is always better than no location
                return true;
            }

            // Check whether the new location fix is newer or older
            long timeDelta = loc.getTime() - currentBestLocation.getTime();
            boolean isSignificantlyNewer = timeDelta > THREE_MINUTES;
            boolean isSignificantlyOlder = timeDelta < -THREE_MINUTES;
            boolean isNewer = timeDelta > 0;

            // If it s been more than two minutes since the current location,
            // use the new location
            // because the user has likely moved
            if (isSignificantlyNewer) {
                return true;
                // If the new location is more than two minutes older, it must
                // be worse
            } else if (isSignificantlyOlder) {
                return false;
            }

            // Check whether the new location fix is more or less accurate
            int accuracyDelta = (int) (loc.getAccuracy() - currentBestLocation
                    .getAccuracy());
            boolean isLessAccurate = accuracyDelta > 0;
            boolean isMoreAccurate = accuracyDelta < 0;
            boolean isSignificantlyLessAccurate = accuracyDelta > 200;

            // Check if the old and new location are from the same provider
            boolean isFromSameProvider = isSameProvider(loc.getProvider(),
                    currentBestLocation.getProvider());

            // Determine location quality using a combination of timeliness and
            // accuracy
            if (isMoreAccurate) {
                return true;
            } else if (isNewer && !isLessAccurate) {
                return true;
            } else if (isNewer && !isSignificantlyLessAccurate
                    && isFromSameProvider) {
                return true;
            }
            return false;
        }

        /** Checks whether two providers are the same */
        private boolean isSameProvider(String provider1, String provider2) {
            if (provider1 == null) {
                return provider2 == null;
            }
            return provider1.equals(provider2);
        }

        @Override
        public void onProviderDisabled(String provider) {
            // required for interface, not used
        }

        @Override
        public void onProviderEnabled(String provider) {
            // required for interface, not used
        }

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            // required for interface, not used
        }
    }
}
问题回答

It says ClassNotFoundException for class FriendTracker. The code you posted does not contain class FriendTracker but it does have class Tracker. Try to search word FriendTracker in your code and replace all those with Tracker. (manifest too) Did you rename FriendTracker to Tracker?

EDIT
(The original exception fixed with the above answer)

新的例外追踪显示<代码>ClassCastException和 SecurityException。 各项服务都必须在安伯内凡斯申报。

<service android:enabled="true" android:name="com.yourcompany.FriendTracker" />

Your package seems to be com.android.tracker.
I suggest changing it to something like com.yourcompany.tracker





相关问题
Android - ListView fling gesture triggers context menu

I m relatively new to Android development. I m developing an app with a ListView. I ve followed the info in #1338475 and have my app recognizing the fling gesture, but after the gesture is complete, ...

AsyncTask and error handling on Android

I m converting my code from using Handler to AsyncTask. The latter is great at what it does - asynchronous updates and handling of results in the main UI thread. What s unclear to me is how to handle ...

Android intent filter for a particular file extension?

I want to be able to download a file with a particular extension from the net, and have it passed to my application to deal with it, but I haven t been able to figure out the intent filter. The ...

Android & Web: What is the equivalent style for the web?

I am quite impressed by the workflow I follow when developing Android applications: Define a layout in an xml file and then write all the code in a code-behind style. Is there an equivalent style for ...

TiledLayer equivalent in Android [duplicate]

To draw landscapes, backgrounds with patterns etc, we used TiledLayer in J2ME. Is there an android counterpart for that. Does android provide an option to set such tiled patterns in the layout XML?

Using Repo with Msysgit

When following the Android Open Source Project instructions on installing repo for use with Git, after running the repo init command, I run into this error: /c/Users/Andrew Rabon/bin/repo: line ...

Android "single top" launch mode and onNewIntent method

I read in the Android documentation that by setting my Activity s launchMode property to singleTop OR by adding the FLAG_ACTIVITY_SINGLE_TOP flag to my Intent, that calling startActivity(intent) would ...

From Web Development to Android Development

I have pretty good skills in PHP , Mysql and Javascript for a junior developer. If I wanted to try my hand as Android Development do you think I might find it tough ? Also what new languages would I ...

热门标签