开发者

using threads in class

开发者 https://www.devze.com 2023-01-28 16:21 出处:网络
hii i am developing an app in which i m getting locations and speed. now when the user in speed , i m showing a screen in front of user on which user has 2 buttons. and doing same in a zone which we m

hii i am developing an app in which i m getting locations and speed. now when the user in speed , i m showing a screen in front of user on which user has 2 buttons. and doing same in a zone which we make restricted. user has to send sms to parent if he is in speed or zone. but i m getting a problem that as user got speed my screen is not coming, phone got hanged and app is in App not responding mode. i apply threading for this also but didn't get succeed , please check my code and guide me is there is anything goes wrong.if the first screen is coming than on click of button it is going in same situation as above.

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)
        {

   开发者_StackOverflow社区         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");

        }
    }


}

i also put a thread in on button click method. please guide me if anything goes wrong. thanks in advance


pls check this answer

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;

        }


        }
    }


}
0

精彩评论

暂无评论...
验证码 换一张
取 消