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" />
Related
I am having a bit of trouble trying to utilize the default Android dialog for popping up networks listed in the area. I have done some research and tried different avenues, but I haven't found anything that works correctly.
WifiManager mWifiManager;
List<ScanResult> mScanResults;
WifiListAdapter wifiListAdapter;
TextView hiddenVersionNumber;
String connectedSSID = "";
ProgressBar wifiNetworksLoading;
ArrayList<WifiItem> networkList = new ArrayList<>();
private static final int WEAK_WIFI_SIGNAL_STRENGTH = 1;
private final BroadcastReceiver mWifiScanReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context c, Intent intent) {
if (intent.getAction().equals(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION)) {
List<ScanResult>mScanResults = mWifiManager.getScanResults();
//*unregisterReceiver(mWifiScanReceiver);*//
Log.d(TAG, "bozo " + mScanResults.size());
//*networkList.clear();
if (wifiNetworksLoading != null) {
wifiNetworksLoading.setVisibility(View.GONE);
}*//
ArrayList<WifiItem> list = new ArrayList<>();
for (ScanResult scan : mScanResults) {
//*Log.d(TAG, "bozo3 " + scan.SSID);*//
int level = WifiManager.calculateSignalLevel(scan.level, 4);
boolean isConnected = false;
Log.d(TAG, "bozo2 " + connectedSSID);
if (!connectedSSID.isEmpty()) {
Log.d(TAG, "bozo2 " + connectedSSID + " = " + scan.SSID);
if (connectedSSID.equalsIgnoreCase(scan.SSID)) {
isConnected = true;
}
}
if (!scan.SSID.isEmpty()) {
networkList.add(new WifiItem(scan.SSID, scan.capabilities, level, isConnected));
}
}
The OnCreate code listed below...
mWifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
//*registerReceiver(mWifiScanReceiver, new IntentFilter(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION));*//
mWifiManager.startScan();
if (mWifiManager != null) {
mWifiManager.setWifiEnabled(true); // turn on Wifi
}
I had a requirement that if suppose the city is Hyderabad then using places search API I need to get only Hyderabad places while searching. But I am getting only a few places in search. how to get all the places related to Hyderabad city. Please anyone can help me out.
I have tried the code:
if (!Places.isInitialized()) {
Places.initialize(getApplicationContext(), "apikey");
}
final AutocompleteSupportFragment autocompleteFragment = (AutocompleteSupportFragment)
getSupportFragmentManager().findFragmentById(R.id.autofill);
autocompleteFragment.setCountry("IN");
final Button closeBtn = dialog.findViewById(R.id.close_btn);
dialog.show();
autocompleteFragment.setLocationRestriction(RectangularBounds.newInstance(
new LatLng(17.387140, 78.491684),
new LatLng(17.440081, 78.348915)));
autocompleteFragment.setPlaceFields(Arrays.asList(Place.Field.ID, Place.Field.NAME, Place.Field.ADDRESS, Place.Field.LAT_LNG));
autocompleteFragment.setTypeFilter(TypeFilter.ADDRESS);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
#Override
public void onPlaceSelected(Place place) {
// TODO: Get info about the selected place.
if (place.getAddress() != null) {
Log.e("Place", "Place: " + place.getName() + ", " + place.getId() + " , " + place.getAddress() + " , " + place.getLatLng());
// progressDialog.show();
// progressDialog.setCancelable(false);
double latitude = Objects.requireNonNull(place.getLatLng()).latitude;
Log.d("lat:", String.valueOf(latitude));
double longitude = place.getLatLng().longitude;
Log.d("lng:", String.valueOf(longitude));
String name = place.getName();
Geocoder geocoder = new Geocoder(PlacesSearch.this, Locale.getDefault());
List<Address> addresses = null;
try {
addresses = geocoder.getFromLocation(latitude, longitude, 1);
} catch (IOException e) {
e.printStackTrace();
}
String aa = addresses.get(0).getAddressLine(0);
Log.e("aa:", aa);
String[] ad = aa.split(",");
String street = ad[0] + "," + ad[1] + "," + ad[2];
String city1 = addresses.get(0).getLocality();
String state1 = addresses.get(0).getAdminArea();
String zip1 = addresses.get(0).getPostalCode();
String country1 = addresses.get(0).getCountryName();
String countryCode = addresses.get(0).getCountryCode();
System.out.println("countryCode"+countryCode);
placesearch.setText(aa);
// progressDialog.dismiss();
dialog.dismiss();
}
}
#Override
public void onError(Status status) {
// TODO: Handle the error.
Log.e("Place", "An error occurred: " + status);
}
});
I am building a collector application that continuously scans the Bluetooth and writes the RSSI results in a file, I used this code but it scans and records the data every 5-second.
I want to make it scan and collect the RSSI data every 100 mill second.Please help me to modify this.
private ScanCallback leScanCallback = new ScanCallback() {
#Override
public void onScanResult(int callbackType, final ScanResult result) {
new Handler(Looper.getMainLooper()).post(new Runnable() {
// Tried new Handler(Looper.myLopper()) also
#Override
public void run() {
peripheralTextView.append("MAC: " + result.getDevice().getAddress() +","
+ result.getDevice().getName() +","
+ " RSSI: " + result.getRssi() + "\n");
}
});
try {
long TimeStampMillSec = TimeStampMillSec();
String DateTimeToIso8601Datetimehhmmss = DateTimeToIso8601Datetimehhmmss();
JSONObject jsonMsg =new JSONObject();
//Edited by Mansour
jsonMsg.put("BLue",
"6"+","+phoneIMEI+","+DateTimeToIso8601Datetimehhmmss+
","+TimeStampMillSec+","+result.getDevice().getName()
+ "," + result.getRssi());
WriteMessageLog(0, jsonMsg +"\n");
// auto scroll for text view
final int scrollAmount =
peripheralTextView.getLayout().getLineTop(peripheralTextView.getLineCount())
- peripheralTextView.getHeight();
// if there is no need to scroll, scrollAmount will be <=0
if (scrollAmount > 0)
peripheralTextView.scrollTo(0, scrollAmount);
}
catch (Exception e)
{
e.printStackTrace();
}
}
};`
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")