Android应用程序在网络消息中卡住了

Android应用程序在网络消息中卡住了,android,Android,我将解释我的应用程序的过程 首先,它显示谷歌地图,然后我画了一些多段线,然后我选择了一些联系人向他发送坐标(所有这些都是在主要活动中进行的,它正在工作) 这是我主要活动的代码: public class MainActivity extends FragmentActivity { static boolean active = false; @Override public void onStart() { super.onStart(); active = true; }

我将解释我的应用程序的过程

首先,它显示谷歌地图,然后我画了一些多段线,然后我选择了一些联系人向他发送坐标(所有这些都是在主要活动中进行的,它正在工作)

这是我主要活动的代码:

public class MainActivity extends FragmentActivity {

static boolean active = false;
@Override
public void onStart() {

   super.onStart();

   active = true;
}

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

   active = false;
}
public static boolean isActive(){
    return active;
}

private static final int PICK_CONTACT = 1;

GoogleMap googleMap;
ArrayList<LatLng>  points= new  ArrayList<LatLng>() ;

Double glat;
Double glon;
int find_someone=0;
int save=0;

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

// Getting reference to the SupportMapFragment of activity_main.xml

SupportMapFragment fm = (SupportMapFragment)    getSupportFragmentManager().findFragmentById(R.id.map);

// Getting GoogleMap object from the fragment
googleMap = fm.getMap();

// Enabling MyLocation Layer of Google Map
googleMap.setMyLocationEnabled(true);

// Enabling buildings of Google Map
googleMap.setBuildingsEnabled(true);

googleMap.setOnMapLoadedCallback(new OnMapLoadedCallback() {

    @Override
    public void onMapLoaded() {
Location lm = googleMap.getMyLocation();
if (lm!=null){
CameraPosition cp = new CameraPosition.Builder()
.target(new LatLng(lm.getLatitude(), lm.getLongitude()))
.zoom(17)
.build();     
googleMap.animateCamera(CameraUpdateFactory.newCameraPosition(cp));
}
     }
});

// Setting OnClick event listener for the Google Map
googleMap.setOnMapClickListener(new OnMapClickListener() {

    @Override
    public void onMapClick(LatLng point) {

        // Instantiating the class MarkerOptions to plot marker on the map
        MarkerOptions markerOptions = new MarkerOptions();

        // Setting latitude and longitude of the marker position
        markerOptions.position(point);

        // Setting title of the infowindow of the marker
        markerOptions.title("Position");

        // Setting the content of the infowindow of the marker
        markerOptions.snippet("Latitude:"+point.latitude+","+"Longitude:"+point.longitude);

        // Instantiating the class PolylineOptions to plot polyline in the map
        PolylineOptions polylineOptions = new PolylineOptions();

        // Setting the color of the polyline
        polylineOptions.color(Color.BLUE);

        // Setting the width of the polyline
        polylineOptions.width(6);

        // Adding the taped point to the ArrayList

        points.add(point);

        // Setting points of polyline
        polylineOptions.addAll(points);

        // Adding the polyline to the map
        googleMap.addPolyline(polylineOptions);

        // Adding the marker to the map
        googleMap.addMarker(markerOptions);
    }
});

googleMap.setOnMapLongClickListener(new OnMapLongClickListener() {

    @Override
    public void onMapLongClick(LatLng point) {
        // Clearing the markers and polylines in the google map
        googleMap.clear();

        // Empty the array list
        points.clear();
    }
}); 

if (String.valueOf(points)!=null){
    Button pickContact = (Button) findViewById(R.id.button1);

    pickContact.setOnClickListener(new OnClickListener(){

        public void onClick(View v) {
            save=1;
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE);
            startActivityForResult(intent, 1);
                  }
    });
    }

    else{
         Toast.makeText(this, "select points", Toast.LENGTH_LONG).show();
    }
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (data != null) {
        Uri uri = data.getData();

        if (uri != null) {
            Cursor c = null;
            try {
                c = getContentResolver().query(uri, new String[]{ 
                            ContactsContract.CommonDataKinds.Phone.NUMBER,  
                            ContactsContract.CommonDataKinds.Phone.TYPE },
                        null, null, null);

                if (c != null && c.moveToFirst()) {
                    String number = c.getString(0);
                    int type = c.getInt(1);
                    showSelectedNumber(type, number);
                    System.out.println(number);
                    System.out.println("val: "+String.valueOf(points));
                    if (save==1)
                            {
                    SmsManager sm = SmsManager.getDefault();
                    ArrayList<String> parts =sm.divideMessage(String.valueOf(points));
                    int numParts = parts.size();

                    ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>();
                    ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>();

                    for (int i = 0; i < numParts; i++) {
                    sentIntents.add(PendingIntent.getBroadcast(getBaseContext(), 0, getIntent(), 0));
                    deliveryIntents.add(PendingIntent.getBroadcast(getBaseContext(), 0, data, 0));
                    }

                    sm.sendMultipartTextMessage(number,null, parts, sentIntents, deliveryIntents);
                    }
                }
            }
             finally {
                if (c != null) {
                    c.close();
                }
            }
        }
    }
}

