I'm having trouble converting coordinates to an actual address.
I have two variables that pull coordinates but I'm getting many errors when I tweak the code. The first error is "unreported exception IOException; must be caught or declared to be thrown" and then I add the try catch then another error pops up, "yourAddresses might not have been initialized.
I'm just trying to get the address, street, and city so I can append it into a textView.
#Override
public void onLocationChanged(Location location)
{
double latitude = location.getLongitude();
double longitude = location.getLatitude();
//t.append("\n " + location.getLongitude() + " " + location.getLatitude());
Geocoder geocoder;
List<Address> yourAddresses;
geocoder = new Geocoder(context, Locale.getDefault());
yourAddresses = geocoder.getFromLocation(latitude, longitude, 1);
if (yourAddresses.size() > 0) {
String yourAddress = yourAddresses.get(0).getAddressLine(0);
String yourCity = yourAddresses.get(0).getAddressLine(1);
String yourCountry = yourAddresses.get(0).getAddressLine(2);
}
}
Thanks!
I used this code and its works for me....
public void getAddressFromLocation(final double latitude, final double longitude,
final Context context, final Handler handler)
{
Thread thread = new Thread()
{
#Override
public void run()
{
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
Address address = null;
try
{
List<Address> addressList = geocoder.getFromLocation(latitude, longitude, 1);
if (addressList != null && addressList.size() > 0)
{
address = addressList.get(0);
}
}
catch (Exception e)
{
Log.e(TAG, "getAddressFromLocation:run: exception while getting address from location");
e.printStackTrace();
}
finally
{
Message message = Message.obtain();
message.setTarget(handler);
if (address != null)
{
message.what = 1;
Bundle bundle = new Bundle();
bundle.putString("thoroughFare", address.getThoroughfare());
bundle.putString("subThoroughFare", address.getSubThoroughfare());
bundle.putString("city", address.getLocality());
bundle.putString("state", address.getAdminArea());
bundle.putString("country", address.getCountryName());
bundle.putString("postalCode", address.getPostalCode());
bundle.putString("subAdminArea", address.getSubAdminArea());
bundle.putString("subLocality", address.getSubLocality());
message.setData(bundle);
}
else
{
message.what = 1;
Bundle bundle = new Bundle();
result = "Latitude: " + latitude + "Longitude: " + longitude +
"\n Unable to get address for this location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
This is my GeoCoderHandler class....
private class GeoCoderHandler extends Handler
{
#Override
public void handleMessage(Message msg)
{
switch (msg.what)
{
case 1:
String address = "";
Bundle bundle = msg.getData();
if (bundle.getString("subThoroughFare") != null)
{
if (!bundle.getString("subThoroughFare").equalsIgnoreCase("null"))
{
address = bundle.getString("subThoroughFare") + ", " +
bundle.getString("thoroughFare");
}
}
else
{
address = bundle.getString("thoroughFare");
}
tvAddress1.setText("");
tvAddress1.setText(address);
tvAddress2.setText("");
tvAddress2.setText(bundle.getString("subLocality"));
tvAddress3.setText("");
tvAddress3.setText(bundle.getString("subAdminArea"));
edtPinCode.setText("");
edtPinCode.setText(bundle.getString("postalCode"));
tvCity.setText("");
tvCity.setText(bundle.getString("city"));
tvState.setText("");
tvState.setText(bundle.getString("state"));
tvCountry.setText("");
tvCountry.setText(bundle.getString("country"));
break;
default:
tvAddress1.setText(getResources().getString(R.string.address_not_found));
tvAddress2.setText("");
tvAddress3.setText("");
edtPinCode.setText("");
tvCity.setText("");
tvState.setText("");
tvCountry.setText("");
break;
}
}
}
your need some initialized for yourAddress
List<Address> yourAddresses = new ArrayList();
I was working with geocoder in my android app to get country name using latitude and longitude. I found that it was working good in kitkat version and below. But when i test my app in above versions it was giving null. So my question is simple that how to use geocoder above kitkat versions.
If there is any other better option instead of geocoder then please suggest me!
Thanks in advance!
I post my code for Geocoder. Follow it
//Keep this GeocodingLocation.java in a separate file.
public class GeocodingLocation {
private static final String TAG = "GeocodingLocation";
public static void getAddressFromLocation( final String locationAddress,
final Context context, final Handler handler) {
Thread thread = new Thread() {
#Override
public void run() {
Geocoder geocoder = new Geocoder(context, Locale.getDefault());
String result = null;
String latitude = null;
String longitude = null;
try {
List<Address> addressList = geocoder.getFromLocationName(locationAddress, 1);
if (addressList != null && addressList.size() > 0) {
Log.e("GeocodingLocation --> getAddressFromLocation ==>" +
addressList.toString());
Address address = (Address) addressList.get(0);
StringBuilder sb = new StringBuilder();
latitude = String.valueOf(address.getLatitude());
longitude = String.valueOf(address.getLongitude());
Logger.infoLog("GeocodingLocation --> Lat & Lang ==>" + latitude +" "+longitude);
//sb.append(address.getLatitude()).append("\n");
//sb.append(address.getLongitude()).append("\n");
}
} catch (IOException e) {
Log.e(TAG, "Unable to connect to Geocoder", e);
} finally {
Message message = Message.obtain();
message.setTarget(handler);
if (latitude != null && longitude != null) {
message.what = 1;
Bundle bundle = new Bundle();
bundle.putString("latitude", latitude);
bundle.putString("longitude", longitude);
message.setData(bundle);
} else {
message.what = 1;
Bundle bundle = new Bundle();
result = "Address: " + locationAddress +
"\n Unable to get Latitude and Longitude for this address location.";
bundle.putString("address", result);
message.setData(bundle);
}
message.sendToTarget();
}
}
};
thread.start();
}
}
call the class from your fragment.
private void getAddressLatitudeLongitude(String branchAddress) {
Log.e("getAddressLatitudeLongitude ==>" + branchAddress);
GeocodingLocation.getAddressFromLocation(branchAddress, thisActivity, new GeocoderHandler());
}
Keep this class as inner class in same fragment
private class GeocoderHandler extends Handler {
#Override
public void handleMessage(Message message) {
switch (message.what) {
case 1:
try {
Bundle bundle = message.getData();
latitude = bundle.getString("latitude");
longitude = bundle.getString("longitude");
Log.e("CreateBranch --> GeocoderHandler ==>" + latitude + " " + longitude);
}catch (Exception e){
e.printStackTrace();
}
break;
default:
latitude = null;
longitude = null;
}
latitudeList.add(latitude);
longitudeList.add(longitude);
if(latitude==null || longitude==null){
showAlertDialog("Please enter correct address", Constants.APP_NAME);
}
Log.e("Latitude list =>" + latitudeList);
Log.e("Longitude list =>" + longitudeList);
}
}
Output will get latitude and longitude. Hope this answer helps.
I have 2 different class, first class Tracking.java and second class ReportingService.java. how to passing location address on ReportingService.java to Tracking.java?
private void doLogout(){
Log.i(TAG, "loginOnClick: ");
//ReportingService rs = new ReportingService();
//rs.sendUpdateLocation(boolean isUpdate, Location);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(NetHelper.getDomainAddress(this))
.addConverterFactory(ScalarsConverterFactory.create())
.build();
ToyotaService toyotaService = retrofit.create(ToyotaService.class);
// caller
Call<ResponseBody> caller = toyotaService.logout("0,0",
AppConfig.getUserName(this),
"null");
// async task
caller.enqueue(new Callback<ResponseBody>() {
#Override
public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
try {
Log.i(TAG, "onResponse: "+response.body().string());
}catch (IOException e){}
}
#Override
public void onFailure(Call<ResponseBody> call, Throwable t) {
Log.e(TAG, "onFailure: ", t);
}
});
AppConfig.saveLoginStatus(this, AppConfig.LOGOUT);
AppConfig.storeAccount(this, "", "");
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
finish();
}
This code for location address
Call<ResponseBody> caller = toyotaService.logout("0,0",
AppConfig.getUserName(this),
"null");
And this is class ReportingService.java location of code get longtitude, latitude and location address from googlemap
private void sendUpdateLocation(boolean isUpdate, Location location) {
Log.i(TAG, "onLocationChanged "+location.getLongitude());
Geocoder geocoder;
List<Address> addresses;
geocoder = new Geocoder(this, Locale.getDefault());
String street = "Unknown";
try {
addresses = geocoder.getFromLocation(location.getLatitude(), location.getLongitude(), 1);
if (addresses != null) {
String address = addresses.get(0).getAddressLine(0);
String city = addresses.get(0).getLocality();
String state = addresses.get(0).getAdminArea();
String country = addresses.get(0).getCountryName();
String postalCode = addresses.get(0).getPostalCode();
String knowName = addresses.get(0).getFeatureName();
street = address + " " + city + " " + state + " " + country + " " + postalCode + " " + knowName;
Log.i(TAG, "street "+street);
}
} catch (IOException e) {
e.printStackTrace();
}
if (isUpdate)
NetHelper.report(this, AppConfig.getUserName(this), location.getLatitude(),
location.getLongitude(), street, new PostWebTask.HttpConnectionEvent() {
#Override
public void preEvent() {
}
#Override
public void postEvent(String... result) {
try {
int nextUpdate = NetHelper.getNextUpdateSchedule(result[0]); // in second
Log.i(TAG, "next is in " + nextUpdate + " seconds");
if (nextUpdate > 60) {
dismissNotification();
isRunning = false;
} else if (!isRunning){
showNotification();
isRunning = true;
}
handler.postDelayed(location_updater, nextUpdate * 1000 /*millisecond*/);
}catch (JSONException e){
Log.i(TAG, "postEvent error update");
e.printStackTrace();
handler.postDelayed(location_updater, getResources().getInteger(R.integer.interval) * 1000 /*millisecond*/);
}
}
});
else
NetHelper.logout(this, AppConfig.getUserName(this), location.getLatitude(),
location.getLongitude(), street, new PostWebTask.HttpConnectionEvent() {
#Override
public void preEvent() {
}
#Override
public void postEvent(String... result) {
Log.i(TAG, "postEvent logout "+result);
}
});
}
Thanks
Use this library and follow the provided example inside it.
Its for passing anything you wish to anywhere you wish.
i think just using an interface will solve your problem.
pseudo code
ReportingException.java
add this
public interface myLocationListner{
onRecievedLocation(String location);
}
private myLocationListner mylocation;
//add below line where you get street address
mylocation.onRecievedLocation(street);
then implement myLocationListner in Tracking.java
there you go :)
You can use an intent:
The intent will fire the 2nd Receiver and will pass the data into that
If BroadcastReceiver:
Intent intent = new Intent();
intent.setAction("com.example.2ndReceiverFilter");
intent.putExtra("key" , ); //put the data you want to pass on
getApplicationContext().sendBroadcast(intent);
If Service:
Intent intent = new Intent();`
intent.putExtra("key" , value ); //put the data you want to pass on
startService( ReportingService.this , Tracking.class);
in Tracking.java, to retrieve the Data you passed on:
inside onReceive, put this code first
intent.getExtras().getString("key");//if int use getInt("key")
This question already has answers here:
How do I get the current GPS location programmatically in Android?
(21 answers)
Closed 7 years ago.
I making SMS logger. I already get information as data, body of sms etc. But I also want add GPS coordinates where SMS was send from my device and the same with incoming SMS.
How i get SMS info:
public List<String> getInboundSMSCaptured() {
EnterpriseDeviceManager edm = (EnterpriseDeviceManager) getSystemService(EnterpriseDeviceManager.ENTERPRISE_POLICY_SERVICE);
DeviceInventory deviceInventoryPolicy = edm.getDeviceInventory();
List<String> list = new ArrayList<String>();
List<String> outlist = new ArrayList<String>();
try {
deviceInventoryPolicy.enableSMSCapture(true);
// The device has likely logged some SMS messages at some point
// after
// enabling the policy.
list = deviceInventoryPolicy.getInboundSMSCaptured();
String separator = ";";
TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
// String getSimSerialNumber = telemamanger.getSimSerialNumber(); //serial
// String imei = telemamanger.getDeviceId(); // imei
String OperatorName = telemamanger.getSimOperatorName(); // operator
for (String log : list) {
String character = "$";
String newlog = log + character;
newlog = newlog.replace("\n", "").replace("\r", "");
outlist.add(newData(getPieceOfStr("TimeStamp:", " - ", log))
+ separator + "In" + separator
+ getPieceOfStr("From:", " - ", log) + separator
+ OperatorName + separator + "\ufeff"
+ getPieceOfStr("Body:", LastElement(newlog), newlog)
+ separator);
}
} catch (SecurityException e) {
Log.w(TAG, "SecurityException: " + e);
}
return outlist;
}
Then i create CSV file on device:
public void writeAllSMSs(List<String> InSMSs, List<String> OutSMSs) {
List<String> AllSMSs_list = new ArrayList<String>();
InSMSs = getInboundSMSCaptured();
OutSMSs = getOutboundSMSCaptured();
TelephonyManager telemamanger = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imei = telemamanger.getDeviceId();
// separator for excel
String separator = ";";
AllSMSs_list = InSMSs;
AllSMSs_list.addAll(OutSMSs);
// sort from old to new calls
Collections.sort(AllSMSs_list);
// add info on top of file
AllSMSs_list.add(0, "Time" + separator + "Status" + separator
+ "SMS Number" + separator + "Operator" + separator + "Body"
+ separator + "Latitude" + separator + "Longitude");
try {
FileOutputStream fileout = openFileOutput("SMS's.csv",
MODE_MULTI_PROCESS);
OutputStreamWriter outputWriter = new OutputStreamWriter(fileout);
for (int i = 0; i < AllSMSs_list.size(); i++) {
outputWriter.write(AllSMSs_list.get(i) + "\n");
}
Collections.reverse(AllSMSs_list);
outputWriter.write("\n\nFile created: " + currentData());
outputWriter.flush();
outputWriter.close();
// display file saved message
Toast.makeText(getBaseContext(), "File saved successfully!",
Toast.LENGTH_SHORT).show();
copyFile("/data/data/com.example.samsungmdm/files/SMS's.csv",
// for android /0/ for knox /100/
"/storage/emulated/0/KNOX_Logs/"
// "/storage/emulated/100/KNOX_Logs/"
+ imei + " SMS's.csv");
} catch (Exception e) {
e.printStackTrace();
}
}
Thanks
I don't have Android Studio right now in this PC, so sorry for any syntax mistake. In class that you has created you must to add
public classs yourclass {
public void writeAllSMSs(List<String> InSMSs, List<String> OutSMSs) {
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
LocationListener locationListener = new GPS();
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, locationListener);
...
//Now you can use
GPS gps = new GPS();
//And obtain
gps.getCurrentLatitude();
gps.getCurrentLongitude();
//Where you need put coordinates
}
}
And create a new class, GPS for example, that implements LocationListener
private class GPS implements LocationListener {
private static location = new LatLng();
public double getCurrentLatitude(){
return location.latitude;
}
public double getCurrentLongitude(){
return location.longitude;
}
#Override
public void onLocationChanged(Location _location) {
location.latitude = _location.getLatitude();
location.longitude = _location.getLongitude();
}
#Override
public void onProviderDisabled(String provider) {}
#Override
public void onProviderEnabled(String provider) {}
#Override
public void onStatusChanged(String provider, int status, Bundle extras) {}
}
Don't forget Android Manifest PERMISSION
< uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
I am engaging with android sensor data filtering. At the same time, I am not good at JAVA. It needs to integrate "FixFilter" class with main source code which starts ENS492SenorsActivity. In this approach, I aimed that filtering data which is taken from accelerometer and orientation sensors. acx is the taken data from accelerometer in the X directiona and orx is the taken data from orientation data in the X direction.
public float FixFilter (double acx, float orx)
{
orx = 0.75*(orx) + 0.25*(acx);
return orx;
}
public class Ens492SenorsActivity extends Activity implements SensorListener
{
final String tag = "IBMEyes";
SensorManager sm = null;
TextView xViewA = null;
TextView yViewA = null;
TextView zViewA = null;
TextView xViewO = null;
TextView yViewO = null;
TextView zViewO = null;
//for gps
TextView xView1 = null;
TextView yView1 = null;
TextView zView1 = null;
private LocationManager locManager;
private LocationListener locListener = new MyLocationListener();
private boolean gps_enabled = false;
private boolean network_enabled = false;
private Timer mTimer = new Timer();
private int REFRESH_TIME = 1000;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
sm = (SensorManager) getSystemService(SENSOR_SERVICE);
setContentView(R.layout.main);
xViewA = (TextView) findViewById(R.id.xbox);
yViewA = (TextView) findViewById(R.id.ybox);
zViewA = (TextView) findViewById(R.id.zbox);
xViewO = (TextView) findViewById(R.id.xboxo);
yViewO = (TextView) findViewById(R.id.yboxo);
zViewO = (TextView) findViewById(R.id.zboxo);
xView1 = (TextView) findViewById(R.id.xbox1);
yView1 = (TextView) findViewById(R.id.ybox1);
zView1 = (TextView) findViewById(R.id.zbox1);
locManager = (LocationManager) getSystemService(this.LOCATION_SERVICE);
locManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locListener);
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
init_arr();
}
public static void connect(String url)
{
HttpClient httpclient = new DefaultHttpClient();
// Prepare a request object
HttpGet httpget = new HttpGet(url);
// Execute the request
HttpResponse response;
try {
response = httpclient.execute(httpget);
// Examine the response status
Log.i("Praeda",response.getStatusLine().toString());
// Get hold of the response entity
HttpEntity entity = response.getEntity();
// If the response does not enclose an entity, there is no need
// to worry about connection release
if (entity != null) {
// A Simple JSON Response Read
InputStream instream = entity.getContent();
String result= convertStreamToString(instream);
// now you have the string representation of the HTML request
instream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
private static String convertStreamToString(InputStream is) {
/*
* To convert the InputStream to String we use the BufferedReader.readLine()
* method. We iterate until the BufferedReader return null which means
* there's no more data to read. Each line will appended to a StringBuilder
* and returned as String.
*/
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
public void ShowMap(View v)
{
String uri = String.format("geo:%f,%f", alig.getLatitude(), alig.getLongitude());
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
this.startActivity(intent);
}
public double DoruksKalman (double v1, double v2, double v3,double v4,double v5,double v6,double v7,double v8,double v9,double v10 )
{
double result = 0;
//result = 10 / ( 1/ v1 + 1/ v2 +1/ v3 +1/ v4 +1/ v5 +1/ v6 +1/ v7 +1/ v8 +1/ v9 +1/ v10);
result = (v1 + v2 + v3 + v4 +v5 + v6 +v7 + v8 +v9 + v10)/10;
return result;
}
public float FixFilter (double acx, float orx)
{
orx = 0.75*(orx) + 0.25*(acx);
return orx;
}
public void SendToServer(View v)
{
Log.i(getClass().getSimpleName(), "send task - start");
try{
connect("http://192.168.1.117/ens4912/process.php?ip=&lat=" +
DoruksKalman(
alig.getLatitude(), alig.getLatitude(),alig.getLatitude(),
alig.getLatitude(),alig.getLatitude(),alig.getLatitude(),
alig.getLatitude(),alig.getLatitude(),alig.getLatitude(),
alig.getLatitude())+
"&lng="+
DoruksKalman(alig.getLongitude(), alig.getLongitude(),alig.getLongitude(), alig.getLongitude(),
alig.getLongitude(), alig.getLongitude(), alig.getLongitude(),
alig.getLongitude(), alig.getLongitude(), alig.getLongitude())+
"&alt="+
DoruksKalman(alig.getAltitude(),alig.getAltitude(),alig.getAltitude(),
alig.getAltitude(),alig.getAltitude(),alig.getAltitude(),
alig.getAltitude(),alig.getAltitude(),alig.getAltitude(),alig.getAltitude())+
"&accel="+
DoruksKalman(acx_arr[0], acx_arr[1],acx_arr[2],acx_arr[3],acx_arr[4],
acx_arr[5],acx_arr[6],acx_arr[7],
acx_arr[8],acx_arr[9])+
"&mag="+
DoruksKalman(orx_arr[0], orx_arr[1], orx_arr[2], orx_arr[3],
orx_arr[4],orx_arr[5],orx_arr[6],
orx_arr[7],orx_arr[8],orx_arr[9])
);//"http://www.google.com");
}
catch (Exception e)
{
double zero =0.0;
e.printStackTrace();
connect("http://192.168.1.117/ens4912/process.php?ip=&lat=" +
zero+
"&lng="+
zero+
"&alt="+
zero+
"&accel="+
DoruksKalman(acx_arr[0], acx_arr[1],acx_arr[2],acx_arr[3],acx_arr[4],
acx_arr[5],acx_arr[6],acx_arr[7],
acx_arr[8],acx_arr[9])+
"&mag="+
DoruksKalman(orx_arr[0], orx_arr[1], orx_arr[2], orx_arr[3],
orx_arr[4],orx_arr[5],orx_arr[6],
orx_arr[7],orx_arr[8],orx_arr[9])
);
}
Log.i(getClass().getSimpleName(), "send task - end");
}
float orx;
float ory;
float orz;
float acx;
float acy;
float acz;
float [] acx_arr = new float[10];
float [] acy_arr = new float[10];
float [] acz_arr = new float[10];
float [] orx_arr = new float[10];
float [] ory_arr = new float[10];
float [] orz_arr = new float[10];
private void init_arr()
{
for(int i = 0;i <10;i++)
{
acx_arr[i] = 1.0f;
acy_arr[i] = 1.0f;
acz_arr[i] = 1.0f;
orx_arr[i] = 1.0f;
ory_arr[i] = 1.0f;
orz_arr[i] = 1.0f;
}
}
int sensorReadCount = 0;
private final float NOISE = (float) 2.0;
private float mLastX, mLastY, mLastZ;
private boolean mInitialized = false;
public void onSensorChanged(int sensor, float[] values) {
Boolean writeIt = false;
synchronized (this) {
//Log.d(tag, "onSensorChanged: " + sensor + ", x: " + values[0] + ", y: " + values[1] + ", z: " + values[2]);
if (sensor == SensorManager.SENSOR_ORIENTATION) {
xViewO.setText("Orientation X: " +
DoruksKalman(orx_arr[0], orx_arr[1],orx_arr[2],orx_arr[3],orx_arr[4],
orx_arr[5],orx_arr[6],orx_arr[7],
orx_arr[8],orx_arr[9]));
yViewO.setText("Orientation Y: " +
DoruksKalman(ory_arr[0], ory_arr[1],ory_arr[2],ory_arr[3],ory_arr[4],
ory_arr[5],ory_arr[6],ory_arr[7],
ory_arr[8],ory_arr[9]));
zViewO.setText("Orientation Z: " +
DoruksKalman(orz_arr[0], orz_arr[1],orz_arr[2],orz_arr[3],orz_arr[4],
orz_arr[5],orz_arr[6],orz_arr[7],
orx_arr[8],orx_arr[9]));
orx = values[0];
ory = values[1];
orz = values[2];
orx_arr[sensorReadCount%10] = orx;
ory_arr[sensorReadCount%10] = ory;
orz_arr[sensorReadCount%10] = orz;
}
if (sensor == SensorManager.SENSOR_ACCELEROMETER) {
acx = values[0];
acy = values[1];
acz = values[2];
if (!mInitialized) {
mLastX = acx;
mLastY = acy;
mLastZ = acz;
mInitialized = true;
}
else {
float deltaX = Math.abs(mLastX - acx);
float deltaY = Math.abs(mLastY - acy);
float deltaZ = Math.abs(mLastZ - acz);
if (deltaX < NOISE) deltaX = (float)0.0;
if (deltaY < NOISE) deltaY = (float)0.0;
if (deltaZ < NOISE) deltaZ = (float)0.0;
mLastX = acx;
mLastY = acy;
mLastZ = acz;
if (deltaX > deltaY) {
//iv.setImageResource(R.drawable.horizontal);
writeIt = false;
} else if (deltaY > deltaX) {
//iv.setImageResource(R.drawable.vertical);
writeIt = true;
} else {
//iv.setVisibility(View.INVISIBLE);
writeIt = false;
}
}
xViewA.setText("Accel X: " + acx);
yViewA.setText("Accel Y: " + acy);
zViewA.setText("Accel Z: " + acz);
/*
xViewA.setText("Accel X: " +
DoruksKalman(acx_arr[0], acx_arr[1],acx_arr[2],acx_arr[3],acx_arr[4],
acx_arr[5],acx_arr[6],acx_arr[7],
acx_arr[8],acx_arr[9]));
yViewA.setText("Accel Y: " +
DoruksKalman(acy_arr[0], acy_arr[1],acy_arr[2],acy_arr[3],acy_arr[4],
acy_arr[5],acy_arr[6],acy_arr[7],
acy_arr[8],acy_arr[9]));
zViewA.setText("Accel Z: " +
DoruksKalman(acz_arr[0], acz_arr[1],acz_arr[2],acz_arr[3],acz_arr[4],
acz_arr[5],acz_arr[6],acz_arr[7],
acz_arr[8],acz_arr[9]));
*/
acx_arr[sensorReadCount%10] = acx;
acy_arr[sensorReadCount%10] = acy;
acz_arr[sensorReadCount%10] = acz;
}
}
try
{
if(sensorReadCount % 10 == 0 && writeIt)// sensorReadCount <= 60 * 10 /* write for 10 minutes*/ )
{
WriteToTXT();
}
}
catch(Exception e)
{
e.printStackTrace();
}
sensorReadCount++;
}
public Boolean IsItBumb()
{
return true;
}
public void onAccuracyChanged(int sensor, int accuracy) {
Log.d(tag,"onAccuracyChanged: " + sensor + ", accuracy: " + accuracy);
}
int id = 0;
private void WriteToTXT()
{
id++;
// TO DO
// Buray\FD dolduracaks\FDn\FDz
//sat\FDr sat\FDr
//id - lat - lon -alt - magx - magy - magz - accx - accy -accz - time
double lat;
double lon;
double alt;
double speed;
try
{
lat = alig.getLatitude();
lon = alig.getLongitude();
alt = alig.getAltitude();
speed = alig.getSpeed();
}
catch( Exception e)
{
lat = 0.0;
lon = 0.0;
alt = 0.0;
speed = 0.0;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd_HHmmss");
String currentDateandTime = sdf.format(new Date());
String fileName = "doruks_txt";
/*
String sBody = id + " " + lat + " " + lon + " " + alt + " " + orx + " " + ory + " " +
orz + " " + acx + " " + acy + " " + acz + " " + speed + " " + currentDateandTime;
*/
String sBody = lat + "|" + lon + "|" + alt + " " + orx + " " + ory + " " +
orz + " " + acx + " " + acy + " " + acz + " " + speed + " " + currentDateandTime + "|" + id;
generateNoteOnSD(fileName, sBody);
appendLog(sBody);
}
public void appendLog(String text)
{
File logFile = new File("sdcard/mylog.file");
if (!logFile.exists())
{
try
{
logFile.createNewFile();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
try
{
//BufferedWriter for performance, true to set append to file flag
BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
buf.append(text);
buf.newLine();
buf.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void generateNoteOnSD(String sFileName, String sBody)
{
try
{
File root = new File(Environment.getExternalStorageDirectory(), "Notes");
if (!root.exists())
{
root.mkdirs();
}
File gpxfile = new File(root, sFileName);
FileWriter writer = new FileWriter(gpxfile);
writer.append(sBody);
writer.flush();
writer.close();
Toast.makeText(this, "Saved", Toast.LENGTH_SHORT).show();
}
catch(IOException e)
{
e.printStackTrace();
}
}
#Override
protected void onResume() {
super.onResume();
sm.registerListener(this,
SensorManager.SENSOR_ORIENTATION |
SensorManager.SENSOR_ACCELEROMETER,
SensorManager.SENSOR_DELAY_NORMAL);
}
#Override
protected void onStop() {
sm.unregisterListener(this);
super.onStop();
}
public Location alig = null;
class MyLocationListener implements LocationListener {
public Location gLoc = null;
public Location mLoc = null;
public void onLocationChanged(Location location) {
// TODO Auto-generated method stub
if (location != null) {
synchronized (this) {
// This needs to stop getting the location data and save the battery power.
//locManager.removeUpdates(locListener);
alig = location;
String longitude = "Longitude: " + location.getLongitude();
String latitude = "Latitude: " + location.getLatitude();
String altitiude = "Altitiude: " + location.getAltitude();
String accuracy = "Accuracy: " + location.getAccuracy();
String time = "Time: " + location.getTime();
//editTextShowLocation.setText(londitude + "\n" + latitude + "\n" + altitiude + "\n" + accuracy + "\n" + time);
//progress.setVisibility(View.GONE);
xView1.setText("X: " + longitude);
yView1.setText("Y: " + latitude);
zView1.setText("Z: " + altitiude);
}
}
}
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
}
}