在课堂上使用线程

时间:2010-12-04 07:25:35

标签: android multithreading

我正在开发一个应用程序,我可以获得位置和速度。现在当用户处于速度状态时,我在用户面前显示一个用户有2个按钮的屏幕。并在我们限制的区域内做同样的事情。如果用户处于速度或区域,则必须将短信发送给父母。  但我遇到一个问题,当用户速度快我的屏幕没有来,电话被绞死,应用程序处于应用程序无响应模式。我也为此应用了线程,但没有成功,请检查我的代码并指导我是否有任何问题。如果第一个屏幕即将到来,而不是单击按钮,它将与上述情况相同。

public class CheckLocation extends Service{

    private static final String TAG = "CheckLocation";
    private LocationManager lm;
    LocationListener locationListener;
    private float speed,speedinMiles,Speedvalue,lastSpeed;
    private double lattitude=25.66;
    private double longtitude=32.45;
    private Context context;
    String IMEI,result,speedStatus,wantSpeedAlert,addwithData,alertAdd,status;
    String []child,parentNumber;
    String serverAdd= SERVER ADDRESS FOR SAVING LOCATION DATA IN DATABASE;
    String speedAlert=SERVER ADDRESS FOR SENDING MAIL
    PendingIntent pendingIntent;
    CursorHandler cursorHandler;
    boolean zoneFlag,isState,isRestrictedZone,alreadyRunning=false;
     JSONArray jArray;
     JSONObject  json_data=new JSONObject();
     SendingSmsEmail sendingSmsEmail;
     int enter=0,exit=0,speedIntent=0;




    public CheckLocation(Context context)
    {
        this.context = context;

    }


    public CheckLocation() 
    {
        Log.d(TAG,"in constructor of check location");

    }

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onCreate() 
    {
        Log.d(TAG, "onCreate()");
        super.onCreate();

        cursorHandler=new CursorHandler(this);
        TelephonyManager telephonyManager=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
        IMEI = telephonyManager.getDeviceId();
        Log.d(TAG,"imei number of phone..got it.."+IMEI);

        status=getStatus();
        Log.d(TAG, "status of speed sms.."+status);
        Log.d(TAG, "starting service");
        startService();

    }

    private void startService() 
    {
        Log.d(TAG, "startService()");
        lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationListener = new MyLocationListener();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
        Log.d(TAG, "calling location listener");
    }

    private class MyLocationListener implements LocationListener 
    {

        public void onLocationChanged(Location loc)
        {
            Log.d(TAG, "onLocationChanged()");

            if (loc != null)
            {

                lattitude=loc.getLatitude();
                longtitude=loc.getLongitude();
                lastSpeed = speed;
                speed = loc.getSpeed();


// CHANGING SPPEED IN MILES PER SECOND

                speedinMiles=(float) (speed*2.2369362920544);
                Log.d(TAG, "speed in miles.."+speedinMiles);
                loc.setSpeed(speedinMiles);

//BROADCASTING SPEED INTENT             

                Intent intent = new Intent(SOMECLASS.INTENT_SPEED_CHECK);
                intent.putExtra("speed", speedinMiles);
                intent.putExtra("lattitude",lattitude);
                intent.putExtra("longitude", longtitude);
                sendBroadcast(intent);
                Log.d(TAG, "Intent Broad casted");

//SAVING LOCATION DATA IN DATABSE               

                saveData(lattitude,longtitude);

//  CHECKING SPEED
                if(speedinMiles>20)
                {
                    new CheckSpeedTask().execute(status);// HERE STATUS IS FOR IF WE WANT TO SEND SMS OR NOT
                }
                else
                {
                    Log.d(TAG, "user is not in speed ");
                    speedIntent=0;
                }



                }




            }

        public void onProviderDisabled(String provider)
        {
            Log.d(TAG, "onProviderDisabled,enableing network provider");
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
            Log.d(TAG, "Network provider enabled");


        }

        public void onProviderEnabled(String provider) {

            Log.d(TAG, "onProviderEnabled");
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {

            Log.d(TAG, "onStatusChanged)");

        }
    }

    public float getCurrentSpeed() {
        return speedinMiles;
    }
    public double getCurrentLattitude() {
        return lattitude;
    }
    public double getCurrentLongitude() {
        return longtitude;
    }

    public float getLastSpeed() {
        return lastSpeed;
    }


    private String getStatus() 
    {
        //child=conntectionHandler.post(childstatus);
        child=cursorHandler.getData("status");
         for (int i = 0; i < child.length; i++) 
            {

                  Log.d(TAG,"status["+i+"]"+child[i]);
                  speedStatus=child[i];
                 System.out.println("status."+speedStatus);


            } 
        wantSpeedAlert=speedStatus.substring(speedStatus.indexOf(",")+1,speedStatus.lastIndexOf(","));
        System.out.println("speed alert is.."+wantSpeedAlert);

        return wantSpeedAlert;
    }

