Android:Android Service强制应用程序运行缓慢

时间:2013-11-23 05:09:01

标签: android service android-asynctask gps

我已经多次搜索过,并通过询问这类问题尝试了解决方案。但没有帮助。所以我想我的代码可能存在一些问题。

我的应用程序的主要座右铭是在每分钟跟踪gps位置并发送到服务器。并且还做了一些服务器事务。所以我想开始一个后台服务,并通过asynctask在服务中做所有gps和服务器的东西。应用程序正在运行,但执行速度很慢......

我在主要活动中开始了我的服务:

    private void startworks() {
    Calendar cal = Calendar.getInstance();
    Intent intent = new Intent(this, NewService.class);
    PendingIntent pintent = PendingIntent.getService(this, 0, intent, 0);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
            45 * 1000, pintent);
}

    @Override
    protected void onStart() {
    super.onStart();
    startworks();
}

关于我的服务..我在这里提供了一个......

public class NewService extends Service {
String servicestring;
String lastId = "";
String holdLastId = "";
private static final String NotificationUrl = "some url";
private static final double LATITUDE = 12.9056742;
private static final double LONGITUDE = 77.6512342;

public static final int MSG_INCREMENT = 1;
public static final int MSG_COUNTER = 2;

private final IBinder mBinder = new ServiceBinder();

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

    toggleGPSOn();
    sendnotification();

    WifiManager wm = (WifiManager) getSystemService(WIFI_SERVICE);

    if (!wm.isWifiEnabled()) {
        wm.setWifiEnabled(true);
    } else {
        // wm.setWifiEnabled(false);
    }
    // ************************Fetch InTime*******************************
    AsyncTime getDate = new AsyncTime();

    String returnedDateTime = "";
    try {
        returnedDateTime = getDate.execute().get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    if (returnedDateTime.equals("2013-09-18 14:11:01.000")) {
        Toast.makeText(this, "It exits", Toast.LENGTH_SHORT).show();
    } else {
        Toast.makeText(this, "It doesn't exits", Toast.LENGTH_SHORT).show();
    }
    // *****************************----****************************************
    FetchCordinates async = new FetchCordinates();
    async.execute();

    return START_STICKY;
}

public class ServiceBinder extends Binder {
    NewService getService() {
        return NewService.this;
    }
}

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

public void setAlarmReminder(Calendar c) {
    new AlarmReminderTask(this, c).run();
}

private void toggleGPSOn() {
    String provider = Settings.Secure.getString(getContentResolver(),
            Settings.Secure.LOCATION_PROVIDERS_ALLOWED);

    if (!provider.contains("gps")) {
        final Intent poke = new Intent();
        poke.setClassName("com.android.settings",
                "com.android.settings.widget.SettingsAppWidgetProvider");

        poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
        poke.setData(Uri.parse("3"));
        sendBroadcast(poke);
    }
}

public class FetchCordinates extends AsyncTask<String, Integer, String> {

    public double lati = 0.0;
    public double longi = 0.0;
    String serverLatitude = "";
    String serverLongitude = "";
    String dateString;

    public LocationManager mLocationManager;
    public MyLocationListener mVeggsterLocationListener;

    @Override
    protected void onPreExecute() {
        Criteria myCriteria = new Criteria();
        myCriteria.setAccuracy(Criteria.ACCURACY_MEDIUM);
        myCriteria.setPowerRequirement(Criteria.POWER_LOW);

        mVeggsterLocationListener = new MyLocationListener();
        mLocationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        String myProvider = mLocationManager.getBestProvider(myCriteria,
                true);
        mLocationManager.requestLocationUpdates(myProvider, 500, 5,
                mVeggsterLocationListener);
    }

