Scoped Storage won't allow FileInputStream access to file in DOWNLOADS, is there a workaround? - android-external-storage

I import data from a downloaded spreadsheet into a Room database. This is what I need to do :
String filePath = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)
.getAbsolutePath();
String fileName = context.getString(R.my_file_name);
File importFile = new File(filePath + File.separator, fileName);
try {
FileInputStream stream = new FileInputStream(importFile);
// do stuff
} catch (Exception e1) {e1.printStackTrace();}
So, this doesn't work anymore(?) I haven't been able to find a concise explanation (in JAVA) of how to accomplish this simple operation going forward without asking for the MANAGE_EXTERNAL_STORAGE permission (an unacceptable solution) Help from the gurus?

So, need to set up intent in manifest, and leave old permissions for legacy android
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:maxSdkVersion="28"/>
<application
android:requestLegacyExternalStorage="true"
>
<activity
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
in mainActivity, set up file picker, create method to launch the picker, and create method to process picker result.
Main Activity :
private ActivityResultLauncher<Intent> launchFilePicker;
public File importFile;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
filePath = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOWNLOADS).
getAbsolutePath();
launchFilePicker = registerForActivityResult(
new ActivityResultContract<Intent, Uri>() {
#NonNull
#Override
public Intent createIntent(#NonNull Context context, Intent input) {
return input;
}
#Override
public Uri parseResult(int resultCode, #Nullable Intent result) {
if (result == null || resultCode != Activity.RESULT_OK) {
return null;
}
return result.getData();
}
},
this::getFileFromUri);
...
public void launchFileFinder() {
Intent pickerIntent = new Intent(ACTION_OPEN_DOCUMENT);
pickerIntent.addCategory(Intent.CATEGORY_OPENABLE);
pickerIntent.setType(" your mime type ");
pickerIntent.putExtra(DocumentsContract.EXTRA_INITIAL_URI, Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS));
launchFilePicker.launch(pickerIntent);
}
...
public void getFileFromUri(Uri result) {
String fileName = context.getString(R.my_file_name);
File importFile = new File(filePath + File.separator, fileName);
InputStream stream = null;
try {
stream = AppMainActivity.this.getContentResolver().openInputStream(result);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
if (stream != null) {
try {
FileInputStream stream = new FileInputStream(importFile);
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
}
}
}
}

Related

Display specific Activity, when Firebase notification is tapped

