我创建了一个户外导航应用程序。但为了证明我使用了模拟 GPS。但它现在不起作用。在我的应用程序中,这个类有 2 个按钮。当用户选择暂停按钮时,它会自动显示为开始。然后再次用户选择开始按钮,然后它将产生异常。这是我尝试开发的代码:
public class PathRecorderPauseActivity extends Activity implements
TextToSpeech.OnInitListener, OnLongClickListener, OnClickListener,
OnUtteranceCompletedListener {
private Button btnPause;
private TextView text;
private LocationManager manager;
private Button btnStop;
private boolean stop = true;
private LocationListener listener;
private boolean triger = true;
private boolean isIn = false;
private SQLiteOpenHelper dbHelper;
@SuppressWarnings("unused")
private Button btnShowDetails;
private MockGpsProvider mMockGpsProviderTask = null;
private Integer mMockGpsProviderIndex = 0;
private static final int MY_DATA_CHECK_CODE = 1234;
public static final String LOG_TAG = "MockGpsProviderActivity";
private static final String MOCK_GPS_PROVIDER_INDEX = "GpsMockProviderIndex";
// vibrator
//private Vibrator myVib;
private String speechText = "";
private TextToSpeech tts;
private ShakeListener mShaker;
private static final int REQUEST_CODE = 1234;
private static final String TAG = "VoiceRecognition";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pathrecorderpause);
Display display = getWindowManager().getDefaultDisplay();
int height = display.getHeight();
int width = display.getWidth();
if (savedInstanceState instanceof Bundle) {
mMockGpsProviderIndex = savedInstanceState.getInt(
MOCK_GPS_PROVIDER_INDEX, 0);
}
Intent checkIntent = new Intent();
checkIntent.setAction(TextToSpeech.Engine.ACTION_CHECK_TTS_DATA);
startActivityForResult(checkIntent, MY_DATA_CHECK_CODE);
dbHelper = new DbConnect(this);
SQLiteDatabase db = dbHelper.getWritableDatabase();
/*
* db.execSQL("DROP TABLE tblPathInfo");
* db.execSQL("DROP TABLE tblPath");
*/
db.execSQL("CREATE TABLE IF NOT EXISTS "
+ "tblPath(pathId INTEGER PRIMARY KEY," + "source VARCHAR, "
+ "destination VARCHAR, " + "startTime VARCHAR, "
+ "endTime VARCHAR, " + "distance DOUBLE);");
db.execSQL("CREATE TABLE IF NOT EXISTS "
+ "tblPathInfo(infoId INTEGER PRIMARY KEY,"
+ "pathId INTERGER, " + "lat DOUBLE, " + "lon DOUBLE, "
+ "curLocation VARCHAR);");
SimpleDateFormat sdf = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String curentDateandTime = sdf.format(new Date());
Log.d("Time", curentDateandTime);
db.execSQL("INSERT INTO tblPath (pathId,distance,startTime) VALUES ((SELECT max(pathId) FROM tblPath) + 1 ,0,'"
+ curentDateandTime + "')");
db.close();
btnPause = (Button) findViewById(R.id.btnPause);
btnPause.setOnLongClickListener(this);
btnPause.setOnClickListener(this);
// btnPause.setOnTouchListener(this);
btnStop = (Button) findViewById(R.id.btnStop);
btnStop.setOnLongClickListener(this);
btnStop.setOnClickListener(this);
// btnStop.setOnTouchListener(this);
// vibration
/*myVib = (Vibrator) this.getSystemService(VIBRATOR_SERVICE);
int dot = 200;
int long_gap = 100;
long[] pattern = { 0, // Start immediately
dot, long_gap, dot, long_gap, dot, long_gap, dot, long_gap
};*/
// Only perform this pattern one time (-1 means "do not repeat")
//myVib.vibrate(pattern, -1);
// vibration closed
mShaker = new ShakeListener(this);
mShaker.setOnShakeListener(new ShakeListener.OnShakeListener() {
public void onShake() {
if (tts.isSpeaking()) {
tts.stop();
}
}
});
final TextView tv = (TextView) findViewById(R.id.textView7);
tv.setText(String.valueOf(height) + "X" + String.valueOf(width));
View vw = (View) findViewById(R.id.view1); // middle one
vw.setOnTouchListener(new OnTouchListener() {
public boolean onTouch(View view, MotionEvent event) {
if (event.getAction() == android.view.MotionEvent.ACTION_MOVE) {
Log.d("TouchTest", "ACTION_MOVE");
tv.setText(String.valueOf(event.getX()) + " X "
+ String.valueOf(event.getY()));
if ((event.getX() >= 15 && event.getX() <= 305)
&& (event.getY() >= 60 && event.getY() <= 224)) {
if (isIn == false) {
PathRecorderActivity.tts.speak("Stop",
TextToSpeech.QUEUE_FLUSH, null);
isIn = true;
}
}
else if ((event.getX() >= 15 && event.getX() <= 310)
&& (event.getY() >= 245 && event.getY() <= 403)) {
if (isIn == false) {
PathRecorderActivity.tts.speak("Pause",
TextToSpeech.QUEUE_FLUSH, null);
isIn = true;
}
}
else {
isIn = false;
}
}
return true;
}
});
if (AppConstants.VoiceOrTouch.vot == 1) {
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(new Intent(
RecognizerIntent.ACTION_RECOGNIZE_SPEECH), 0);
if (activities.size() != 0) {
// startVoiceRecognitionActivity();
}
}
manager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new LocationListener() {
private JSONObject currentLocJSON;
private String currentLocationInfo;
private String locationName;
public void onStatusChanged(String provider, int status,
Bundle extras) {
}
public void onProviderEnabled(String provider) {
}
public void onProviderDisabled(String provider) {
}
public void onLocationChanged(Location location) {
Log.i("currentLocationInfo -- ", location.getLatitude() + " : "
+ location.getLongitude());
/*
* text = (TextView) findViewById(R.id.textView7);
*
* text.setText("Latitude : " + location.getLatitude() +
* "X Longitude : " + location.getLongitude());
*/
currentLocationInfo = MapConstants.GetConstantLocationInfo(
location.getLatitude(), location.getLongitude());
//if (currentLocationInfo == null) {
// currentLocJSON = getLocationInfoAsJSON(
// location.getLatitude(), location.getLongitude());
// currentLocationInfo = getLocationInfo(currentLocJSON);
//}
Log.i("currentLocationInfo -- ", currentLocationInfo);
Toast.makeText(getApplicationContext(), currentLocationInfo,
Toast.LENGTH_SHORT).show();
insertLocationDatailsToDB(location, currentLocationInfo);
}
private void insertLocationDatailsToDB(Location location,
String currentLocationInfo) {
double latOld = 0;
double lonOld = 0;
double newDistance;
text.setText("Current Location = " + currentLocationInfo
+ " | Latitude = " + location.getLatitude()
+ " | Longitude = " + location.getLongitude());
// Log.i("insertLocationDatailsToDB", "4");
SQLiteDatabase db = dbHelper.getWritableDatabase();
// Log.i("insertLocationDatailsToDB", "5");
// check if there a source name inserted pathTbl
if (triger == true) {
// Log.i("insertLocationDatailsToDB", "6");
db.execSQL("UPDATE tblPath SET source = '"
+ currentLocationInfo
+ "' WHERE pathId = (SELECT max(pathId) FROM tblPath);");
db.execSQL("INSERT INTO tblPathInfo (infoId,pathId,lat,lon,curLocation) VALUES ((SELECT max(infoId) FROM tblPathInfo) + 1 ,"
+ "(SELECT max(pathId) FROM tblPath),"
+ location.getLatitude()
+ ", "
+ location.getLongitude()
+ ",'"
+ currentLocationInfo + "' )");
triger = false;
} else {
// Log.i("insertLocationDatailsToDB", "7");
db.execSQL("INSERT INTO tblPathInfo (infoId,pathId,lat,lon,curLocation) VALUES ((SELECT max(infoId) FROM tblPathInfo) + 1 ,"
+ "(SELECT max(pathId) FROM tblPath),"
+ location.getLatitude()
+ ", "
+ location.getLongitude()
+ ",'"
+ currentLocationInfo + "' )");
Cursor cur = db
.rawQuery(
"SELECT lat,lon,pathId FROM tblPathInfo WHERE pathId = (SELECT max(pathId) FROM tblPath) AND "
+ "infoId=((SELECT max(infoId) FROM tblPathInfo) - 1);",
null);
if (cur.moveToNext()) {
latOld = cur.getDouble(0);
lonOld = cur.getDouble(1);
AppConstants.DataConstants.SELECTED_PATH_ID = cur
.getString(2);
}
Location oldLoc = new Location("oldLocation");
oldLoc.setLatitude(latOld);
oldLoc.setLongitude(lonOld);
newDistance = location.distanceTo(oldLoc);
db.execSQL("UPDATE tblPath SET distance = distance + "
+ newDistance
+ " WHERE pathId = (SELECT max(pathId) FROM tblPath);");
}
db.close();
}
/**
*
* @param currentLocJSON
* this is JSON object which contains the location
* details according to the passed Latitude & Longitude
* value..
* @return String result which should be the location name which we
* requested and returned as JSON from google api's We split
* the most suitable result from the JSON request
*/
private String getLocationInfo(JSONObject currentLocJSON) {
JSONArray jArray = null;
try {
jArray = currentLocJSON.getJSONArray("results");
// Check is there any details available by checking the JSON
// request
if (jArray.length() != 0) {
for (int i = 0; i < jArray.length(); i++) {
locationName = jArray.getJSONObject(0)
.getJSONArray("address_components")
.getJSONObject(i).getString("long_name");
if (locationName != null) {
Toast.makeText(getApplicationContext(),
locationName, Toast.LENGTH_SHORT)
.show();
break;
}
}
}
} catch (JSONException e) {
text.setText("JSONException");
e.printStackTrace();
}
return locationName;
}
/**
*
* @param latitude
* @param longitude
* @return JSON Object This function get latitude & longitude and
* pass them in to the maps.googleapis.com server and get
* location details as JSON result
*/
private JSONObject getLocationInfoAsJSON(double latitude,
double longitude) {
StringBuilder stringBuilder = new StringBuilder();
try {
HttpPost httppost = new HttpPost(
"http://maps.googleapis.com/maps/api/geocode/json?latlng="
+ latitude + "," + longitude
+ "&sensor=true");
HttpClient client = new DefaultHttpClient();
HttpResponse response;
stringBuilder = new StringBuilder();
response = client.execute(httppost);
HttpEntity entity = response.getEntity();
InputStream stream = entity.getContent();
int b;
while ((b = stream.read()) != -1) {
stringBuilder.append((char) b);
}
} catch (ClientProtocolException e) {
text.setText("ClientProtocolException");
} catch (IOException e) {
text.setText("IOException");
} catch (Exception e) {
text.setText("Exception");
}
JSONObject jsonObject = new JSONObject();
try {
jsonObject = new JSONObject(stringBuilder.toString());
} catch (JSONException e) {
text.setText("JSONException");
e.printStackTrace();
}
return jsonObject;
}
};
if (manager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0,
listener);
} else if (!manager
.isProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER)) {
manager.addTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER, false,
false, false, false, true, false, false, 0, 5);
manager.setTestProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER,
true);
}
if (manager.isProviderEnabled(MockGpsProvider.GPS_MOCK_PROVIDER)) {
manager.requestLocationUpdates(MockGpsProvider.GPS_MOCK_PROVIDER,
0, 0, listener);
try {
List<String> data = new ArrayList<String>();
Log.d("LeeInuka", "1");
InputStream is = getAssets().open("mock_gps_data.csv");
BufferedReader reader = new BufferedReader(
new InputStreamReader(is));
Log.d("LeeInuka", "2");
String line = null;
while ((line = reader.readLine()) != null) {
data.add(line);
// Log.d("Lee", line);
Log.d("LeeInuka", "3");
}
Log.d("LeeInuka", "4");
String[] coordinates = new String[data.size()];
data.toArray(coordinates);
mMockGpsProviderTask = new MockGpsProvider();
mMockGpsProviderTask.execute(coordinates);
} catch (Exception e) {
Log.d("MOKE", "........");
}
}
// manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 10,
// listener);
/***
* Pause/Start Recording Button
*/
btnPause = (Button) findViewById(R.id.btnPause);
/***
* Stop Recording Button
*/
btnStop = (Button) findViewById(R.id.btnStop);
btnShowDetails = (Button) findViewById(R.id.button1);
}
@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// store where we are before closing the app, so we can skip to the
// location right away when restarting
savedInstanceState.putInt(MOCK_GPS_PROVIDER_INDEX,
mMockGpsProviderIndex);
super.onSaveInstanceState(savedInstanceState);
}
// Tharika changed vibration
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnPause:
tts.speak("Pause", TextToSpeech.QUEUE_FLUSH, null);
// myVib.vibrate(100);
break;
case R.id.btnStop:
tts.speak("Stop", TextToSpeech.QUEUE_FLUSH, null);
// myVib.vibrate(100);
break;
default:
break;
}
}
public boolean onLongClick(View v) {
switch (v.getId()) {
case R.id.btnPause:
if (stop) {
stop = false;
// Log.d("btn_stop", "Path Recording has been Paused");
btnPause.setBackgroundResource(R.drawable.btn_start);
tts.speak("Path Recording has been Paused",
TextToSpeech.QUEUE_FLUSH, null);
Toast.makeText(getApplicationContext(),
"Path Recording has been Paused", Toast.LENGTH_LONG)
.show();
manager.removeUpdates(listener);
}
else {
manager.requestLocationUpdates(
MockGpsProvider.GPS_MOCK_PROVIDER, 0, 0, listener);
btnPause.setBackgroundResource(R.drawable.btn_pause);
tts.speak("Path Recording has been started",
TextToSpeech.QUEUE_FLUSH, null);
stop = true;
}
break;
case R.id.btnStop:
Toast.makeText(getApplicationContext(),
"Path Recording has been Stoped", Toast.LENGTH_LONG).show();
tts.speak("Path Recording has been Stoped",
TextToSpeech.QUEUE_FLUSH, null);
try {
mMockGpsProviderTask.cancel(true);
mMockGpsProviderTask = null;
} catch (Exception e) {
}
try {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager
.removeTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER);
} catch (Exception e) {
}
manager.removeUpdates(listener);
SQLiteDatabase db = dbHelper.getWritableDatabase();
SimpleDateFormat sdf_1 = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
String curentEndDateandTime = sdf_1.format(new Date());
db.execSQL("UPDATE tblPath SET destination = (SELECT curLocation FROM tblPathInfo WHERE infoId = (SELECT max(infoId) FROM tblPathInfo) ) , endTime = '"
+ curentEndDateandTime
+ "' WHERE pathId = (SELECT max(pathId) FROM tblPath);");
db.close();
db = dbHelper.getReadableDatabase();
Cursor cu2 = db.rawQuery("SELECT max(pathId) FROM tblPath;", null);
if (cu2.moveToNext()) {
AppConstants.DataConstants.SELECTED_PATH_ID = cu2.getString(0);
}
db.close();
startActivity(new Intent(PathRecorderPauseActivity.this,
ShortCutPathActivity.class));
Toast.makeText(getApplicationContext(),
"Path has been recorded successfully", Toast.LENGTH_LONG);
finish();
break;
case R.id.button1:
String testData = "";
String testData1 = "";
db = dbHelper.getReadableDatabase();
Cursor cu = db
.rawQuery(
"SELECT * FROM tblPathInfo WHERE pathId = (SELECT max(pathId) FROM tblPath);",
null);
while (cu.moveToNext()) {
testData = testData + " ********** currentLoc : "
+ cu.getString(4) + " & lat : " + cu.getString(2)
+ " & lon : " + cu.getString(3);
}
Toast.makeText(getApplicationContext(), testData,
Toast.LENGTH_SHORT).show();
Cursor cu1 = db
.rawQuery(
"SELECT * FROM tblPath WHERE pathId = (SELECT max(pathId) FROM tblPath);",
null);
if (cu1.moveToNext()) {
testData1 = cu1.getString(0) + " | " + cu1.getString(1) + " | "
+ " | " + cu1.getString(2) + " | " + cu1.getString(3)
+ " | " + cu1.getString(4) + " | " + cu1.getString(5);
}
Toast.makeText(getApplicationContext(), testData1,
Toast.LENGTH_LONG).show();
db.close();
default:
break;
}
return true;
}
public void onInit(int status) {
if (AppConstants.VoiceOrTouch.vot == 0) {
tts.speak(
"Service is runing.Panel 3.It has two buttons.First button is Stop"
+ "It is top on the screen.Second button is Pause.It is bottom on the screen."
+ "If you choose stop it will stop the recording."
+ "And if you choose Pause it will temporally stop the recording."
+ "Please touch or give single tap to identify the buttons."
+ "Please long press the button that you want to navigate.",
TextToSpeech.QUEUE_FLUSH, null);
}
else if (AppConstants.VoiceOrTouch.vot == 1) {
speechText = "Panel 3.It has two options as stop and paues."
+ "Please say stop to stop the recording path."
+ "Please say pause to pause the recording path.";
HashMap<String, String> hm = new HashMap<String, String>();
hm.put(TextToSpeech.Engine.KEY_PARAM_UTTERANCE_ID, "ourVoice");
tts.setOnUtteranceCompletedListener(this);
tts.speak(speechText, TextToSpeech.QUEUE_FLUSH, hm);
}
if (status == TextToSpeech.SUCCESS) {
if (tts.isLanguageAvailable(Locale.US) == TextToSpeech.LANG_AVAILABLE)
tts.setLanguage(Locale.US);
} else if (status == TextToSpeech.ERROR) {
Toast.makeText(this, "Sorry! Text To Speech failed...",
Toast.LENGTH_LONG).show();
}
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == MY_DATA_CHECK_CODE) {
if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_PASS) {
// success, create the TTS instance
tts = new TextToSpeech(this, this);
}
}
else if (requestCode == REQUEST_CODE && resultCode == RESULT_OK
&& AppConstants.VoiceOrTouch.vot == 1) {
// Log.d("Here", "Here");
ArrayList<String> matches = data
.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
for (String bestMatch : matches) {
if (bestMatch.contains("stop") || bestMatch.contains("sup")
|| bestMatch.contains("pop")
|| bestMatch.contains("map")) {
Intent my = new Intent(getApplicationContext(),
RecordingDetailsActivity.class);
startActivityForResult(my, 0);
break;
}
else if (bestMatch.contains("Pause")
|| bestMatch.contains("false")
|| bestMatch.contains("fox")
|| bestMatch.contains("post")
|| bestMatch.contains("font")) {
// Intent my = new Intent(getApplicationContext(),
// PathRecorderPause.class);
// startActivityForResult(my, 0);
break;
}
else {
// Log.i(TAG, "COMMAND_NOT_MATCHING");
}
}
}
else if (resultCode == TextToSpeech.Engine.CHECK_VOICE_DATA_MISSING_DATA) {
// missing data, install it
Intent installIntent = new Intent();
installIntent
.setAction(TextToSpeech.Engine.ACTION_INSTALL_TTS_DATA);
startActivity(installIntent);
}
super.onActivityResult(requestCode, resultCode, data);
}
public void onDestroy() {
super.onDestroy();
if (tts != null) {
tts.stop();
tts.shutdown();
}
try {
mMockGpsProviderTask.cancel(true);
mMockGpsProviderTask = null;
} catch (Exception e) {
Log.d("mMockGpsProviderTask", e.getMessage());
}
try {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager
.removeTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER);
} catch (Exception e) {
Log.d("LocationManager", e.getMessage());
}
}
@Override
public void onResume() {
mShaker.resume();
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onResume();
}
@Override
public void onPause() {
mShaker.pause();
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onPause();
try {
mMockGpsProviderTask.cancel(true);
mMockGpsProviderTask = null;
} catch (Exception e) {
}
try {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager
.removeTestProvider(MockGpsProvider.GPS_MOCK_PROVIDER);
} catch (Exception e) {
}
}
private class MockGpsProvider extends AsyncTask<String, Integer, Void> {
public static final String LOG_TAG = "GpsMockProvider";
public static final String GPS_MOCK_PROVIDER = "GpsMockProvider";
/** Keeps track of the currently processed coordinate. */
public Integer index = 0;
@Override
protected Void doInBackground(String... data) {
for (String str : data) {
if (index < mMockGpsProviderIndex) {
index++;
continue;
}
publishProgress(index);
Double latitude = null;
Double longitude = null;
Double altitude = null;
try {
String[] parts = str.split(",");
latitude = Double.valueOf(parts[0]);
longitude = Double.valueOf(parts[1]);
altitude = Double.valueOf(parts[2]);
} catch (NullPointerException e) {
break;
} catch (Exception e) {
continue;
}
Location location = new Location(GPS_MOCK_PROVIDER);
location.setLatitude(latitude);
location.setLongitude(longitude);
location.setAltitude(altitude);
location.setTime(System.currentTimeMillis());
Log.d(LOG_TAG + "-Inuka", location.toString());
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
locationManager.setTestProviderLocation(GPS_MOCK_PROVIDER,
location);
try {
Log.d(LOG_TAG + "_Traed", "22222");
Thread.sleep(5000);
Log.d(LOG_TAG + "_Traed", "22222w");
if (Thread.currentThread().isInterrupted())
throw new InterruptedException("");
} catch (InterruptedException e) {
Log.d(LOG_TAG + "_Traed", "Exception " + e.getMessage());
break;
}
index++;
}
return null;
}
@Override
protected void onProgressUpdate(Integer... values) {
Log.d(LOG_TAG + "-2Inuka", "onProgressUpdate(): " + values[0]);
mMockGpsProviderIndex = values[0];
}
}
public void onUtteranceCompleted(String utteranceId) {
Log.d("TTS", "On Finish()");
startVoiceRecognitionActivity();
tts.shutdown();
tts = null;
}
private void startVoiceRecognitionActivity() {
Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_PROMPT, "");
startActivityForResult(intent, REQUEST_CODE);
}
}