    private double distance(double lat1, double lon1, double lat2,
            double lon2) {
        double theta = lon1 - lon2;
        double dist = Math.sin(deg2rad(lat1)) * Math.sin(deg2rad(lat2))
                + Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2))
                * Math.cos(deg2rad(theta));
        dist = Math.acos(dist);
        dist = rad2deg(dist);
        dist = dist * 60 * 1.1515;
        return (dist);
    }

    private double deg2rad(double deg) {
        return (deg * Math.PI / 180.0);
    }

    private double rad2deg(double rad) {
        return (rad * 180.0 / Math.PI);
    }

    public double round(double unrounded) {
        BigDecimal bd = new BigDecimal(unrounded * 1.609344f);
        BigDecimal rounded = bd.setScale(1, BigDecimal.ROUND_CEILING);
        Log.d("Distance Is:", "Currentlly you are " + rounded.doubleValue()
                * 1000 + " meters " + "distance from Last Distance");
        return rounded.doubleValue() * 1000;
    }

    @Override
    protected String doInBackground(String... params) {

        while (this.lati == 0.0) {

        }
        return null;
    }

    public class MyLocationListener implements LocationListener {

        @Override
        public void onLocationChanged(Location location) {

            try {

                SimpleDateFormat fmt = new SimpleDateFormat(
                        "dd-MM-yyyy-HH:mm:ss");
                Date date = new Date();
                dateString = fmt.format(date);
                Log.d("DateString", dateString);

                lati = location.getLatitude();
                longi = location.getLongitude();

            } catch (Exception e) {
                e.printStackTrace();
            }

        }

        @Override
        public void onProviderDisabled(String provider) {
            Log.i("OnProviderDisabled", "OnProviderDisabled");
        }

        @Override
        public void onProviderEnabled(String provider) {
            Log.i("onProviderEnabled", "onProviderEnabled");
        }

        @Override
        public void onStatusChanged(String provider, int status,
                Bundle extras) {
            Log.i("onStatusChanged", "onStatusChanged");

        }

    }

    @Override
    protected void onCancelled() {

        mLocationManager.removeUpdates(mVeggsterLocationListener);
    }

    @Override
    protected void onPostExecute(String result) {
        Log.d("Post Execute", "Executed");
        super.onPostExecute(result);
        float[] arr = new float[30];

        if (round(distance(LATITUDE, LONGITUDE, lati, longi)) < 500) {
            Log.d("OnPostExecute", "In");
            sendServiceActiveBroadcast(true);
            Thread swipeInThread = new Thread() {

                @Override
                public void run() {
                    super.run();
                    try {
                        HttpClient client = new DefaultHttpClient();
                        HttpPost post = new HttpPost(
                                "url...");
                        HttpResponse responses = client.execute(post);
                        int status = responses.getStatusLine()
                                .getStatusCode();
                        Log.d("Status", String.valueOf(status));

                    } catch (ClientProtocolException e) {
                        e.printStackTrace();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }

            };
            swipeInThread.start();

        } else if (round(distance(LATITUDE, LONGITUDE, lati, longi)) > 500
                && round(distance(LATITUDE, LONGITUDE, lati, longi)) < 600) {
            Log.d("OnPostExecute", "Out");
            sendServiceActiveBroadcast(false);

        } else {

        }
    }

    private final void sendServiceActiveBroadcast(final boolean pActivate) {
        final Intent _intent = new Intent();
        _intent.setAction(BROADCAST_ACTION);
        _intent.putExtra("isactive", pActivate);

        NewService.this.sendBroadcast(_intent);
    }

}

class AsyncTime extends AsyncTask<Void, Void, String> {

    @Override
    protected String doInBackground(Void... v) {
        String getDateTime = "";

        try {
            HttpClient client = new DefaultHttpClient();
            HttpGet get = new HttpGet(
                    "url..");
            HttpResponse responses = client.execute(get);
            int status = responses.getStatusLine().getStatusCode();
            Log.d("Status For Get", String.valueOf(status));
            BufferedReader bf = new BufferedReader(new InputStreamReader(
                    responses.getEntity().getContent()));
            String datas = "";
            while ((datas = bf.readLine()) != null) {
                Log.d("data", datas);
                try {
                    JSONObject jsonStuffs = new JSONObject(datas);
                    getDateTime = jsonStuffs.getString("inTime");
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return getDateTime;
    }

}

我知道我在这里分享了一个巨大的代码。但对我来说最重要的是分享这个。

任何建议和帮助都是值得赞赏的。

谢谢

3 个答案:

答案 0 :(得分:2)

我认为问题在于此代码returnedDateTime = getDate.execute().get();

参与此get method

get方法也许等待你的doinBackground工作完成,这将导致等待MainThread并使你的应用变慢;

希望得到这个帮助。

答案 1 :(得分:1)

执行此操作的正确方法是使用侦听器,以便您可以接收更新,然后将其发送到服务器。此外,你应该采取一种策略来沟通你不会耗尽电池。

请查看Location Strategies guide,您将更好地了解如何达到您想要的效果。

答案 2 :(得分:1)

首先,您扩展Service,这意味着您的所有服务代码都在主线程(toggleGPSOnsendnotification ...)中运行。您可以扩展IntentService而不是onStartCommand将在单独的线程中执行。在这种情况下,您甚至不需要AsyncTaks。

其次,AsyncTask并不像看起来那么简单。在新的机器人上,它是一个单线程队列。因此,您的服务任务有时会阻止应用程序任务。

最后,如果你真的有一个繁重的服务,并且你不能在一个过程中适应所有,你可以在单独的过程中运行服务,并使用IPC在服务和主应用程序之间进行通信。