public void showSelectedNumber(int type, String number) {
    Toast.makeText(this, type + ": " + number, Toast.LENGTH_LONG).show();
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
     Inflate the menu; this adds items to the action bar if it is present.

    return true;
}
}
然后我的手机响了,服务一直锁定在网络上

这是我的服务代码:

public class GPSTRACKER extends Service implements LocationListener {

    //private final Context mContext=getBaseContext();

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location

    double latitude;// latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; 

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES =  60 ; 

    // Declaring a Location Manager
    protected LocationManager locationManager;

    //public GPSTRACKER(Context context) {
        //this.mContext = context;
    //}
    //WakeLock wakeLock;

    @Override

    public IBinder onBind(Intent arg0) {

        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();

            //PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

            //wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");
    }
    @Override
    public void onStart(Intent intent, int startId) {

        Bundle extras = intent.getExtras();

                if (extras != null && !extras.isEmpty()) {  // has effect of unparcelling Bundle

                    String message = intent.getStringExtra("message");
                    String number = intent.getStringExtra("number");
                  //int pumber= Integer.parseInt(number.toString());

                    int p=0,j,i=1,t,success=0;
                    double[] d = new double[1000];

                    Matcher m = Pattern.compile("(?!=\\d\\.\\d\\.)([\\d.]+)").matcher(message);

                    while(m.find())
                    {
                       double  k = Double.parseDouble(m.group(1));
                       d[p]=k;
                       p++;
                     }

                     //if (message.contains(number)){
                        // Location h=getLocation();
                        // latitude=h.getLatitude();
                         //longitude = h.getLongitude();
                        // final LocalBroadcastManager localBroadcastManager =
                                   // LocalBroadcastManager.getInstance(getBaseContext());
                                    //intent.putExtra("lat",latitude);
                                   // intent.putExtra("lng",longitude);
                                    //localBroadcastManager.sendBroadcast(new Intent());

                   // }
                     double line;
                     double[] ship = new double[1000] ;
                     double[] b = new double[1000] ;

                    ship[0]=SlopeCalc(d[2],d[0],d[3],d[1]);
                    b[0]=d[0]-ship[0]*d[1];


                    if (p>3)
                    {

                    for(j=2;j<p;j++)
                    {
                        if(j+2<p){
                        ship[i]=SlopeCalc(d[j+2],d[j-2+2],d[j+1+2],d[j-1+2]);
                        b[i]=d[j]-(ship[i]*d[j+1]);

                        j++;
                        i++;
                        }
                        else{
                            break;
                        }
                    }
                    }

                    while(true)
                    {
                     Location h=getLocation();
                     latitude=h.getLatitude();
                     longitude = h.getLongitude();
                     //System.out.println(latitude);
                    // System.out.println(longitude);
                    for (t=0;t<i;t++){
                    line=ship[t]*longitude+b[t]-latitude;

                    if (line>-0.001 && line<0.001){
                        success=1;
                        break;
                    }
                    }
                    if (success==1){
                    break;
                    }

                    }
                    if ( success==1){
                        SmsManager.getDefault().sendTextMessage(number, null, "HI WHATS UP DUDE HE IS THER", null, null);
                        //wakeLock.release();
                        stopService(intent);
                    }
                }
                else
                {
                    Log.i("Log", "Bundle is null");
                }
    }           