When user taps on a notification sent from the Firebase console, I need to launch a specific Android Activity, only when the user taps on the notification. How can this be accomplished in the following 2 scenarios:
App is not opened or app running in Background
App is in the foreground
You can achieve this in two ways,
1. First way
Adding click_action in notification payload,
jNotification.put("click_action", "OPEN_ACTIVITY_1");
private void pushNotification(String token) {
JSONObject jPayload = new JSONObject();
JSONObject jNotification = new JSONObject();
JSONObject jData = new JSONObject();
try {
jNotification.put("title", "Google I/O 2016");
jNotification.put("text", "Firebase Cloud Messaging (App)");
jNotification.put("sound", "default");
jNotification.put("badge", "1");
jNotification.put("click_action", "OPEN_ACTIVITY_1");
jData.put("picture_url", "http://opsbug.com/static/google-io.jpg");
jPayload.put("to", token);
//jPayload.put("to", "/topics/news");
//jPayload.put("condition", "'logined' in topics || 'news' in topics");
//jPayload.put("registration_ids", jData);
jPayload.put("priority", "high");
jPayload.put("notification", jNotification);
jPayload.put("data", jData);
URL url = new URL("https://fcm.googleapis.com/fcm/send");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("POST");
conn.setRequestProperty("Authorization", AUTH_KEY);
conn.setRequestProperty("Content-Type", "application/json");
conn.setDoOutput(true);
// Send FCM message content.
OutputStream outputStream = conn.getOutputStream();
outputStream.write(jPayload.toString().getBytes());
// Read FCM response.
InputStream inputStream = conn.getInputStream();
final String resp = convertStreamToString(inputStream);
Handler h = new Handler(Looper.getMainLooper());
h.post(new Runnable() {
#Override
public void run() {
Log.e("Response", resp);
//txtStatus.setText(resp);
}
});
} catch (JSONException | IOException e) {
e.printStackTrace();
}
}
Add this is in your AndroidManifest.xml
<activity android:name="com.example.fcm.SecondActivity">
<intent-filter>
<action android:name="OPEN_ACTIVITY_1" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
MyFirebaseMessagingService.java
public class MyFirebaseMessagingService extends FirebaseMessagingService {
#Override
public void onMessageReceived(RemoteMessage remoteMessage) {
super.onMessageReceived(remoteMessage);
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
RemoteMessage.Notification notification = remoteMessage.getNotification();
Map<String, String> map = remoteMessage.getData();
sendNotification(notification.getTitle(), notification.getBody(), map);
}
private void sendNotification(String title, String body, Map<String, String> map) {
Bitmap icon = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setContentTitle(title)
.setContentText(body)
.setAutoCancel(true)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setContentIntent(pendingIntent)
.setContentInfo(title)
.setLargeIcon(icon)
.setSmallIcon(R.mipmap.ic_launcher);
try {
String picture_url = map.get("picture_url");
if (picture_url != null && !"".equals(picture_url)) {
URL url = new URL(picture_url);
Bitmap bigPicture = BitmapFactory.decodeStream(url.openConnection().getInputStream());
notificationBuilder.setStyle(new NotificationCompat.BigPictureStyle().bigPicture(bigPicture).setSummaryText(body));
}
} catch (IOException e) {
e.printStackTrace();
}
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
notificationBuilder.setLights(Color.YELLOW, 1000, 300);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
}
}
SecondActivity.java
public class SecondActivity extends AppCompatActivity {
private static final String TAG = "SecondActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Bundle bundle = getIntent().getExtras();
if (bundle != null) {
for (String key : bundle.keySet()) {
Object value = bundle.get(key);
Log.d(TAG, "Key: " + key + " Value: " + value.toString());
}
}
}
}
2. Second way
Send key through data payload like below and get key in MainActivity via getIntent() and call specific activity or fragments.
json1.put("title","Your Title");
json1.put("body","body content");
json1.put("message","Your Message");
json1.put("screen","2"); //secondFragment is 2nd position in nav drawer
json.put("data", json1);
MainActivity.java
Intent intent = getIntent();
String pos = getIntent().getStringExtra("screen");
if(pos !=null){
selectDrawerItem(navigationView.getMenu().getItem(Integer.parseInt(pos)));
}
Sample project in GITHUB,
https://github.com/Google-IO-extended-bangkok/FCM-Android

how to send location in android device to server (php) automaticlly