    void saveData(double lattitude2, double longtitude2)
    {
        try{        

            Log.d(TAG,"Saving...latt.."+lattitude+"..long.."+longtitude);

            addwithData=serverAdd+IMEI+"&latitude="+lattitude2+"&longitude="+longtitude2;
            Log.d(TAG,"completeServerAdd.."+addwithData);
         HttpClient httpclient = new DefaultHttpClient();
           HttpGet httpGet=new HttpGet(addwithData);
            HttpResponse response = httpclient.execute(httpGet); 
           Log.d(TAG, response.toString());
            Log.d(TAG,"server Connected"); 
            Log.i(TAG,"data inserted");

        }
        catch(Exception e)
        {

            Log.e(TAG, "Error converting result "+e.getMessage());

        }
    }


    private class CheckSpeedTask extends AsyncTask<String,Void,Void>
    {
        @Override
        protected Void doInBackground(String... status) 
        {
            Log.d(TAG, "CHECK SPEED TASK");
            String statusForMail=status[0];
            if(statusForMail.equalsIgnoreCase("y"))
            {           

                System.out.println("speed Alert status is..."+statusForMail);

                if(speedIntent==0)
                {
                        //sending mail and sms to parent
                        alertAdd=speedAlert+IMEI+"&speed="+speedinMiles;
                        Log.d(TAG, "address for speed alert."+alertAdd);
                        Log.d(TAG, "prompting server ");
                        try 
                        {
                         HttpClient httpClient = new DefaultHttpClient();
                        HttpGet  httpGet=new HttpGet(alertAdd);
                        HttpResponse response = httpClient.execute(httpGet);
                          Log.d(TAG,"mail send");
                          speedIntent=1;

                        } 
                        catch (Exception e)
                        {
                            Toast.makeText(context,"Sever Connection Problem",Toast.LENGTH_LONG);
                            e.printStackTrace();

                        }
                }
                else
                {
                    Log.d(TAG, "speed intent value is 1 so not sending mail");
                }

            }
            else
            {

                Log.d(TAG, "Speed alert status is negative");
            }
            return null;

        }

        @Override
        protected void onPostExecute(Void result)
        {
            Log.d(TAG, "Starting Intent");
            Intent screenIntent=new Intent(getApplicationContext(),SpeedScreen.class);
            screenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            screenIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            getApplicationContext().startActivity(screenIntent);    
            Log.d(TAG, "new Activity Starts");

        }
    }


}

我还在按钮点击方法中添加了一个线程。  如果出现任何问题,请指导我。   提前谢谢

1 个答案:

答案 0 :(得分:1)

请检查此答案

public class CheckLocation extends Service{

    private static final String TAG = "CheckLocation";
    private LocationManager lm;
    LocationListener locationListener;
    private float speed,speedinMiles,Speedvalue,lastSpeed;
    private double lattitude=25.66;
    private double longtitude=32.45;
    private Context context;
    String IMEI,result,speedStatus,wantSpeedAlert,addwithData,alertAdd,status;
    String []child,parentNumber;
    String serverAdd= SERVER ADDRESS FOR SAVING LOCATION DATA IN DATABASE;
    String speedAlert=SERVER ADDRESS FOR SENDING MAIL
    PendingIntent pendingIntent;
    CursorHandler cursorHandler;
    boolean zoneFlag,isState,isRestrictedZone,alreadyRunning=false;
     JSONArray jArray;
     JSONObject  json_data=new JSONObject();
     SendingSmsEmail sendingSmsEmail;
     int enter=0,exit=0,speedIntent=0;




    public CheckLocation(Context context)
    {
        this.context = context;

    }


    public CheckLocation() 
    {
        Log.d(TAG,"in constructor of check location");

    }

    @Override
    public IBinder onBind(Intent intent) {

        return null;
    }

    @Override
    public void onCreate() 
    {
        Log.d(TAG, "onCreate()");
        super.onCreate();

        cursorHandler=new CursorHandler(this);
        TelephonyManager telephonyManager=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
        IMEI = telephonyManager.getDeviceId();
        Log.d(TAG,"imei number of phone..got it.."+IMEI);

        status=getStatus();
        Log.d(TAG, "status of speed sms.."+status);
        Log.d(TAG, "starting service");
        startService();

    }

    private void startService() 
    {
        Log.d(TAG, "startService()");
        lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
        locationListener = new MyLocationListener();
        lm.requestLocationUpdates(LocationManager.GPS_PROVIDER,0,0,locationListener);
        Log.d(TAG, "calling location listener");
    }

    private class MyLocationListener implements LocationListener 
    {