    public static double SlopeCalc(double y2,double y1, double x2,double x1){

        double sou;
        sou=(y2-y1)/(x2-x1);
        return sou;
    }


    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
            public void stopUsingGPS(){
            if(locationManager != null){
            locationManager.removeUpdates((android.location.LocationListener) GPSTRACKER.this);
            }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will launch Settings Options
     * */
    //public void showSettingsAlert(){
        //AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
       // alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
       // alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
       // alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
         //   public void onClick(DialogInterface dialog,int which) {
            //  Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                //mContext.startActivity(intent);
           // }
       // });

        // on pressing cancel button
       // alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        //    public void onClick(DialogInterface dialog, int which) {
          //  dialog.cancel();
           // }
        //});

        // Showing Alert Message
      //  alertDialog.show();
    //}

    @Override
    public void onLocationChanged(Location location) {
        //getLocation();
    }
    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    public Location getLocation() {
        locationManager = (LocationManager) 
                getSystemService(LOCATION_SERVICE);

         //getting GPS status
         isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);


            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES,  this);
            Log.d("Netork", "Network");
            if (locationManager != null) {
                location = locationManager
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        }

            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES,this );
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        }
                    }
                }

        return location;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }
}
公共类GPSTRACKER扩展服务实现LocationListener{
//私有最终上下文mContext=getBaseContext();
//GPS状态标志
布尔值isGPSEnabled=false;
//网络状态标志
布尔值isNetworkEnabled=false;
//GPS状态标志
布尔值canGetLocation=false;
位置;//位置
双纬度;//纬度
双经度;//经度
//更改更新的最小距离(以米为单位)
私有静态最终长最小距离更改更新=1;
//更新之间的最短时间(以毫秒为单位)
私有静态最终长最小时间更新=60;
//声明位置管理器
受保护的LocationManager LocationManager;
//公共GPSTRACKER(上下文){
//this.mContext=上下文;
//}
//WakeLock WakeLock;
@凌驾
公共IBinder onBind(意图arg0){
返回null;
}
@凌驾
public void onCreate(){
super.onCreate();
//PowerManager pm=(PowerManager)getSystemService(Context.POWER\u服务);
//wakeLock=pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,“DoNotSleep”);
}
@凌驾
公共无效启动(Intent Intent,int startId){
Bundle extras=intent.getExtras();
如果(extras!=null&&!extras.isEmpty()){//具有解包的效果
字符串消息=intent.getStringExtra(“消息”);
字符串编号=intent.getStringExtra(“编号”);
//int pumber=Integer.parseInt(number.toString());
int p=0,j,i=1,t,success=0;
double[]d=新的double[1000];
匹配器m=Pattern.compile((?!=\\d\\\.\\d\\)([\\d.]+)”).Matcher(消息);
while(m.find())
{
double k=double.parseDouble(m组(1));
d[p]=k;
p++;
}
//if(消息包含(编号)){
//位置h=getLocation();
//纬度=h.getLatitude();
//经度=h.getLongitude();
//最终LocalBroadcastManager LocalBroadcastManager=
//getInstance(getBaseContext());
//意向。额外(“纬度”,纬度);
//意向。额外(“液化天然气”,经度);
//localBroadcastManager.sendBroadcast(new Intent());
// }
双线;
双人[]船=新双人[1000];
double[]b=新的double[1000];
ship[0]=SlopeCalc(d[2],d[0],d[3],d[1]);
b[0]=d[0]-船[0]*d[1];
如果(p>3)
{

因为(j=2;j看起来像是你在(true)
的时候从来没有突破过
,所以你一遍又一遍地调用
Location h=getLocation();
。读代码有点难,但是如果你在
onStart()中没有获得
success==1
那么这就可以解释你的问题了

看看帮助页面,看看你如何改进你的问题,这将帮助你获得更好更快的答案:谢谢……我只是对我的代码感到困惑,因为我在日志中没有看到任何错误,这很烦人……很抱歉回答得太长了。这在……之前有效(正确)是在服务中,应该在后台工作,并不断获得坐标,直到它将中断…有没有更好的主意,获得位置更新而不需要while循环?听起来你可能想要一个广播接收器之类的东西,看看哇好…我会检查出来谢谢:)
public class GPSTRACKER extends Service implements LocationListener {

    //private final Context mContext=getBaseContext();

    // flag for GPS status
    boolean isGPSEnabled = false;

    // flag for network status
    boolean isNetworkEnabled = false;

    // flag for GPS status
    boolean canGetLocation = false;

    Location location; // location

    double latitude;// latitude
    double longitude; // longitude

    // The minimum distance to change Updates in meters
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1; 

    // The minimum time between updates in milliseconds
    private static final long MIN_TIME_BW_UPDATES =  60 ; 

    // Declaring a Location Manager
    protected LocationManager locationManager;

    //public GPSTRACKER(Context context) {
        //this.mContext = context;
    //}
    //WakeLock wakeLock;

    @Override

    public IBinder onBind(Intent arg0) {

        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();

            //PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);

            //wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "DoNotSleep");
    }
    @Override
    public void onStart(Intent intent, int startId) {

        Bundle extras = intent.getExtras();

                if (extras != null && !extras.isEmpty()) {  // has effect of unparcelling Bundle

                    String message = intent.getStringExtra("message");
                    String number = intent.getStringExtra("number");
                  //int pumber= Integer.parseInt(number.toString());

                    int p=0,j,i=1,t,success=0;
                    double[] d = new double[1000];

                    Matcher m = Pattern.compile("(?!=\\d\\.\\d\\.)([\\d.]+)").matcher(message);

                    while(m.find())
                    {
                       double  k = Double.parseDouble(m.group(1));
                       d[p]=k;
                       p++;
                     }

                     //if (message.contains(number)){
                        // Location h=getLocation();
                        // latitude=h.getLatitude();
                         //longitude = h.getLongitude();
                        // final LocalBroadcastManager localBroadcastManager =
                                   // LocalBroadcastManager.getInstance(getBaseContext());
                                    //intent.putExtra("lat",latitude);
                                   // intent.putExtra("lng",longitude);
                                    //localBroadcastManager.sendBroadcast(new Intent());

                   // }
                     double line;
                     double[] ship = new double[1000] ;
                     double[] b = new double[1000] ;

                    ship[0]=SlopeCalc(d[2],d[0],d[3],d[1]);
                    b[0]=d[0]-ship[0]*d[1];


                    if (p>3)
                    {

                    for(j=2;j<p;j++)
                    {
                        if(j+2<p){
                        ship[i]=SlopeCalc(d[j+2],d[j-2+2],d[j+1+2],d[j-1+2]);
                        b[i]=d[j]-(ship[i]*d[j+1]);

                        j++;
                        i++;
                        }
                        else{
                            break;
                        }
                    }
                    }

                    while(true)
                    {
                     Location h=getLocation();
                     latitude=h.getLatitude();
                     longitude = h.getLongitude();
                     //System.out.println(latitude);
                    // System.out.println(longitude);
                    for (t=0;t<i;t++){
                    line=ship[t]*longitude+b[t]-latitude;

                    if (line>-0.001 && line<0.001){
                        success=1;
                        break;
                    }
                    }
                    if (success==1){
                    break;
                    }

                    }
                    if ( success==1){
                        SmsManager.getDefault().sendTextMessage(number, null, "HI WHATS UP DUDE HE IS THER", null, null);
                        //wakeLock.release();
                        stopService(intent);
                    }
                }
                else
                {
                    Log.i("Log", "Bundle is null");
                }
    }           

    public static double SlopeCalc(double y2,double y1, double x2,double x1){

        double sou;
        sou=(y2-y1)/(x2-x1);
        return sou;
    }


    /**
     * Stop using GPS listener
     * Calling this function will stop using GPS in your app
     * */
            public void stopUsingGPS(){
            if(locationManager != null){
            locationManager.removeUpdates((android.location.LocationListener) GPSTRACKER.this);
            }       
    }

    /**
     * Function to get latitude
     * */
    public double getLatitude(){
        if(location != null){
            latitude = location.getLatitude();
        }

        // return latitude
        return latitude;
    }

    /**
     * Function to get longitude
     * */
    public double getLongitude(){
        if(location != null){
            longitude = location.getLongitude();
        }

        // return longitude
        return longitude;
    }

    /**
     * Function to check GPS/wifi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }

    /**
     * Function to show settings alert dialog
     * On pressing Settings button will launch Settings Options
     * */
    //public void showSettingsAlert(){
        //AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

        // Setting Dialog Title
       // alertDialog.setTitle("GPS is settings");

        // Setting Dialog Message
       // alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?");

        // On pressing Settings button
       // alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() {
         //   public void onClick(DialogInterface dialog,int which) {
            //  Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                //mContext.startActivity(intent);
           // }
       // });

        // on pressing cancel button
       // alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        //    public void onClick(DialogInterface dialog, int which) {
          //  dialog.cancel();
           // }
        //});

        // Showing Alert Message
      //  alertDialog.show();
    //}

    @Override
    public void onLocationChanged(Location location) {
        //getLocation();
    }
    @Override
    public void onProviderDisabled(String provider) {
    }

    @Override
    public void onProviderEnabled(String provider) {
    }

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

    public Location getLocation() {
        locationManager = (LocationManager) 
                getSystemService(LOCATION_SERVICE);

         //getting GPS status
         isGPSEnabled = locationManager
                .isProviderEnabled(LocationManager.GPS_PROVIDER);

        // getting network status
        isNetworkEnabled = locationManager
                .isProviderEnabled(LocationManager.NETWORK_PROVIDER);


            if (isNetworkEnabled) {
                locationManager.requestLocationUpdates(
                        LocationManager.NETWORK_PROVIDER,
                        MIN_TIME_BW_UPDATES,
                        MIN_DISTANCE_CHANGE_FOR_UPDATES,  this);
            Log.d("Netork", "Network");
            if (locationManager != null) {
                location = locationManager
            .getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
        }
        }

            // if GPS Enabled get lat/long using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    locationManager.requestLocationUpdates(
                            LocationManager.GPS_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES,this );
                    Log.d("GPS Enabled", "GPS Enabled");
                    if (locationManager != null) {
                        location = locationManager
                                .getLastKnownLocation(LocationManager.GPS_PROVIDER);
                        }
                    }
                }

        return location;
    }

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