我的应用程序通过服务在后台运行。它每2分钟获取纬度,经度,电池状态,速度,高度和航向等数据,每隔3分钟推送一次数据。我用一个计时器。但是当打开相机,互联网,音乐播放器等任何东西时,它会抛出内存异常。
请帮我花很多时间 我的代码是
package com.Multiplex.gpstracking;
import java.io.IOException;
import java.io.InputStream;
import java.util.Timer;
import java.util.TimerTask;
import android.R.string;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import android.app.Activity;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.database.Cursor;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.location.GpsSatellite;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.os.Messenger;
import android.telephony.TelephonyManager;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.ViewGroup.LayoutParams;
import android.widget.Toast;
public class MyService extends Service implements SensorEventListener
{
int ll=1;
// now get altitude,no of satelight and Heading variables
int first_angel=0;
Boolean first_angel_flag=true;
LocationManager locationmanager;
private SensorManager mSensorManager;
private Sensor mCompass;
public static int Satellites = 0;
private static final String TAG = "MyService";
String serverResponse="";
DBAdapter db;
String latLongString="";
double ddlatitude=0.f;
double ddlongitude =0.f;
double ddaltitude=0.f;
double ddspeed=0.f;
InputStream xml_response=null;
String imeiID="";
String langitude="";
String longitude="";
String altitude="";
String batteryStatus="0";
String datetime="";
String speed="0";
String angle="0";
int isGPRS=0;
int isGPS=0;
int sync=0;
int int_speed=0;
String saved_id="";
String saved_imeiid="";
String saved_latitude="";
String saved_longitude="";
String saved_altitude="";
String saved_battery="";
String saved_time="";
String saved_angle="";
String saved_speed="";
String saved_satelllite="";
String saved_gps="";
String saved_gprs ="";
String succes_error="";
public IBinder onBind(Intent arg0)
{
return null;
}
private BroadcastReceiver mBatInfoReceiver = new BroadcastReceiver(){
@Override
public void onReceive(Context arg0, Intent intent) {
int level = intent.getIntExtra("level", 0);
batteryStatus=String.valueOf(level);
}
};
@Override
public void onCreate()
{
mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
mCompass = mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION);
}
public void onStart(Intent intent, int startId)
{
mSensorManager.registerListener(this, mCompass, SensorManager.SENSOR_DELAY_NORMAL);
timerOFRetriveData(5000,300000);
timerOFPussData(600000,600000);
}
@Override
public void onDestroy()
{
mSensorManager.unregisterListener(this);
}
// The following method is required by the SensorEventListener interface;
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
// The following method is required by the SensorEventListener interface;
// Hook this event to process updates;
public void onSensorChanged(SensorEvent event) {
float azimuth = Math.round(event.values[0]);
// The other values provided are:
// float pitch = event.values[1];
// float roll = event.values[2];
if(first_angel_flag)
{
first_angel=(int)azimuth;
first_angel_flag=false;
}
angle=Float.toString(azimuth);
int int_azimuth=(int)azimuth;
angle=String.valueOf(int_azimuth);
int angle_change=int_azimuth-first_angel;
angle_change=Math.abs(angle_change);
int retval =Double.compare(1.39, ddspeed);
//if(angle_change>90 && int_speed<5)
if(angle_change>90 && retval<0)
{
getDatAfter_30Sec();
PushData_afterInterval(600000);
}
else if(retval>0 && angle_change>30)
{
getDatAfter_30Sec();
PushData_afterInterval(300000);
}
}
public void getDatAfter_30Sec()
{
getBatteryStatus();
IMEI();
getUserLocationAndGPSstatus();
GPRSAvalibilty();
datetime=Config.currentTime();
db=new DBAdapter(getBaseContext());
db.open();
long i=db.insertTitle(imeiID, langitude, longitude, altitude, batteryStatus, datetime,isGPS,isGPRS,sync,speed,angle,Satellites);
System.out.println("value inserted "+i);
db.close();
}
public void PushData_afterInterval(int time)
{
final int delayTime=time;
db=new DBAdapter(getBaseContext());
db.open();
Cursor cc=db.getSearchRecord("0");
if(cc.getCount()==0)
{
//Toast.makeText(getApplicationContext(), "No Data Found",Toast.LENGTH_SHORT).show();
cc.close();
db.close();
}
else
{
while(cc.moveToNext())
{
saved_id =cc.getString(0);
saved_imeiid =cc.getString(1);
saved_latitude =cc.getString(2);
saved_longitude =cc.getString(3);
saved_altitude =cc.getString(4);
saved_battery =cc.getString(5);
saved_time =cc.getString(6);
saved_angle =cc.getString(7);
saved_speed =cc.getString(8);
saved_satelllite =cc.getString(9);
saved_gps =cc.getString(10);
saved_gprs =cc.getString(11);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isConnectedOrConnecting())
{
Thread thread = new Thread(new Runnable()
{
public void run()
{
try
{
Thread.sleep(delayTime);
senddatatoserver(saved_id,saved_imeiid,saved_latitude,saved_longitude,saved_altitude,saved_battery,saved_time,saved_gps,saved_gprs,saved_angle,saved_speed,saved_satelllite);
succes_error=parseServerResponse();
} catch (Exception e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
thread.start();
if(succes_error.equalsIgnoreCase("SUCCESS"))
{
int id=Integer.parseInt(saved_id);
db=new DBAdapter(getBaseContext());
db.open();
db.updateRow(id,1);
db.close();
}
}
else
{
//Toast.makeText(getBaseContext(), "No InterNet Available ", Toast.LENGTH_LONG).show();
}
}
cc.close();
db.close();
}
}
// Will be called asynchronously be Android
public void IMEI()
{
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imeiID = telephonyManager.getDeviceId();
}
public void getUserLocationAndGPSstatus()
{
locationmanager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);
String provider = locationmanager.GPS_PROVIDER;
Location location = locationmanager.getLastKnownLocation(provider);
boolean statusOfGPS = locationmanager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(statusOfGPS)
{
isGPS=1;
}
else
{
isGPS=0;
}
updatewithnewlocation(location);
GpsStatus.Listener gpsStatusListener = new GpsStatus.Listener()
{
public void onGpsStatusChanged(int event)
{
if (event == GpsStatus.GPS_EVENT_SATELLITE_STATUS || event == GpsStatus.GPS_EVENT_FIRST_FIX) {
GpsStatus status = locationmanager.getGpsStatus(null);
Iterable<GpsSatellite> sats = status.getSatellites();
// Check number of satellites in list to determine fix state
for (GpsSatellite sat : sats) {
//if(sat.usedInFix())
Satellites++;
}
Log.i("Setting Satellites from GpsStatusListener: " + Satellites,"***");
//Toast.makeText(getBaseContext(), "Setting Satellites from GpsStatusListener: " + Satellites, Toast.LENGTH_LONG).show();
//satelite.setText(""+Satellites);
}
}
};
locationmanager.addGpsStatusListener(gpsStatusListener);
final LocationListener locationlistener = new LocationListener() {
public void onLocationChanged(Location location) {
updatewithnewlocation(location);
}
public void onProviderDisabled(String provider){
updatewithnewlocation(null);
}
public void onProviderEnabled(String provider){ }
public void onStatusChanged(String provider, int status,
Bundle extras){ }
};
//locationmanager.requestLocationUpdates(provider, 2000, 10, locationlistener);
try
{
locationmanager.requestLocationUpdates(provider, 5000, 0, locationlistener);
}
catch(Exception e)
{
//Toast.makeText(getBaseContext(), "No provider found", Toast.LENGTH_LONG).show();
}
}
private void updatewithnewlocation(Location location)
{
// TODO Auto-generated method stub
if (location != null)
{
ddlatitude = location.getLatitude();
ddlongitude = location.getLongitude();
ddaltitude = location.getAltitude();
ddspeed =location.getSpeed();
langitude =String.valueOf(ddlatitude);
longitude =String.valueOf(ddlongitude);
altitude =String.valueOf(ddaltitude);
int_speed =(int)ddspeed;
speed =String.valueOf(int_speed);
System.out.println("******* lattiude "+langitude);
System.out.println("******* longitude "+longitude);
System.out.println("******* altitude "+altitude);
System.out.println("******* speed "+int_speed);
} else
{
langitude="0.0";
longitude="0.0";
altitude="0";
latLongString = "No location found";
int_speed=0;
}
}
public void getBatteryStatus()
{
this.registerReceiver(this.mBatInfoReceiver,new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
}
public void GPRSAvalibilty()
{
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isConnectedOrConnecting())
{
isGPRS=1;
}
else
{
isGPRS=0;
}
//Toast.makeText(getApplicationContext(), "isGPRS is "+isGPRS, Toast.LENGTH_LONG).show();
}
public void timerOFRetriveData(int delay_time,int interval_time)
{
Timer myTimerFirst = new Timer();
myTimerFirst.scheduleAtFixedRate( new TimerTask()
{
private Handler updateUI = new Handler(){
@Override
public void dispatchMessage(Message msg)
{
super.dispatchMessage(msg);
getBatteryStatus();
IMEI();
getUserLocationAndGPSstatus();
GPRSAvalibilty();
datetime=Config.currentTime();
System.out.println("Current time => "+datetime);
db=new DBAdapter(getBaseContext());
db.open();
//Toast.makeText(getBaseContext(), "Latitude is "+langitude+" longitude is "+longitude, Toast.LENGTH_LONG).show();
long i=db.insertTitle(imeiID, langitude, longitude, altitude, batteryStatus, datetime,isGPS,isGPRS,sync,speed,angle,Satellites);
System.out.println("value inserted "+i);
//Toast.makeText(getBaseContext(), "value inserted after 2 min "+i, Toast.LENGTH_LONG).show();
db.close();
}
};
public void run() {
try {
updateUI.sendEmptyMessage(0);
} catch (Exception e) {e.printStackTrace(); }
}
}, delay_time,interval_time);
} // close timer method
public void timerOFPussData(int delaytime,int intervaltime)
{
Timer myTimerSecond = new Timer();
myTimerSecond.scheduleAtFixedRate( new TimerTask()
{
private Handler updateUI = new Handler(){
@Override
public void dispatchMessage(Message msg)
{
super.dispatchMessage(msg);
db=new DBAdapter(getBaseContext());
db.open();
Cursor c=db.getSearchRecord("0");
if(c.getCount()==0)
{
//Toast.makeText(getApplicationContext(), "No Data Found",Toast.LENGTH_SHORT).show();
c.close();
db.close();
}
else
{
while(c.moveToNext())
{
saved_id =c.getString(0);
saved_imeiid =c.getString(1);
saved_latitude =c.getString(2);
saved_longitude =c.getString(3);
saved_altitude =c.getString(4);
saved_battery =c.getString(5);
saved_time =c.getString(6);
saved_angle =c.getString(7);
saved_speed =c.getString(8);
saved_satelllite =c.getString(9);
saved_gps =c.getString(10);
saved_gprs =c.getString(11);
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo info = cm.getActiveNetworkInfo();
if (info != null && info.isConnectedOrConnecting())
{
Thread readthread = new Thread(new Runnable()
{ public void run()
{
try
{
senddatatoserver(saved_id,saved_imeiid,saved_latitude,saved_longitude,saved_altitude,saved_battery,saved_time,saved_gps,saved_gprs,saved_angle,saved_speed,saved_satelllite);
succes_error=parseServerResponse();
} catch (Exception e) {
//TODO Auto-generated catch block
e.printStackTrace();
}
}
}
);
readthread.start();
if(succes_error.equalsIgnoreCase("SUCCESS"))
{
//Toast.makeText(getApplicationContext(), "Server succesfully accepted data "+ll, Toast.LENGTH_LONG).show();
ll++;
int id=Integer.parseInt(saved_id);
db=new DBAdapter(getBaseContext());
db.open();
db.updateRow(id,1);
db.close();
}
}
else
{
//Toast.makeText(getBaseContext(), "No InterNet Available ", Toast.LENGTH_LONG).show();
}
}
c.close();
db.close();
}
}
};
public void run() {
try {
updateUI.sendEmptyMessage(0);
} catch (Exception e) {e.printStackTrace(); }
}
}, delaytime,intervaltime);
} // close timer of pull data method
public void senddatatoserver(String saved_id,String saved_imeiid,String saved_latitude,String saved_longitude,String saved_altitude,String saved_battery,String saved_time,String saved_gps,String saved_gprs,String saved_angle,String saved_speed,String saved_satelllite)
{
try
{
HttpClient client = new DefaultHttpClient();
saved_time = saved_time.replace(" ", "%20");
String url = Config.url+"imieno="+saved_imeiid+"&lat="+saved_latitude+"&longitude="+saved_longitude+"&altitude="+saved_altitude+"&speed="+saved_speed+"&angle="+saved_angle+"&cTime="+saved_time+"&nosat="+saved_satelllite+"&IsGPS="+saved_gps+"&IsGPRS="+saved_gprs;
//url = url.replace(" ", "%20");
System.out.println("complete url is ***** "+url);
HttpGet httpGet = new HttpGet(url);
HttpResponse response = client.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
HttpEntity entity = response.getEntity();
xml_response=entity.getContent();
// do something with response
} else {
// handle bad response
}
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
}
}
public String parseServerResponse()
{
String responseStr="";
try
{
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(new InputSource(xml_response));
doc.getDocumentElement().normalize();
NodeList nodeList = doc.getElementsByTagName("PushGPSDataResponse");
for (int i = 0; i < nodeList.getLength(); i++) {
Node node = nodeList.item(i);
Element fstElmnt = (Element) node;
NodeList nameList = fstElmnt.getElementsByTagName("PushGPSDataResult");
Element nameElement = (Element) nameList.item(0);
nameList = nameElement.getChildNodes();
responseStr =((Node) nameList.item(0)).getNodeValue();
System.out.println("welcome "+responseStr);
//Toast.makeText(getBaseContext(), ""+responseStr , Toast.LENGTH_LONG).show();
}
}
catch (Exception e)
{
System.out.println("XML Pasing Excpetion = " + e);
}
return responseStr;
}
}
答案 0 :(得分:1)
狂野猜测:locationmanager.addGpsStatusListener(gpsStatusListener);
你最终会添加很多听众而永远不会删除它们。
我的建议,重构一遍,你应该:
DBSupport
类用于数据库访问ServerSupport
用于向您的服务器发送数据(这可能是一项服务) 使用更少的组件可以很容易地确保一切正常。