Android应用程序自动关闭
问题描述:
我写了一个Android应用程序,它将GPS数据定期发送到Web服务器。我使用Android的locationmanager和httpget类。Android应用程序自动关闭
它的工作正常。但问题是应用程序神秘地关闭,没有任何错误消息不调用活动关闭方法。我甚至将我的活动屏幕始终打开,以便屏幕在超时后不会熄灭。此外,我还通过覆盖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梭哈io为这些。我使用的是目标版本2.3.3(API 10),因为我的手机没有更高的Android版本。
请让我知道,如果有任何事情我错过了。在几个HttpGet发送之后,它神秘崩溃而没有任何通知。
答
我不认为这与特定的开发环境及其相关编码有任何关系。我认为这纯粹是一个Android问题。我开发了两个测试应用程序,一个使用位置传感器控件,另一个使用Android API。收集GPS信息并在两次读数后都崩溃。你从来没有在iOS上看到这个问题(但是,在某些地区iOS成功的情况下,它在其他领域失败了)。
在我看来,Android和iOS仍然是婴儿,并且正在经历重大的成熟问题,并且很难相信将任何外来特征编码到应用程序中。
将您的设备置于调试模式,并检查logcat是否有任何异常。你做到了吗? – Blacklight 2015-03-13 12:57:47
您的应用程序是否具有在屏幕上可见的活动,尽管它已关闭?或者它只是在后台运行(在这种情况下,您需要一个前台服务才能有机会不被系统杀死)。 – JHH 2015-03-13 13:00:46
@Blacklight 不,我没有做到。其实它很难把它放在调试模式和测试。 GPS信号只能在室外得到,所以连接到PC并测试很困难。 – Partha 2015-03-13 13:00:48