سؤال

I'm working on a program that works with GPS and checks user speed.But, Unfortunately, it never works and gives me force closes. I don't know what is the problem. Should I check the internet connection for it or.....?

Below is my code:- (there is some code for timer too but you can ignore it)

 package com.bestdiet;


import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Handler.Callback;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class Training extends Activity implements LocationListener {
    TextView text, text2, text3;
    long starttime = 0;
    //this  posts a message to the main thread from our timertask
    //and updates the textfield
   final Handler h = new Handler(new Callback() {

        @Override
        public boolean handleMessage(Message msg) {
           long millis = System.currentTimeMillis() - starttime;
           int seconds = (int) (millis / 1000);
           int minutes = seconds / 60;
           seconds     = seconds % 60;

           text.setText(String.format("%d:%02d", minutes, seconds,millis));
            return false;
        }
    });
   //runs without timer be reposting self
   Handler h2 = new Handler();
   Runnable run = new Runnable() {

        @Override
        public void run() {
           long millis = System.currentTimeMillis() - starttime;
           int seconds = (int) (millis / 1000);
           int minutes = seconds / 60;
           seconds     = seconds % 60;

     //      text3.setText(String.format("%d:%02d", minutes, seconds));

           h2.postDelayed(this, 500);
        }
    };

   //tells handler to send a message
   class firstTask extends TimerTask {

        @Override
        public void run() {
            h.sendEmptyMessage(0);
        }
   };

   //tells activity to run on ui thread
   class secondTask extends TimerTask {

        @Override
        public void run() {
            Training.this.runOnUiThread(new Runnable() {

                @Override
                public void run() {
                   long millis = System.currentTimeMillis() - starttime;
                   int seconds = (int) (millis / 1000);
                   int minutes = seconds / 60;
                   seconds     = seconds % 60;

                  // text2.setText(String.format("%d:%02d", minutes, seconds));
                }
            });
        }
   };


   Timer timer = new Timer();
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_training);

        this.setVolumeControlStream(AudioManager.STREAM_MUSIC);
            this.setVolumeControlStream(AudioManager.STREAM_RING);  
            this.setVolumeControlStream(AudioManager.STREAM_ALARM);  
            this.setVolumeControlStream(AudioManager.STREAM_NOTIFICATION);  
            this.setVolumeControlStream(AudioManager.STREAM_SYSTEM);  
        //  this.setVolumeControlStream(AudioManager.STREAM_VOICECALL);  





        text = (TextView)findViewById(R.id.textView1);
      //  text2 = (TextView)findViewById(R.id.text2);
       // text3 = (TextView)findViewById(R.id.text3);

        Button b = (Button)findViewById(R.id.button1);
        b.setText("start");
        b.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {
                Button b = (Button)v;
                if(b.getText().equals("stop")){
                    timer.cancel();
                    timer.purge();
                    h2.removeCallbacks(run);
                    b.setText("start");
                }else{
                    starttime = System.currentTimeMillis();
                    timer = new Timer();
                    timer.schedule(new firstTask(), 0,500);
                    timer.schedule(new secondTask(),  0,500);
                    h2.postDelayed(run, 0);
                    b.setText("stop");
                }
            }
        });
        ////////////////////////////////////////////////////////////
        Button bb=(Button)findViewById(R.id.button2);
    }

    @Override
    public void onBackPressed() {
        // TODO Auto-generated method stub
        super.onBackPressed();

    }

    @Override
    public void onPause() {
        super.onPause();
        timer.cancel();
        timer.purge();
        h2.removeCallbacks(run);
        Button b = (Button)findViewById(R.id.button);
        b.setText("start");
    }
@Override
protected void onDestroy() {
    // TODO Auto-generated method stub
    android.os.Process.killProcess(android.os.Process.myPid());
    super.onDestroy();


}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // TODO Auto-generated method stub
//  return super.onOptionsItemSelected(item);
    switch(item.getItemId())
    {
    case R.id.exit:
        finish();
        //System.exit(0);
        break;
    case R.id.help:
        Intent i=new Intent(Training.this,TrainingHelp.class);
        startActivity(i);
        break;
    //case R.id.options:
    //  Intent j= new Intent(MyTimer.this,prefs.class);
        //startActivity(j);
        //break;
    }
    return false;
}

@Override
public void onLocationChanged(Location loc) {
    // TODO Auto-generated method stub
    if(isonline()&&hasGPSEnabled() )
    {
      Float thespeed=loc.getSpeed();
      Toast.makeText(Training.this,String.valueOf(thespeed), Toast.LENGTH_LONG).show();
      TextView tt=(TextView)findViewById(R.id.textView3);
      tt.setText(""+thespeed);
      ImageView vv=(ImageView)findViewById(R.id.imageView1);

      if(thespeed<3)
      {
          vv.setImageResource(R.drawable.idle);
      }
      if(thespeed>=3&&thespeed<10)
      {
          vv.setImageResource(R.drawable.walking);
      }
      if(thespeed>=10)
      {
          vv.setImageResource(R.drawable.rinnung);
      }
    }
}


private boolean hasGPSEnabled() {
    LocationManager mlocManager = 
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
 boolean   isGPSEnabled = mlocManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);
    return isGPSEnabled;
}





private boolean isonline() {
    // TODO Auto-generated method stub
       ConnectivityManager cm =
                (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo netInfo = cm.getActiveNetworkInfo();
            if (netInfo != null && netInfo.isConnectedOrConnecting()) {
                return true;
            }
            return false;
}




@Override
public void onProviderDisabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onProviderEnabled(String arg0) {
    // TODO Auto-generated method stub

}

@Override
public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
    // TODO Auto-generated method stub

}
}
هل كانت مفيدة؟

المحلول

It might not return a speed. A speed isn't always available. If you are logging distance and time you can get speed as d/t. Your code doesn't look like it should produce an error. Maybe it's an ANR. Try initializing LocationListener off the UI thread.

// Check if device GPS is enabled.
// Must be true to proceed
private boolean hasGPSEnabled() {
    LocationManager mlocManager = 
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    isGPSEnabled = mlocManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);
    return isGPSEnabled;
}
// Check if device has network connection.
// Must be true to proceed
public boolean isOnline() {
    ConnectivityManager cm =
        (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo netInfo = cm.getActiveNetworkInfo();
    if (netInfo != null && netInfo.isConnectedOrConnecting()) {
        return true;
    }
    return false;
}
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top