我编写了一个Android应用程序,定期将GPS数据发送到Web服务器。我使用过locationmanager和Android的httpget类。
工作正常。但问题是应用程序神秘地关闭,没有任何错误消息没有调用活动关闭方法。我甚至将活动屏幕设置为常亮,以便屏幕在超时后永不熄灭。此外,我通过覆盖它们在onClose或onDestroy方法中添加了一些振动功能,这样当应用程序关闭时,我可以将错误日志写入文件。
但仍然没有发生任何事。这些方法根本没有调用,应用程序神秘地关闭。
该应用程序可以运行一段时间。我通过打开GPS和3G进行测试,然后走进街道一段时间。但是当我到家时,我发现该应用程序已经关闭。
如果我错过了一些处理或内存溢出,请帮助他吗?
这是我的源代码
MainActivity.java
package com.test.partha1.gps1;
import android.app.*;
import android.content.*;
import android.location.*;
import android.os.*;
import android.view.*;
import android.widget.*;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import org.apache.http.HttpResponse;
import org.apache.http.client.*;
import org.apache.http.client.methods.*;
import org.apache.http.impl.client.DefaultHttpClient;
import java.io.*;
import java.net.*;
import java.util.*;
public class MainActivity extends Activity implements LocationListener {
Button urlBtn;
ToggleButton toggleBtn;
TextView txt1;
TextView urlServer;
long prevTime = -1;
double prevLatitude;
double prevLongitude;
boolean isGPSEnabled = false;
int count = 0;
protected LocationManager locationManager;
RandomAccessFile outFile;
String TimeStamp = "";
String UserID = "4084";
String server = "http://www.parthasarathimishra.com";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File externalStorageDir = Environment.getExternalStorageDirectory();
File myFile = new File(externalStorageDir, "ErrLogFile.txt");
txt1 = (TextView) findViewById(R.id.gpsVal);
urlServer = (TextView) findViewById(R.id.urlTxt);
urlBtn = (Button) findViewById(R.id.urlBtn);
urlBtn.setOnClickListener(urlBtnClick);
toggleBtn = (ToggleButton) findViewById(R.id.toggleButton);
try
{
if(!myFile.exists())
{
myFile.createNewFile();
}
outFile = new RandomAccessFile(myFile, "rw");
outFile.seek(myFile.length());
}
catch(Exception e)
{
txt1.setText(e.getMessage());
}
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
}
@Override
public void onStop () {
try
{
outFile.close();
}
catch(Exception e)
{
}
super.onStop();
}
@Override
protected void onDestroy()
{
Vibrator v = (Vibrator)this.getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(2000);
super.onDestroy();
}
@Override
public void onLocationChanged(Location location) {
if(!urlBtn.isEnabled() && ((prevTime == -1) || (System.currentTimeMillis() - prevTime >= 10000)))
{
try
{
UpdateTimeStamp();
connectWithHttpGet(String.valueOf(location.getLatitude()), String.valueOf(location.getLongitude()), TimeStamp);
prevTime = System.currentTimeMillis();
prevLatitude = location.getLatitude();
prevLongitude = location.getLongitude();
txt1.setText(String.valueOf(prevLatitude) + "/" + String.valueOf(prevLongitude));
}
catch(Exception e)
{
txt1.setText(e.getMessage());
try
{
outFile.writeBytes("\r\n" + e.getMessage());
}
catch (Exception e2)
{
txt1.setText(e2.getMessage());
}
}
}
else
{
txt1.setText("");
}
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
txt1.setText("GPS ON");
isGPSEnabled = true;
}
@Override
public void onProviderDisabled(String provider) {
txt1.setText("GPS OFF");
isGPSEnabled = false;
}
private boolean isNetworkAvailable()
{
ConnectivityManager connectivityManager
= (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
return activeNetworkInfo != null && activeNetworkInfo.isConnected();
}
private void UpdateTimeStamp()
{
Date date = new Date();
date.setTime(System.currentTimeMillis());
String cTime = date.toString();
Calendar cal = Calendar.getInstance();
String day = cTime.split(" ")[2];
String month = String.valueOf(cal.MONTH);
String year = cTime.split(" ")[cTime.split(" ").length - 1];
String hr = cTime.split(" ")[3].split(":")[0];
String min = cTime.split(" ")[3].split(":")[1];
String sec = cTime.split(" ")[3].split(":")[2];
TimeStamp = day + "," + month + "," + year + "," + hr + "," + min + "," + sec;
}
private View.OnClickListener urlBtnClick = new View.OnClickListener() {
@Override
public void onClick(View v) {
server = urlServer.toString();
}
};
public void toggleBtnChange(View view)
{
boolean on = ((ToggleButton)view).isChecked();
if(on)
{
if(isNetworkAvailable())
{
urlBtn.setEnabled(false);
urlServer.setEnabled(false);
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, this);
}
else
{
txt1.setText("No Network!! Enable the Network Connectivity.");
}
}
else
{
urlBtn.setEnabled(true);
urlServer.setEnabled(true);
locationManager.removeUpdates(this);
}
}
private void connectWithHttpGet(final String pLatitude, final String pLongitude, final String timeStamp) {
class HttpGetAsyncTask extends AsyncTask<String, Void, String>{
String url = "";
String Lat = pLatitude;
String Lng = pLongitude;
String tStamp = timeStamp;
@Override
protected String doInBackground(String... params) {
url = server + "/" + UserID + "/add.php?lat=" +
Lat + "&long=" + Lng + "&time=" + tStamp;
try
{
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(url);
HttpResponse httpResponse = httpClient.execute(httpGet);
int status = httpResponse.getStatusLine().getStatusCode();
if(status != 200)
{
txt1.setText("Unable to Send");
}
}
catch(Exception e)
{
txt1.setText(e.getMessage());
try
{
outFile.writeBytes("\r\n" + e.getMessage());
}
catch (Exception e2)
{
txt1.setText(e2.getMessage());
}
}
return "";
}
@Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
}
}
// Initialize the AsyncTask class
HttpGetAsyncTask httpGetAsyncTask = new HttpGetAsyncTask();
// Parameter we pass in the execute() method is relate to the first generic type of the AsyncTask
// We are passing the connectWithHttpGet() method arguments to that
httpGetAsyncTask.execute(pLatitude, pLongitude);
}
@Override
protected void onResume(){
super.onResume();
}
}
activity_main.xml中
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity"
android:background="#ff3f3dad"
android:id="@+id/lay"
android:keepScreenOn="true">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Update URL"
android:id="@+id/urlBtn"
android:textColor="#ff000000"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/gpsVal"
android:textColor="#ffffffff"
android:textSize="10dp"
android:background="#ff000000"
android:layout_alignParentBottom="true"
android:layout_marginBottom="50dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true" />
<EditText
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/urlTxt"
android:text="www.parthasarathimishra.com"
android:textColor="#fffff500"
android:editable="true"
android:background="#ff000000"
android:layout_below="@+id/urlBtn"
android:layout_alignParentLeft="true"
android:layout_marginTop="41dp"
android:layout_alignParentRight="true" />
<ToggleButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="ON"
android:id="@+id/toggleButton"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="45dp"
android:onClick="toggleBtnChange" />
</RelativeLayout>
的AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.test.partha1.gps1" >
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.VIBRATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
</manifest>
我正在使用Android Studio。我使用的是目标版本2.3.3(API 10),因为我的手机中没有更高版本的Android版本。
如果我遗漏了任何事情,请告诉我。在HttpGet发送之后,它没有任何通知就神秘地崩溃了。
答案 0 :(得分:0)
我认为这与特定的开发环境及其相关编码无关。我认为这纯粹是一个Android问题。我开发了2个测试应用程序,一个使用位置传感器控件,另一个使用Android API。两者都收集GPS信息,并在几次读数后崩溃。你永远不会在iOS中看到这个问题(但是,iOS在某些领域取得成功,在其他领域却很失败)。
在我看来,Android和iOS仍然是婴儿,并且正在经历严重的成熟问题,这使得很难相信将任何奇特的功能编码到应用程序中。