        public void onLocationChanged(Location loc)
        {
            Log.d(TAG, "onLocationChanged()");

            if (loc != null)
            {

                lattitude=loc.getLatitude();
                longtitude=loc.getLongitude();
                lastSpeed = speed;
                speed = loc.getSpeed();


// CHANGING SPPEED IN MILES PER SECOND

                speedinMiles=(float) (speed*2.2369362920544);
                Log.d(TAG, "speed in miles.."+speedinMiles);
                loc.setSpeed(speedinMiles);

//BROADCASTING SPEED INTENT             

                Intent intent = new Intent(SOMECLASS.INTENT_SPEED_CHECK);
                intent.putExtra("speed", speedinMiles);
                intent.putExtra("lattitude",lattitude);
                intent.putExtra("longitude", longtitude);
                sendBroadcast(intent);
                Log.d(TAG, "Intent Broad casted");

//SAVING LOCATION DATA IN DATABSE               

                saveData(lattitude,longtitude);

//  CHECKING SPEED
                if(speedinMiles>20)
                {
                    new CheckSpeedTask().execute(status);// HERE STATUS IS FOR IF WE WANT TO SEND SMS OR NOT
                }
                else
                {
                    Log.d(TAG, "user is not in speed ");
                    speedIntent=0;
                }



                }




            }

        public void onProviderDisabled(String provider)
        {
            Log.d(TAG, "onProviderDisabled,enableing network provider");
            lm.requestLocationUpdates(LocationManager.NETWORK_PROVIDER,0,0,locationListener);
            Log.d(TAG, "Network provider enabled");


        }

        public void onProviderEnabled(String provider) {

            Log.d(TAG, "onProviderEnabled");
        }

        public void onStatusChanged(String provider, int status, Bundle extras) {

            Log.d(TAG, "onStatusChanged)");

        }
    }

    public float getCurrentSpeed() {
        return speedinMiles;
    }
    public double getCurrentLattitude() {
        return lattitude;
    }
    public double getCurrentLongitude() {
        return longtitude;
    }

    public float getLastSpeed() {
        return lastSpeed;
    }


    private String getStatus() 
    {
        //child=conntectionHandler.post(childstatus);
        child=cursorHandler.getData("status");
         for (int i = 0; i < child.length; i++) 
            {

                  Log.d(TAG,"status["+i+"]"+child[i]);
                  speedStatus=child[i];
                 System.out.println("status."+speedStatus);


            } 
        wantSpeedAlert=speedStatus.substring(speedStatus.indexOf(",")+1,speedStatus.lastIndexOf(","));
        System.out.println("speed alert is.."+wantSpeedAlert);

        return wantSpeedAlert;
    }

    void saveData(double lattitude2, double longtitude2)
    {
        try{        

            Log.d(TAG,"Saving...latt.."+lattitude+"..long.."+longtitude);

            addwithData=serverAdd+IMEI+"&latitude="+lattitude2+"&longitude="+longtitude2;
            Log.d(TAG,"completeServerAdd.."+addwithData);
         HttpClient httpclient = new DefaultHttpClient();
           HttpGet httpGet=new HttpGet(addwithData);
            HttpResponse response = httpclient.execute(httpGet); 
           Log.d(TAG, response.toString());
            Log.d(TAG,"server Connected"); 
            Log.i(TAG,"data inserted");

        }
        catch(Exception e)
        {

            Log.e(TAG, "Error converting result "+e.getMessage());

        }
    }


    private class CheckSpeedTask extends AsyncTask<String,Void,Void>
    {


        @Override
        protected Void doInBackground(String... status) 
        {
            Log.d(TAG, "CHECK SPEED TASK");
            String statusForMail=status[0];
            if(statusForMail.equalsIgnoreCase("y"))
            {           

                System.out.println("speed Alert status is..."+statusForMail);

                if(speedIntent==0)
                {
                        //sending mail and sms to parent
                        alertAdd=speedAlert+IMEI+"&speed="+speedinMiles;
                        Log.d(TAG, "address for speed alert."+alertAdd);
                        Log.d(TAG, "prompting server ");
                        try 
                        {
                         HttpClient httpClient = new DefaultHttpClient();
                        HttpGet  httpGet=new HttpGet(alertAdd);
                        HttpResponse response = httpClient.execute(httpGet);
                          Log.d(TAG,"mail send");
                          speedIntent=1;

                        } 
                        catch (Exception e)
                        {
                            Toast.makeText(context,"Sever Connection Problem",Toast.LENGTH_LONG);
                            e.printStackTrace();

                        }
                }
                else
                {
                    Log.d(TAG, "speed intent value is 1 so not sending mail");
                }

            }
            else
            {

                Log.d(TAG, "Speed alert status is negative");
            }

             Log.d(TAG, "Starting Intent");
            Intent screenIntent=new Intent(getApplicationContext(),SpeedScreen.class);
            screenIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            screenIntent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
            getApplicationContext().startActivity(screenIntent);    
            Log.d(TAG, "new Activity Starts");



            return null;

        }


        }
    }


}