I have to send location(latitude & longitude) from android device to server (php) automatically (every 2 min)
and for this work I am using JobSchedulerCompat for service to send location.
But after this send locations to the server only after the application run, I want to send locations to the server continuously.
How can I achieve that?
Here is my code so far:
GpsTracker.java
public class GPSTracker extends Service {
private final Context mContext;
boolean isGPSEnabled = false;
boolean isNetworkEnabled = false;
boolean canGetLocation = false;
Location location; // location
double latitude; // latitude
double longitude; // longitude
// The minimum distance to change Updates in meters
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context context) {
this.mContext = context;
getLocation();
}
LocationListener locationListenerNetwork = new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
LocationListener locationListenerGps = new LocationListener() {
public void onLocationChanged(Location location) {
}
public void onProviderDisabled(String provider) {}
public void onProviderEnabled(String provider) {}
public void onStatusChanged(String provider, int status, Bundle extras) {}
};
public Location getLocation() {
try {
locationManager = (LocationManager) mContext
.getSystemService(LOCATION_SERVICE);
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);
try {
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
}catch (Exception ex){
ex.printStackTrace();
}
if (!isGPSEnabled && !isNetworkEnabled) {
// no network provider is enabled
} else {
this.canGetLocation = true;
if (isNetworkEnabled) {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListenerNetwork);
Toast.makeText(mContext,"Network Enabled",Toast.LENGTH_SHORT).show();
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
if (isGPSEnabled) {
if (location == null) {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES, locationListenerGps);
//Log.d("GPS Enabled", "GPS Enabled");
Toast.makeText(mContext,"GPS Enabled",Toast.LENGTH_SHORT).show();
if (locationManager != null) {
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location != null) {
latitude = location.getLatitude();
longitude = location.getLongitude();
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return location;
}
public void stopUsingGPS(){
if(locationManager != null){
locationManager.removeUpdates(locationListenerGps);
}
}
public double getLatitude(){
if(location != null){
latitude = location.getLatitude();
}
return latitude;
}
public double getLongitude(){
if(location != null){
longitude = location.getLongitude();
}
return longitude;
}
public boolean canGetLocation() {
return this.canGetLocation;
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
MyService.java
public class MyService extends JobService{
String code;
#Override
public boolean onStartJob(JobParameters params) {
code=readsavefile(getApplicationContext(),"Code2","Error");
//Toast.makeText(getApplicationContext(),code,Toast.LENGTH_SHORT).show();
new SendLocation(this,params,getApplicationContext()).execute(code);
//Toast.makeText(getApplicationContext(),"Start",Toast.LENGTH_SHORT).show();
//jobFinished(params, false);
return true;
}
public static String readsavefile(Context context,String pname,String dvalue){
SharedPreferences shared=context.getSharedPreferences("GetCodeService", Context.MODE_PRIVATE);
return shared.getString(pname,dvalue);
}
#Override
public boolean onStopJob(JobParameters params) {
return false;
}
private static class SendLocation extends AsyncTask<String, Void, String> {
MyService myService;
JobParameters jobParameters;
Context _context;
GPSTracker gps;
double lat,lon;
public SendLocation(MyService myService,JobParameters jobParameters,Context context){
this._context=context;
gps=new GPSTracker(context);
if (gps.canGetLocation){
lat=gps.getLatitude();
lon=gps.getLongitude();
}
this.myService=myService;
this.jobParameters=jobParameters;
}
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... strings) {
String link = Config.IP_Config + "Hatef/getlocation.php";
HttpClient httpclint = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
try {
JSONObject jsonobj = new JSONObject();
jsonobj.put("latitude", lat+"");
jsonobj.put("longitude", lon+"");
jsonobj.put("code", strings[0]);
List<NameValuePair> namevaluepair = new ArrayList<NameValuePair>();
namevaluepair.add(new BasicNameValuePair("req", jsonobj.toString()));
httppost.setEntity(new UrlEncodedFormEntity(namevaluepair, HTTP.UTF_8));
HttpResponse response = httpclint.execute(httppost);
InputStream inputstream = response.getEntity().getContent();
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(inputstream));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (Exception ex) {
ex.printStackTrace();
}
return sb.toString();
} catch (Exception ex) {
ex.printStackTrace();
return null;
}
}
#Override
protected void onPostExecute(String s) {
myService.jobFinished(jobParameters, false);
}
}
}
Run Service
JobInfo.Builder builder=new JobInfo.Builder(100,new ComponentName(this,MyService.class));
builder.setPeriodic(10000)
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY)
.setPersisted(true);
mJobScheduler.schedule(builder.build());
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher2"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".Main"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".second_page"
android:screenOrientation="portrait" >
</activity>
<service android:name=".MyService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"
/>
</application>

Android Fragment activity shown fullscreen

I have a question regarding a fragment layout of an OSM Map. I'd like to display the fragment within the activity in full screen modus.
However, the map is only shown on two thirds of the screen.
How can this be achieved?
Can this be done only be editing the .xml file or do I need to make any changes at the manifest or main activity as well?
Here the .xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:orientation="vertical" >
<fragment
android:id="#+id/map"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="8.01" >
</fragment>
</LinearLayout>
Here is the MapFragment.java file:
package com.example.uadclient;
import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Patter
import org.osmdroid.DefaultResourceProxyImpl;
import org.osmdroid.ResourceProxy;
import org.osmdroid.bonuspack.overlays.ExtendedOverlayItem;
import org.osmdroid.bonuspack.overlays.ItemizedOverlayWithBubble;
import org.osmdroid.bonuspack.overlays.Polyline;
import org.osmdroid.bonuspack.routing.Road;
import org.osmdroid.bonuspack.routing.RoadManager;
import org.osmdroid.bonuspack.routing.RoadNode;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapController;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.ItemizedIconOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.OverlayItem;
import org.osmdroid.views.overlay.PathOverlay;
import android.app.Fragment;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;
import com.example.uadclient.R;
public class MapFragment extends Fragment {
private MapController mMapController;
private MapView mMapView;
private ItemizedIconOverlay<OverlayItem> myLocationOverlay;
protected ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes;
protected PathOverlay roadOverlay;
FileInputStream fis = null;
private ResourceProxy mResourceProxy;
private LocationManager mLocMgr;
String s = "";
String s1 = "";
String s2 = "";
String lon = "";
String lat = "";
int mIncr = 10000;
int counter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mResourceProxy = new DefaultResourceProxyImpl(inflater.getContext().getApplicationContext());
mMapView = new MapView(inflater.getContext(), 256, mResourceProxy);
//read GPS data from file
readfromFile();
readfromFile2();
readfromFile();
String str1;
str1 = s1.toString();
readfromFile2();
String str2;
str2 = s2.toString();
try {
countLines();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
lon = str1;
lat = str2;
while (counter > 0){ //Anzahl Zeilen -> Anzahl der Punkte
double var_lon = Double.parseDouble(lon);
double var_lat = Double.parseDouble(lat);
View v = inflater.inflate(R.layout.meetfragment, null);
mMapView = (MapView) v.findViewById(R.id.mapview);
mMapView.setTileSource(TileSourceFactory.MAPNIK);
mMapView.setBuiltInZoomControls(true);
mMapView.setMultiTouchControls(true);
mMapController = mMapView.getController();
mMapController.setZoom(13);
GeoPoint point1 = new GeoPoint(var_lat, var_lon);
GeoPoint point2 = new GeoPoint(52.120310618246236, 9.905589604799236); // centre map
GeoPoint point3 = new GeoPoint(52.11712212336459, 9.899281049195961);
mMapController.setCenter(point1);
//mMapController.setCenter(point3);
ArrayList<OverlayItem> items = new ArrayList<OverlayItem>(3);
// Put overlay icon on the centre
items.add(new OverlayItem("Here", "SampleDescription", point1));
/* items.add(new OverlayItem("Here", "SampleDescription", point2));
items.add(new OverlayItem("Here", "SampleDescription", point3));*/
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>(3);
waypoints.add(point1);
waypoints.add(point2);
waypoints.add(point3);
// new UpdateRoadTask().execute(waypoints);
if (savedInstanceState == null){
//Test road service at first launch:
getRoadAsync(point1, point2);
} else {
Road mRoad = null;
updateUIWithRoad(mRoad);
}
this.myLocationOverlay = new ItemizedIconOverlay<OverlayItem>(items,
new ItemizedIconOverlay.OnItemGestureListener<OverlayItem>() {
#Override
public boolean onItemSingleTapUp(final int index,
final OverlayItem item) {
return true;
}
#Override
public boolean onItemLongPress(final int index,
final OverlayItem item) {
return false;
}
}, mResourceProxy);
this.mMapView.getOverlays().add(this.myLocationOverlay);
counter--;
return v;
}
return container;}
public void getRoadAsync(GeoPoint start, GeoPoint destination){
ArrayList<GeoPoint> waypoints = new ArrayList<GeoPoint>(2);
waypoints.add(start);
//intermediate waypoints can be added here:
//waypoints.add(new GeoPoint(48.226, -1.9456));
waypoints.add(destination);
new UpdateRoadTask().execute(waypoints);
}
void updateUIWithRoad(Road road){
List<Overlay> mapOverlays = mMapView.getOverlays();
if (roadOverlay != null){
mapOverlays.remove(roadOverlay);
}
if (road.mStatus == Road.STATUS_DEFAULT)
Toast.makeText(mMapView.getContext(), "We have a problem to get the route", Toast.LENGTH_SHORT).show();
roadOverlay = RoadManager.buildRoadOverlay(road, mMapView.getContext());
Overlay removedOverlay = mapOverlays.set(1, roadOverlay);
//we set the road overlay at the "bottom", just above the MapEventsOverlay,
//to avoid covering the other overlays.
mapOverlays.add(removedOverlay);
putRoadNodes(road);
mMapView.invalidate();
}
private void putRoadNodes(Road road){
roadNodes.removeAllItems();
Drawable marker = getResources().getDrawable(R.drawable.marker_node);
int n = road.mNodes.size();
TypedArray iconIds = getResources().obtainTypedArray(R.array.direction_icons);
for (int i=0; i<n; i++){
RoadNode node = road.mNodes.get(i);
String instructions = (node.mInstructions==null ? "" : node.mInstructions);
ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem(
"Step " + (i+1), instructions,
node.mLocation, this);
nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
nodeMarker.setMarker(marker);
int iconId = iconIds.getResourceId(node.mManeuverType, R.drawable.ic_empty);
if (iconId != R.drawable.ic_empty){
Drawable icon = getResources().getDrawable(iconId);
nodeMarker.setImage(icon);
}
roadNodes.addItem(nodeMarker);
}
}
/**
* Async task to get the road in a separate thread.
*/
private class UpdateRoadTask extends AsyncTask<Object, Void, Road> {
protected Road doInBackground(Object... params) {
#SuppressWarnings("unchecked")
ArrayList<GeoPoint> waypoints = (ArrayList<GeoPoint>)params[0];
//RoadManager roadManager = new GoogleRoadManager();
RoadManager roadManager = new OSRMRoadManager();
/*
RoadManager roadManager = new MapQuestRoadManager();
Locale locale = Locale.getDefault();
roadManager.addRequestOption("locale="+locale.getLanguage()+"_"+locale.getCountry());
*/
return roadManager.getRoad(waypoints);
}
private void putRoadNodes(Road road){
ItemizedOverlayWithBubble<ExtendedOverlayItem> roadNodes = null;
roadNodes.removeAllItems();
Drawable marker = getResources().getDrawable(R.drawable.marker_node);
int n = road.mNodes.size();
TypedArray iconIds = getResources().obtainTypedArray(R.array.direction_icons);
for (int i=0; i<n; i++){
RoadNode node = road.mNodes.get(i);
String instructions = (node.mInstructions==null ? "" : node.mInstructions);
ExtendedOverlayItem nodeMarker = new ExtendedOverlayItem(
"Step " + (i+1), instructions,
node.mLocation, this);
nodeMarker.setSubDescription(road.getLengthDurationText(node.mLength, node.mDuration));
nodeMarker.setMarkerHotspot(OverlayItem.HotspotPlace.CENTER);
nodeMarker.setMarker(marker);
int iconId = iconIds.getResourceId(node.mManeuverType, R.drawable.ic_empty);
if (iconId != R.drawable.ic_empty){
Drawable icon = getResources().getDrawable(iconId);
nodeMarker.setImage(icon);
}
roadNodes.addItem(nodeMarker);
}
}
}
public void onFinish(Bundle savedInstanceState) {
super.getActivity().finish();
}
public void onDestroy() {
super.onDestroy();
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
}
public int countLines() throws IOException {
File file = new File(Environment.getExternalStorageDirectory().getPath()+"/GPSdata.txt");
InputStream is = new BufferedInputStream(new FileInputStream(file));
try {
byte[] c = new byte[1024];
int readChars = 0;
boolean empty = true;
while ((readChars = is.read(c)) != -1) {
empty = false;
for (int i = 0; i < readChars; ++i) {
if (c[i] == '\n') {
++counter;
}
}
}
return (counter == 0 && !empty) ? 1 : counter;
} finally {
is.close();
}
}
public String readfromFile() {
// Read from file
BufferedReader bufferedReader = null;
// Pattern being checked for lattidude
Pattern p1 = Pattern.compile("[0-9]{1}.[0-9]+");
Matcher m;
// Der Pfad zur Textdatei
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/GPSdata.txt");
try {
// Der BufferedReader erwartet einen FileReader.
// Diesen kann man im Konstruktoraufruf erzeugen.
bufferedReader = new BufferedReader(new FileReader(file));
String line;
String str = null;
// null wird bei EOF oder Fehler zurueckgegeben
while ((line = bufferedReader.readLine()) != null) {
// Zeile auf der Konsole ausgeben
// Pattern currently being checked for
m = p1.matcher(line);
if (m.find()) {
str = m.group();
// arrayList1.add(str);
}
System.out.println(line);
s1 = str;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return s1;
}
public String readfromFile2() {
// Read from file
BufferedReader bufferedReader = null;
// Pattern being checked for longitude
Pattern p = Pattern.compile("[0-9]+.[0-9]+");
Matcher m;
// Der Pfad zur Textdatei
File file = new File(Environment.getExternalStorageDirectory()
.getPath() + "/GPSdata.txt");
try {
// Der BufferedReader erwartet einen FileReader.
// Diesen kann man im Konstruktoraufruf erzeugen.
bufferedReader = new BufferedReader(new FileReader(file));
String line;
String str1 = null;
// null wird bei EOF oder Fehler zurueckgegeben
while ((line = bufferedReader.readLine()) != null) {
// Zeile auf der Konsole ausgeben
// Pattern currently being checked for
m = p.matcher(line);
while (m.find()) {
str1 = m.group();
//arrayList2.add(str1);
}
System.out.println(line);
s2 = str1;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (null != bufferedReader) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return s2;
}
/*public void readLine(){
try {
BufferedReader in = new BufferedReader(new FileReader("GPSdata.txt"));
String zeile = null;
while ((zeile = in.readLine()) != null){
System.out.println("Gelesene Zeile:" + zeile);
}
} catch (IOException ex) {
ex.printStackTrace();
}
}*/
}
and here is the mainfest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.uadclient"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="14"
android:targetSdkVersion="14" />
<permission
android:name="in.wptrafficanalyzer.LocationGoogleMapV2Demo.permission.MAPS_RECEIVE"
android:protectionLevel="signature"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.INTERACT_ACROSS_USERS_FULL"/>
<uses-permission android:name="android.permission.SET_DEBUG_APP"></uses-permission>
<uses-feature
android:glEsVersion="0x00020000"
android:required="true"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.bosch.uadclient.MainMenuActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.bosch.uadclient.LocationProviderService" >
</service>
</application>
</manifest>
Best Wishes

Displaying contacts with EMAIL address only in android

i am trying to build a app, where phone contacts only with email address has to be displayed to the user.When the user click on the editbox in my app,phone contacts only with email address has to be displayed,after the user selects a contact, the email address of that contact has to be sent back to my app, which i use it further in my app.
//this is my code under onActivityResult() method
try
{
Uri result = data.getData();
String id = result.getLastPathSegment();
cursor = getContentResolver().query(Email.CONTENT_URI, null, Email.CONTACT_ID + "=?", new String[] { id }, null);
emailIdx = cursor.getColumnIndex(Email.DATA);
if (cursor.moveToFirst())
{
while (cursor.isAfterLast() == false)
{
emailid = cursor.getString(emailIdx);
allids.add(emailid);
cursor.moveToNext();
}
}
else
{
//no results actions
}
}
// This is the intent i am passing.
Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
intent.setType(ContactsContract.CommonDataKinds.Email.ADDRESS);
startActivityForResult(intent, 1);
// manifest permissions.
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<intent-filter>
<action android:name="android.intent.action.PICK" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="vnd.android.cursor.dir/email_v2" />
<data android:mimeType="vnd.android.cursor.item/email_v2" />
</intent-filter>
i am getting the below error when i try to run my app.
android.content.ActivityNotFoundException: No Activity found to handle Intent {act=android.intent.action.PICK typ=data1 }
I am not sure of what could be the problem, am i missing something in the manifest.xml?.please help.
Thanks!
This is quite old now but if I was searching for it I'm sure others are too so here's my solution. The intent is launched as follows:
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.CommonDataKinds.Email.CONTENT_TYPE);
startActivityForResult(intent, RC_GET_EMAIL);
Then to get the email address from the picked contact:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == RC_GET_EMAIL) {
if(resultCode == Activity.RESULT_OK) {
Uri contactUri = data.getData();
String[] projection = new String[]{ContactsContract.CommonDataKinds.Email.DATA};
Cursor cursor = getContext().getContentResolver().query(contactUri, projection, null, null, null);
if(cursor != null) {
if(cursor.moveToFirst()) {
int emailIndex = cursor.getColumnIndex(ContactsContract.CommonDataKinds.Email.DATA);
String email = cursor.getString(emailIndex);
// do something with email
}
cursor.close();
}
}
}
}
Remember that for Marshmallow and above you will need to manually request the READ_CONTACTS permission in order to do anything meaningful.
Put the below code in the listener, hope this helps.
Code
Intent intent = new Intent(Intent.ACTION_PICK,Contacts.CONTENT_URI);
startActivityForResult(intent, PICK_CONTACT);

Service not Starting from AsyncTask

I tried to start my service from AsyncTask but cannot see that its starting.
Hope you can see my errors.
here my code:
protected String doInBackground(String... params) {
//starts service number activite
Intent i = new Intent(context, DownloadService.class);
i.putExtra("url", "www.google.com");
i.putExtra("receiver", new DownloadReceiver(new Handler()));
context.startService(i);
here is my service
public class DownloadService extends Service{
protected void onHandleIntent(Intent intent) {
String urlLink = intent.getStringExtra("url");
ResultReceiver receiver = intent.getParcelableExtra("receiver");
// some body
Bundle data = new Bundle();
//publishing progress
data.putString("key",getActivityUrl() );
receiver.send(1,data);
}
ResultReceiver resultReceiver;
public int onStart(Intent intent, int flags, int startId) {
onHandleIntent( intent)
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public String getActivityUrl() {.....}
and my manifest file:
<service android:name="connection.DownloadService">
<intent-filter>
<action android:name="connection.DownloadService">
</action>
</intent-filter>