I am using Mapbox sdk for android.
I want to get current location,and i am also getting,but the problem is:
I am getting wrong current location,which is near Nigeria.
can anyone help me to get perfect location??
here is my gradle file's details:
android {
compileSdkVersion 27
defaultConfig {
applicationId "com.app.mapboxdemo"
minSdkVersion 15
targetSdkVersion 27
multiDexEnabled true
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support:design:27.1.1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.intuit.ssp:ssp-android:1.0.5'
implementation 'com.intuit.sdp:sdp-android:1.0.5'
implementation('com.mapbox.mapboxsdk:mapbox-android-sdk:6.1.3#aar') {
transitive = true
}
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-locationlayer:0.5.3'
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-cluster-utils:0.3.0'
implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.13.0'
implementation('com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.13.0') {
transitive = true
}
}
and here are the permisssions:
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-feature android:name="android.hardware.location.gps"/>
and here is my code for getting user location:
package com.app.mapboxdemo;// classes needed to initialize map
import com.mapbox.api.geocoding.v5.MapboxGeocoding;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.maps.MapView;
// classes needed to add location layer
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import android.location.Location;
import com.mapbox.mapboxsdk.geometry.LatLng;
import android.os.Bundle;
import android.support.annotation.NonNull;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.CameraMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.RenderMode;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
// classes needed to add a marker
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
// classes to calculate a route
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
// classes needed to launch navigation UI
import android.view.View;
import android.widget.Button;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
// classes needed to add location layer
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import android.location.Location;
import com.mapbox.mapboxsdk.geometry.LatLng;
import android.support.annotation.NonNull;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.mapboxsdk.plugins.locationlayer.modes.RenderMode;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncherOptions;
import com.mapbox.android.core.location.LocationEngine;
import com.mapbox.android.core.location.LocationEngineListener;
import com.mapbox.android.core.location.LocationEnginePriority;
import com.mapbox.android.core.location.LocationEngineProvider;
import com.mapbox.android.core.permissions.PermissionsListener;
import com.mapbox.android.core.permissions.PermissionsManager;
// classes needed to add a marker
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
// classes to calculate a route
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.util.Log;
// classes needed to launch navigation UI
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import java.util.List;
public class NavigationActivity extends AppCompatActivity implements LocationEngineListener, PermissionsListener {
private MapView mapView;
// variables for adding location layer
private static MapboxMap map;
private PermissionsManager permissionsManager;
private LocationLayerPlugin locationPlugin;
private LocationEngine locationEngine;
private Location originLocation;
// variables for adding a marker
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
// variables for calculating and drawing a route
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
EditText edtLatitude, edtLongitude;
private Button button, buttonGetLocation;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_draw_navigation);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
/*mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng point) {
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
}
});*/
button = findViewById(R.id.startButton);
edtLatitude = findViewById(R.id.edtLatitude);
edtLongitude = findViewById(R.id.edtLongitude);
buttonGetLocation = findViewById(R.id.buttonGetLocation);
buttonGetLocation.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.e(TAG, "buttonGetLocation onClick: " );
checkLatLong(mapboxMap);
}
});
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Point origin = originPosition;
Point destination = destinationPosition;
boolean simulateRoute = true;
NavigationLauncherOptions options = NavigationLauncherOptions.builder()
.origin(origin)
.destination(destination)
.shouldSimulateRoute(simulateRoute)
.build();
Log.e(TAG, "onClick: Start Button");
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(NavigationActivity.this, options);
}
});
}
});
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#SuppressWarnings({"MissingPermission"})
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
locationPlugin.setCameraMode(CameraMode.TRACKING);
locationPlugin.setRenderMode(RenderMode.COMPASS);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings({"MissingPermission"})
private void initializeLocationEngine() {
LocationEngineProvider locationEngineProvider = new LocationEngineProvider(this);
locationEngineProvider.obtainLocationEngineBy(LocationEngine.Type.ANDROID);
locationEngine = locationEngineProvider.obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
locationEngine.requestLocationUpdates();
Location lastLocation = locationEngine.getLastLocation();
// Log.e(TAG, "initializeLocationEngine: Latitude is"+lastLocation.getLatitude()+" Longitude is "+lastLocation.getLongitude() );
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
if (granted) {
enableLocationPlugin();
} else {
finish();
}
}
#Override
#SuppressWarnings({"MissingPermission"})
public void onConnected() {
locationEngine.requestLocationUpdates();
}
#Override
public void onLocationChanged(Location location) {
if (location != null) {
originLocation = location;
setCameraPosition(location);
locationEngine.removeLocationEngineListener(this);
}
}
#Override
#SuppressWarnings({"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStop();
}
mapView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
public void checkLatLong(MapboxMap mapboxMap) {
if ((edtLatitude.getText() == null && edtLatitude.getText().length() == 0) && (edtLongitude.getText() == null && edtLongitude.getText().length() == 0)) {
Toast.makeText(getApplicationContext(), "Enter Proper Longitude and Latitude.", Toast.LENGTH_LONG).show();
} else {
if (destinationMarker != null) {
map.removeMarker(destinationMarker);
}
destinationCoord = new LatLng(Double.parseDouble(edtLatitude.getText().toString()), Double.parseDouble(edtLongitude.getText().toString()));
destinationMarker = map.addMarker(new MarkerOptions()
.position(destinationCoord)
);
Log.e(TAG, "checkLatLong: ");
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
setCameraPosition(originLocation);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
}
}
}
please help me to get user location.
Help is appreciated,i referred a lot of questions but didnt get any solution.
than also,suggest any help in reffering questions too.
I Solved it by making few changes in methods initializeLocationEngine() and enableLocationPlugin()
Here are the modified methods for answer:
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(true);
locationPlugin.setCameraMode(CameraMode.TRACKING);
locationPlugin.setRenderMode(RenderMode.COMPASS);
getLifecycle().addObserver(locationPlugin);
Log.e(TAG, "enableLocationPlugin:Permission Granted" );
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
Log.e(TAG, "enableLocationPlugin:Permission Not Granted" );
}
}
private void initializeLocationEngine() {
locationEngine = new LocationEngineProvider(this).obtainBestLocationEngineAvailable();
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.addLocationEngineListener(this);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
Related
I tried to upload a file on firebase cloud from MainActivity, i made when application is destoryed it start background services and make a file contains StorageReference.toString()
and in background service i used getReferenceFromUrl(string)
To complete the uploading and i used after it
List<UploadTask> tasks = storage.getActiveTasks();
and i used Toast.makeText(this, "tasks: " + tasks.size(), 0).show();
and it shows tasks = 0
Why? And the upload doesnt complete yet
MainActivity
import android.Manifest;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ClipData;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.coordinatorlayout.widget.CoordinatorLayout;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.tasks.Task;
import com.google.android.material.appbar.AppBarLayout;
import com.google.firebase.FirebaseApp;
import com.google.firebase.storage.UploadTask;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
import java.io.File;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public final int REQ_CD_IM = 101;
private Toolbar _toolbar;
private AppBarLayout _app_bar;
private CoordinatorLayout _coordinator;
private String image = "";
private UploadSaveed upload;
private String url = "";
private ImageView imageview1;
private Button button1;
private ProgressBar progressbar1;
private TextView textview1;
private AlertDialog.Builder d;
private Intent im = new Intent(Intent.ACTION_GET_CONTENT);
#Override
protected void onCreate(Bundle _savedInstanceState) {
super.onCreate(_savedInstanceState);
setContentView(R.layout.main);
initialize(_savedInstanceState);
upload = new UploadSaveed(getApplicationContext());
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_DENIED) {
ActivityCompat.requestPermissions(this, new String[] { Manifest.permission.READ_EXTERNAL_STORAGE }, 1000);
} else {
initializeLogic();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 1000) {
initializeLogic();
}
}
private void initialize(Bundle _savedInstanceState) {
_app_bar = findViewById(R.id._app_bar);
_coordinator = findViewById(R.id._coordinator);
_toolbar = findViewById(R.id._toolbar);
setSupportActionBar(_toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
_toolbar.setNavigationOnClickListener((view) -> {
onBackPressed();
});
imageview1 = findViewById(R.id.imageview1);
button1 = findViewById(R.id.button1);
progressbar1 = findViewById(R.id.progressbar1);
textview1 = findViewById(R.id.textview1);
d = new AlertDialog.Builder(this);
im.setType("*/*");
im.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
imageview1.setOnClickListener((view) -> {
startActivityForResult(im, REQ_CD_IM);
});
button1.setOnClickListener((view) -> {
upload.setUploadListener(new UploadSaveed.UploadSavedListener() {
#Override
public void onFailureListener(Exception e) {
SketchwareUtil.showMessage(getApplicationContext(), e.toString());
}
#Override
public void onProgressListener(UploadTask.TaskSnapshot task) {
double progress = (100 * task.getBytesTransferred()) / task.getTotalByteCount();
progressbar1.setProgress((int) progress);
double bytes = task.getBytesTransferred();
SketchwareUtil.showMessage(getApplicationContext(), "transferred : " + bytes);
if (upload.getUploadUrl() != null) {
url = upload.getUploadUrl();
}
}
#Override
public void onPausedListener(UploadTask.TaskSnapshot task) {
SketchwareUtil.showMessage(getApplicationContext(), "your uploading was paused");
}
#Override
public void onSuccessListener(UploadTask.TaskSnapshot task) {
Task<Uri> taskk = task.getStorage().getDownloadUrl();
while (!taskk.isSuccessful())
;
textview1.setText(taskk.getResult().toString());
SketchwareUtil.showMessage(getApplicationContext(), "finished");
}
});
upload.UploadFile(image);
});
}
private void initializeLogic() {
if (!isMyServiceRunning(UploadService.class)) {
} else {
stopService(new Intent(getApplicationContext(), UploadService.class));
stopService(new Intent(getApplicationContext(), UploadSaveed.class));
}
d.setTitle("AutoStart");
d.setMessage("You must enable autostart for application to Work in background.");
d.setPositiveButton("enable", (dialog, which) -> {
try {
final Intent intent = new Intent();
String manufacturer = Build.MANUFACTURER.toLowerCase();
if ("xiaomi".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.miui.securitycenter",
"com.miui.permcenter.autostart.AutoStartManagementActivity"));
} else if ("oppo".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.coloros.safecenter",
"com.coloros.safecenter.permission.startup.StartupAppListActivity"));
// intent.setComponent(new ComponentName("com.coloros.oppoguardelf",
// "com.coloros.powermanager.fuelgaue.PowerConsumptionActivity"));
} else if ("vivo".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.vivo.permissionmanager",
"com.vivo.permissionmanager.activity.BgStartUpManagerActivity"));
} else if ("huawei".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.huawei.systemmanager",
"com.huawei.systemmanager.optimize.process.ProtectActivity"));
} else if ("Letv".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.letv.android.letvsafe",
"com.letv.android.letvsafe.AutobootManageActivity"));
} else if ("Honor".equalsIgnoreCase(manufacturer)) {
intent.setComponent(new ComponentName("com.huawei.systemmanager",
"com.huawei.systemmanager.optimize.process.ProtectActivity"));
} else {
return;
}
startActivity(intent);
SketchwareUtil.showMessage(getApplicationContext(),
"please enable auto start to background application");
} catch (Exception e) {
e.printStackTrace();
}
});
d.setNegativeButton("I already enabled it", (dialog, which) -> {
});
d.create().show();
}
#Override
protected void onActivityResult(int _requestCode, int _resultCode, Intent _data) {
super.onActivityResult(_requestCode, _resultCode, _data);
switch (_requestCode) {
case REQ_CD_IM:
if (_resultCode == Activity.RESULT_OK) {
ArrayList<String> _filePath = new ArrayList<>();
if (_data != null) {
if (_data.getClipData() != null) {
for (int _index = 0; _index < _data.getClipData().getItemCount(); _index++) {
ClipData.Item _item = _data.getClipData().getItemAt(_index);
_filePath.add(FileUtil.convertUriToFilePath(getApplicationContext(), _item.getUri()));
}
} else {
_filePath.add(FileUtil.convertUriToFilePath(getApplicationContext(), _data.getData()));
}
}
image = _filePath.get((int) (0));
} else {
}
break;
default:
break;
}
}
#Override
public void onDestroy() {
super.onDestroy();
try {
File fi = new File(Environment.getExternalStorageDirectory(), "saved");
if (!fi.exists()) {
fi.mkdirs();
}
File gpxfile = new File(fi, "saved.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(url);
writer.flush();
writer.close();
} catch (IOException ee) {
ee.printStackTrace();
}
upload.PauseUploading();
startService(new Intent(this, UploadService.class));
startService(new Intent(getApplicationContext(), UploadSaveed.class));
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
UploadService
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import androidx.annotation.Nullable;
import com.google.android.gms.tasks.Task;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class UploadService extends Service {
public static final String TAG = "UploadService";
private UploadSaveed upload;
#Nullable
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public int onStartCommand(Intent i, int flags, int startId) {
upload = new UploadSaveed(getApplicationContext());
upload.setUploadListener(new UploadSaveed.UploadSavedListener() {
#Override
public void onFailureListener(Exception e) {
simpleNotifaction(1, "Upload Faild", "Upload Faild !");
try {
File fi = new File(Environment.getExternalStorageDirectory(), "saved");
if (!fi.exists()) {
fi.mkdirs();
}
File gpxfile = new File(fi, "errors.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(e.toString());
writer.flush();
writer.close();
} catch (IOException ee) {
ee.printStackTrace();
}
}
#Override
public void onProgressListener(UploadTask.TaskSnapshot task) {
double progress = (100 * task.getBytesTransferred()) / task.getTotalByteCount();
notiProgress(1, "Uploading", "Your file is Uploading..", progress);
}
#Override
public void onPausedListener(UploadTask.TaskSnapshot task) {
SketchwareUtil.showMessage(getApplicationContext(), "your uploading is paused");
}
#Override
public void onSuccessListener(UploadTask.TaskSnapshot task) {
Task<Uri> taskk = task.getStorage().getDownloadUrl();
while (!taskk.isSuccessful())
;
simpleNotifaction(1, "Uploaded", "Url: " + taskk.getResult().toString());
stopSelf();
}
});
upload.UploadFormUrl(upload.getUploadUrl2());
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent i) {
startService(new Intent(this, UploadService.class));
super.onTaskRemoved(i);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
}
private void notiProgress(final double _id, final String _title, final String _text, final double _progress) {
final Context context = getApplicationContext();
android.app.NotificationManager notificationManager = (android.app.NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
androidx.core.app.NotificationCompat.Builder builder;
int notificationId = (int) _id;
String channelId = "channel-01";
String channelName = "Channel Name";
int importance = android.app.NotificationManager.IMPORTANCE_HIGH;
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
android.app.NotificationChannel mChannel = new android.app.NotificationChannel(channelId, channelName,
importance);
notificationManager.createNotificationChannel(mChannel);
}
androidx.core.app.NotificationCompat.Builder mBuilder = new androidx.core.app.NotificationCompat.Builder(
context, channelId).setSmallIcon(android.R.drawable.stat_sys_upload).setTicker("")
.setContentTitle(_title).setContentText(_text).setProgress((int) 100, (int) _progress, false);
notificationManager.notify(notificationId, mBuilder.build());
}
private void simpleNotifaction(int id2, String title, String description) {
androidx.core.app.NotificationCompat.Builder builder = new androidx.core.app.NotificationCompat.Builder(this,
"channel-01")
.setSmallIcon(android.R.drawable.stat_sys_upload_done)
.setSound(android.media.RingtoneManager
.getDefaultUri(android.media.RingtoneManager.TYPE_NOTIFICATION))
.setContentTitle(title).setContentText(description)
.setPriority(androidx.core.app.NotificationCompat.PRIORITY_MAX).setAutoCancel(true);
androidx.core.app.NotificationManagerCompat notificationManager = androidx.core.app.NotificationManagerCompat
.from(this);
notificationManager.notify(id2, builder.build());
}
}
UploadSaveed
import android.app.Activity;
import android.app.Service;
import android.content.Context;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;
import android.content.Intent;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.storage.FirebaseStorage;
import com.google.firebase.storage.StorageReference;
import com.google.firebase.storage.UploadTask;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileWriter;
import java.util.List;
import java.util.Scanner;
public class UploadSaveed extends Service {
public static final String TAG = "UploadSaveed";
private FirebaseApp app;
private StorageReference storagee, path;
private UploadTask path2;
private List<UploadTask> tasks;
private String urll;
#Nullable
#Override
public IBinder onBind(Intent i) {
return null;
}
#Override
public int onStartCommand(Intent i, int flags, int startId) {
return START_STICKY;
}
public interface UploadSavedListener {
void onProgressListener(#NonNull UploadTask.TaskSnapshot task);
void onFailureListener(#NonNull Exception e);
void onSuccessListener(#NonNull UploadTask.TaskSnapshot task);
void onPausedListener(#NonNull UploadTask.TaskSnapshot task);
}
private UploadSavedListener listener;
public void setUploadListener(UploadSavedListener listener) {
this.listener = listener;
}
public UploadSaveed() {
}
public UploadSaveed(Context c) {
FirebaseOptions options = new FirebaseOptions.Builder()
.setApplicationId("1:982483603219:android:ce7ef5f660652cdca054e6")
.setApiKey("AIzaSyAhffAnCI7dG0d3NucUAjPM6oWaX6mVSHk")
.setDatabaseUrl("trav-chat-2-default-rtdb.firebaseio.com").setStorageBucket("trav-chat-2.appspot.com")
.build();
try {
FirebaseApp.initializeApp(c, options, "firebasedb");
app = FirebaseApp.getInstance("firebasedb");
} catch (Exception e) {
e.printStackTrace();
FirebaseApp.initializeApp(c, options);
app = FirebaseApp.getInstance("firebasedb");
}
try {
File fi = new File(Environment.getExternalStorageDirectory(), "saved");
if (!fi.exists()) {
fi.mkdirs();
}
File gpxfile = new File(fi, "ssaved.txt");
FileWriter writer = new FileWriter(gpxfile);
writer.append(app.toString());
writer.flush();
writer.close();
} catch (IOException ee) {
ee.printStackTrace();
}
}
public void UploadFile(String file) {
Uri file2 = Uri.parse(file);
Uri file3 = Uri.fromFile(new File(file));
storagee = FirebaseStorage.getInstance(app).getReference();
path = storagee.child("test image").child(file2.getLastPathSegment());
path2 = path.putFile(file3);
if (listener != null) {
path2.addOnFailureListener((e) -> {
listener.onFailureListener(e);
}).addOnPausedListener((task) -> {
listener.onPausedListener(task);
}).addOnProgressListener((task) -> {
listener.onProgressListener(task);
}).addOnSuccessListener((task) -> {
listener.onSuccessListener(task);
});
} else if (listener == null) {
throw new IllegalArgumentException("listener cannot be null");
}
}
/*
public void UploadFormUrl(String url) {
storagee = FirebaseStorage.getInstance(app).getReferenceFromUrl(url);
tasks = storagee.getActiveUploadTasks();
if (tasks.size() > 0) {
if (listener != null) {
path2 = tasks.get(0);
ResumeUploading();
SketchwareUtil.showMessage(this, "lol");
path2.addOnFailureListener((e) -> {
listener.onFailureListener(e);
}).addOnPausedListener((task) -> {
listener.onPausedListener(task);
}).addOnProgressListener((task) -> {
listener.onProgressListener(task);
}).addOnSuccessListener((task) -> {
listener.onSuccessListener(task);
});
} else {
throw new IllegalArgumentException("listener cannot be null");
}
} else {
throw new IllegalArgumentException("tasks cannot be equal 0 or less");
}
}
*/
public String getUploadUrl() {
if (path != null) {
return path.toString();
} else if (storagee != null) {
return storagee.toString();
} else {
throw new IllegalArgumentException("Storage Reference is null");
}
}
public void CancelUploading() {
path2.cancel();
}
public void PauseUploading() {
path2.pause();
}
public void ResumeUploading() {
path2.resume();
}
public String getUploadUrl2() {
urll = FileUtil.readFile(Environment.getExternalStorageDirectory().toString() + "/saved/saved.txt");
return urll;
}
#Override
public void onTaskRemoved(Intent i) {
startService(new Intent(this, UploadSaveed.class));
super.onTaskRemoved(i);
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i(TAG, "onDestroy");
}
}
Try to use intent
Try this code:
val intent = Intent(this, Main2Activity::class.java)
startActivity(intent)
Video player is not buffering and the controller always false of isBuffering property
_controller.value.isBuffering
when i seek to a place i passed it re-download the video again .
I've tried to use other plugins but all of them depend on video_player under the hood
how to solve this issue ?
Replace this code with the code inside VideoPlayer.java file which is located inside video_player package. Then it will work
Link to file in github
package io.flutter.plugins.videoplayer;
import static com.google.android.exoplayer2.Player.REPEAT_MODE_ALL;
import static com.google.android.exoplayer2.Player.REPEAT_MODE_OFF;
import android.content.Context;
import android.net.Uri;
import android.os.Build;
import android.view.Surface;
import com.google.android.exoplayer2.C;
import com.google.android.exoplayer2.ExoPlaybackException;
import com.google.android.exoplayer2.ExoPlayerFactory;
import com.google.android.exoplayer2.Format;
import com.google.android.exoplayer2.Player;
import com.google.android.exoplayer2.Player.EventListener;
import com.google.android.exoplayer2.SimpleExoPlayer;
import com.google.android.exoplayer2.audio.AudioAttributes;
import com.google.android.exoplayer2.extractor.DefaultExtractorsFactory;
import com.google.android.exoplayer2.source.ExtractorMediaSource;
import com.google.android.exoplayer2.source.MediaSource;
import com.google.android.exoplayer2.source.dash.DashMediaSource;
import com.google.android.exoplayer2.source.dash.DefaultDashChunkSource;
import com.google.android.exoplayer2.source.hls.HlsMediaSource;
import com.google.android.exoplayer2.source.smoothstreaming.DefaultSsChunkSource;
import com.google.android.exoplayer2.source.smoothstreaming.SsMediaSource;
import com.google.android.exoplayer2.trackselection.DefaultTrackSelector;
import com.google.android.exoplayer2.trackselection.TrackSelector;
import com.google.android.exoplayer2.upstream.DataSource;
import com.google.android.exoplayer2.upstream.DefaultDataSourceFactory;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSource;
import com.google.android.exoplayer2.upstream.DefaultHttpDataSourceFactory;
import com.google.android.exoplayer2.util.Util;
import io.flutter.plugin.common.EventChannel;
import io.flutter.view.TextureRegistry;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
final class VideoPlayer {
private static final String FORMAT_SS = "ss";
private static final String FORMAT_DASH = "dash";
private static final String FORMAT_HLS = "hls";
private static final String FORMAT_OTHER = "other";
private SimpleExoPlayer exoPlayer;
private Surface surface;
private final TextureRegistry.SurfaceTextureEntry textureEntry;
private QueuingEventSink eventSink = new QueuingEventSink();
private final EventChannel eventChannel;
private boolean isInitialized = false;
VideoPlayer(
Context context,
EventChannel eventChannel,
TextureRegistry.SurfaceTextureEntry textureEntry,
String dataSource,
String formatHint) {
this.eventChannel = eventChannel;
this.textureEntry = textureEntry;
TrackSelector trackSelector = new DefaultTrackSelector();
exoPlayer = ExoPlayerFactory.newSimpleInstance(context, trackSelector);
Uri uri = Uri.parse(dataSource);
DataSource.Factory dataSourceFactory;
if (isHTTP(uri)) {
dataSourceFactory =
new DefaultHttpDataSourceFactory(
"ExoPlayer",
null,
DefaultHttpDataSource.DEFAULT_CONNECT_TIMEOUT_MILLIS,
DefaultHttpDataSource.DEFAULT_READ_TIMEOUT_MILLIS,
true);
} else {
dataSourceFactory = new DefaultDataSourceFactory(context, "ExoPlayer");
}
MediaSource mediaSource = buildMediaSource(uri, dataSourceFactory, formatHint, context);
exoPlayer.prepare(mediaSource);
setupVideoPlayer(eventChannel, textureEntry);
}
private static boolean isHTTP(Uri uri) {
if (uri == null || uri.getScheme() == null) {
return false;
}
String scheme = uri.getScheme();
return scheme.equals("http") || scheme.equals("https");
}
private MediaSource buildMediaSource(
Uri uri, DataSource.Factory mediaDataSourceFactory, String formatHint, Context context) {
int type;
if (formatHint == null) {
type = Util.inferContentType(uri.getLastPathSegment());
} else {
switch (formatHint) {
case FORMAT_SS:
type = C.TYPE_SS;
break;
case FORMAT_DASH:
type = C.TYPE_DASH;
break;
case FORMAT_HLS:
type = C.TYPE_HLS;
break;
case FORMAT_OTHER:
type = C.TYPE_OTHER;
break;
default:
type = -1;
break;
}
}
switch (type) {
case C.TYPE_SS:
return new SsMediaSource.Factory(
new DefaultSsChunkSource.Factory(mediaDataSourceFactory),
new DefaultDataSourceFactory(context, null, mediaDataSourceFactory))
.createMediaSource(uri);
case C.TYPE_DASH:
return new DashMediaSource.Factory(
new DefaultDashChunkSource.Factory(mediaDataSourceFactory),
new DefaultDataSourceFactory(context, null, mediaDataSourceFactory))
.createMediaSource(uri);
case C.TYPE_HLS:
return new HlsMediaSource.Factory(mediaDataSourceFactory).createMediaSource(uri);
case C.TYPE_OTHER:
return new ExtractorMediaSource.Factory(mediaDataSourceFactory)
.setExtractorsFactory(new DefaultExtractorsFactory())
.createMediaSource(uri);
default:
{
throw new IllegalStateException("Unsupported type: " + type);
}
}
}
private void setupVideoPlayer(
EventChannel eventChannel, TextureRegistry.SurfaceTextureEntry textureEntry) {
eventChannel.setStreamHandler(
new EventChannel.StreamHandler() {
#Override
public void onListen(Object o, EventChannel.EventSink sink) {
eventSink.setDelegate(sink);
}
#Override
public void onCancel(Object o) {
eventSink.setDelegate(null);
}
});
surface = new Surface(textureEntry.surfaceTexture());
exoPlayer.setVideoSurface(surface);
setAudioAttributes(exoPlayer);
exoPlayer.addListener(
new EventListener() {
#Override
public void onPlayerStateChanged(final boolean playWhenReady, final int playbackState) {
if (playbackState == Player.STATE_BUFFERING) {
sendBufferingUpdate();
Map<String, Object> event = new HashMap<>();
event.put("event", "bufferingStart");
eventSink.success(event);
} else if (playbackState == Player.STATE_READY) {
if (isInitialized) {
Map<String, Object> event = new HashMap<>();
event.put("event", "bufferingEnd");
eventSink.success(event);
} else {
isInitialized = true;
sendInitialized();
}
} else if (playbackState == Player.STATE_ENDED) {
Map<String, Object> event = new HashMap<>();
event.put("event", "completed");
eventSink.success(event);
}
}
#Override
public void onPlayerError(final ExoPlaybackException error) {
if (eventSink != null) {
eventSink.error("VideoError", "Video player had error " + error, null);
}
}
});
}
void sendBufferingUpdate() {
Map<String, Object> event = new HashMap<>();
event.put("event", "bufferingUpdate");
List<? extends Number> range = Arrays.asList(0, exoPlayer.getBufferedPosition());
// iOS supports a list of buffered ranges, so here is a list with a single range.
event.put("values", Collections.singletonList(range));
eventSink.success(event);
}
#SuppressWarnings("deprecation")
private static void setAudioAttributes(SimpleExoPlayer exoPlayer) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
exoPlayer.setAudioAttributes(
new AudioAttributes.Builder().setContentType(C.CONTENT_TYPE_MOVIE).build());
} else {
exoPlayer.setAudioStreamType(C.STREAM_TYPE_MUSIC);
}
}
void play() {
exoPlayer.setPlayWhenReady(true);
}
void pause() {
exoPlayer.setPlayWhenReady(false);
}
void setLooping(boolean value) {
exoPlayer.setRepeatMode(value ? REPEAT_MODE_ALL : REPEAT_MODE_OFF);
}
void setVolume(double value) {
float bracketedValue = (float) Math.max(0.0, Math.min(1.0, value));
exoPlayer.setVolume(bracketedValue);
}
void seekTo(int location) {
exoPlayer.seekTo(location);
}
long getPosition() {
return exoPlayer.getCurrentPosition();
}
#SuppressWarnings("SuspiciousNameCombination")
private void sendInitialized() {
if (isInitialized) {
Map<String, Object> event = new HashMap<>();
event.put("event", "initialized");
event.put("duration", exoPlayer.getDuration());
if (exoPlayer.getVideoFormat() != null) {
Format videoFormat = exoPlayer.getVideoFormat();
int width = videoFormat.width;
int height = videoFormat.height;
int rotationDegrees = videoFormat.rotationDegrees;
// Switch the width/height if video was taken in portrait mode
if (rotationDegrees == 90 || rotationDegrees == 270) {
width = exoPlayer.getVideoFormat().height;
height = exoPlayer.getVideoFormat().width;
}
event.put("width", width);
event.put("height", height);
}
eventSink.success(event);
}
}
void dispose() {
if (isInitialized) {
exoPlayer.stop();
}
textureEntry.release();
eventChannel.setStreamHandler(null);
if (surface != null) {
surface.release();
}
if (exoPlayer != null) {
exoPlayer.release();
}
}
}
Working on a project on Android studio to turn on LED via Bluetooth using mapbox turn-by-turn navigation directions. To be specific turn on left LED on the "To the right" direction arrow is displayed or any other is displayed. Is it possible to do?
MainActivity.java
import android.location.Location;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.mapbox.geojson.Point;
import com.mapbox.mapboxsdk.Mapbox;
import com.mapbox.mapboxsdk.annotations.Marker;
import com.mapbox.mapboxsdk.annotations.MarkerOptions;
import com.mapbox.mapboxsdk.camera.CameraUpdateFactory;
import com.mapbox.mapboxsdk.geometry.LatLng;
import com.mapbox.mapboxsdk.maps.MapView;
import com.mapbox.mapboxsdk.maps.MapboxMap;
import com.mapbox.mapboxsdk.maps.OnMapReadyCallback;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerMode;
import com.mapbox.mapboxsdk.plugins.locationlayer.LocationLayerPlugin;
import com.mapbox.services.android.location.LostLocationEngine;
import com.mapbox.services.android.navigation.ui.v5.NavigationLauncher;
import com.mapbox.services.android.navigation.ui.v5.NavigationViewOptions;
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.services.android.telemetry.location.LocationEngine;
import com.mapbox.services.android.telemetry.location.LocationEngineListener;
import com.mapbox.services.android.telemetry.location.LocationEnginePriority;
import com.mapbox.services.android.telemetry.permissions.PermissionsListener;
import com.mapbox.services.android.telemetry.permissions.PermissionsManager;
// classes to calculate a route
import com.mapbox.services.android.navigation.ui.v5.route.NavigationMapRoute;
import com.mapbox.services.android.navigation.v5.navigation.NavigationRoute;
import com.mapbox.api.directions.v5.models.DirectionsResponse;
import com.mapbox.api.directions.v5.models.DirectionsRoute;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import java.util.List;
public class MainActivity extends AppCompatActivity implements LocationEngineListener, PermissionsListener {
private MapView mapView;
private MapboxMap map;
private PermissionsManager permissionsManager;
private LocationLayerPlugin locationPlugin;
private LocationEngine locationEngine;
private Location originLocation;
private Marker destinationMarker;
private LatLng originCoord;
private LatLng destinationCoord;
private Button button;
// variables for calculating and drawing a route
private Point originPosition;
private Point destinationPosition;
private DirectionsRoute currentRoute;
private static final String TAG = "DirectionsActivity";
private NavigationMapRoute navigationMapRoute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Mapbox.getInstance(this, getString(R.string.access_token));
setContentView(R.layout.activity_main);
mapView = (MapView) findViewById(R.id.mapView);
mapView.onCreate(savedInstanceState);
mapView.getMapAsync(new OnMapReadyCallback() {
#Override
public void onMapReady(final MapboxMap mapboxMap) {
map = mapboxMap;
enableLocationPlugin();
originCoord = new LatLng(originLocation.getLatitude(), originLocation.getLongitude());
mapboxMap.addOnMapClickListener(new MapboxMap.OnMapClickListener() {
#Override
public void onMapClick(#NonNull LatLng point) {
if (destinationMarker != null) {
mapboxMap.removeMarker(destinationMarker);
}
destinationCoord = point;
destinationMarker = mapboxMap.addMarker(new MarkerOptions()
.position(destinationCoord)
);
destinationPosition = Point.fromLngLat(destinationCoord.getLongitude(), destinationCoord.getLatitude());
originPosition = Point.fromLngLat(originCoord.getLongitude(), originCoord.getLatitude());
getRoute(originPosition, destinationPosition);
button.setEnabled(true);
button.setBackgroundResource(R.color.mapboxBlue);
};
});
};
});
button = findViewById(R.id.startButton);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Point origin = originPosition;
Point destination = destinationPosition;
// Pass in your Amazon Polly pool id for speech synthesis using Amazon Polly
// Set to null to use the default Android speech synthesizer
String awsPoolId = null;
boolean simulateRoute = false;
NavigationViewOptions options = NavigationViewOptions.builder()
.origin(origin)
.destination(destination)
.awsPoolId(awsPoolId)
.shouldSimulateRoute(simulateRoute)
.build();
// Call this method with Context from within an Activity
NavigationLauncher.startNavigation(MainActivity.this, options);
}
});
}
#SuppressWarnings( {"MissingPermission"})
private void enableLocationPlugin() {
// Check if permissions are enabled and if not request
if (PermissionsManager.areLocationPermissionsGranted(this)) {
// Create an instance of LOST location engine
initializeLocationEngine();
locationPlugin = new LocationLayerPlugin(mapView, map, locationEngine);
locationPlugin.setLocationLayerEnabled(LocationLayerMode.TRACKING);
} else {
permissionsManager = new PermissionsManager(this);
permissionsManager.requestLocationPermissions(this);
}
}
#SuppressWarnings( {"MissingPermission"})
private void initializeLocationEngine() {
locationEngine = new LostLocationEngine(MainActivity.this);
locationEngine.setPriority(LocationEnginePriority.HIGH_ACCURACY);
locationEngine.activate();
Location lastLocation = locationEngine.getLastLocation();
if (lastLocation != null) {
originLocation = lastLocation;
setCameraPosition(lastLocation);
} else {
locationEngine.addLocationEngineListener(this);
}
}
private void setCameraPosition(Location location) {
map.animateCamera(CameraUpdateFactory.newLatLngZoom(
new LatLng(location.getLatitude(), location.getLongitude()), 13));
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
permissionsManager.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
private void getRoute(Point origin, Point destination) {
NavigationRoute.builder()
.accessToken(Mapbox.getAccessToken())
.origin(origin)
.destination(destination)
.build()
.getRoute(new Callback<DirectionsResponse>() {
#Override
public void onResponse(Call<DirectionsResponse> call, Response<DirectionsResponse> response) {
// You can get the generic HTTP info about the response
Log.d(TAG, "Response code: " + response.code());
if (response.body() == null) {
Log.e(TAG, "No routes found, make sure you set the right user and access token.");
return;
} else if (response.body().routes().size() < 1) {
Log.e(TAG, "No routes found");
return;
}
currentRoute = response.body().routes().get(0);
// Draw the route on the map
if (navigationMapRoute != null) {
navigationMapRoute.removeRoute();
} else {
navigationMapRoute = new NavigationMapRoute(null, mapView, map, R.style.NavigationMapRoute);
}
navigationMapRoute.addRoute(currentRoute);
}
#Override
public void onFailure(Call<DirectionsResponse> call, Throwable throwable) {
Log.e(TAG, "Error: " + throwable.getMessage());
}
});
}
#Override
#SuppressWarnings( {"MissingPermission"})
protected void onStart() {
super.onStart();
if (locationEngine != null) {
locationEngine.requestLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStart();
}
mapView.onStart();
}
#Override
protected void onStop() {
super.onStop();
if (locationEngine != null) {
locationEngine.removeLocationUpdates();
}
if (locationPlugin != null) {
locationPlugin.onStop();
}
mapView.onStop();
}
#Override
protected void onDestroy() {
super.onDestroy();
mapView.onDestroy();
if (locationEngine != null) {
locationEngine.deactivate();
}
}
#Override
public void onLowMemory() {
super.onLowMemory();
mapView.onLowMemory();
}
#Override
protected void onResume() {
super.onResume();
mapView.onResume();
}
#Override
protected void onPause() {
super.onPause();
mapView.onPause();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
mapView.onSaveInstanceState(outState);
}
#Override
public void onConnected() {
}
#Override
public void onLocationChanged(Location location) {
}
#Override
public void onExplanationNeeded(List<String> permissionsToExplain) {
}
#Override
public void onPermissionResult(boolean granted) {
}
}
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:mapbox="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="#+id/startButton"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:padding="5px"
android:layout_margin="20px"
android:text="Start navigation"
android:background="#color/mapboxGrayLight"
android:textColor="#color/mapboxWhite"
android:enabled="false"/>
<com.mapbox.mapboxsdk.maps.MapView
android:id="#+id/mapView"
android:layout_width="match_parent"
android:layout_height="match_parent"
mapbox:mapbox_cameraTargetLat="38.9098"
mapbox:mapbox_cameraTargetLng="-77.0295"
mapbox:mapbox_styleUrl="mapbox://styles/mapbox/streets-v10"
mapbox:mapbox_cameraZoom="12" />
</RelativeLayout>
build.gradle
android {
compileSdkVersion 26
defaultConfig {
applicationId "com.adailtonribeiro.android_navigator"
minSdkVersion 19
targetSdkVersion 26
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
repositories {
mavenCentral()
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:26.1.0'
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.1'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.1'
implementation 'com.mcxiaoke.volley:library:1.0.19'
implementation ('com.mapbox.mapboxsdk:mapbox-android-sdk:5.5.0#aar') {
transitive=true
}
implementation 'com.mapbox.mapboxsdk:mapbox-android-navigation:0.11.1'
implementation ('com.mapbox.mapboxsdk:mapbox-android-navigation-ui:0.11.1') {
transitive = true
}
implementation 'com.mapbox.mapboxsdk:mapbox-android-plugin-locationlayer:0.4.0'
}
buildscript {
repositories {
google()
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.2.1'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.adailtonribeiro.android_navigator">
<!-- Coarse location -->
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<!-- Or fine location -->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
I am looking to list the friends who are Facebook contacts and also have the app. It has shown a couple of times, but usually doesn't work.
I have no idea why. When I run the debugger, it says that I have a NullPointerException error on the following line:
friendslist = new JSONArray(jsondata);
I have tried a lot to work this out, so if you can let me know where my code goes wrong, I'll be very grateful.
I have included important pages below:
LoginActivity:
package com.phinder.phinder;
import android.Manifest;
import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.Signature;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.phinder.phinder.utils.ApiServices;
import com.phinder.phinder.utils.Constants;
import com.phinder.phinder.utils.MyLinks;
import org.json.JSONObject;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.FacebookSdk;
import com.facebook.GraphRequest;
import com.facebook.GraphRequestAsyncTask;
import com.facebook.GraphResponse;
import com.facebook.HttpMethod;
import com.facebook.appevents.AppEventsLogger;
import com.facebook.login.LoginManager;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.util.Arrays;
public class LoginActivity extends AppCompatActivity /*implements View.OnClickListener*/ {
private final int REQUEST_READ_WRITE_PERMISSION = 3, REQUEST_CAMERA_PERMISSION = 4;
CallbackManager callbackManager;
AccessToken accessToken;
Retrofit retrofit;
ApiServices apiServices;
AppCompatActivity activity;
SharedPreferences.Editor editor;
LoginButton loginButton;
Toolbar toolbar;
private String profileUri = "", id = "", name = "", email = "";
private Constants constants;
private MyLinks myLinks;
private ProgressDialog progressDialog;
private boolean isReadWritePermitted = false, isCameraPermitted = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
facebookSDKInitialize();
setContentView(R.layout.activity_login);
Constants.loginSharedPreferences = getSharedPreferences(Constants.LoginPref, MODE_PRIVATE);
activity = LoginActivity.this;
myLinks = new MyLinks(activity);
constants = new Constants();
editor = Constants.loginSharedPreferences.edit();
toolbar = (Toolbar) findViewById(R.id.toolbar_activity_login);
setSupportActionBar(toolbar);
printKeyHash();
List<String> permission = new ArrayList<String>();
permission.add("email");
permission.add("public_profile");
permission.add("user_location");
permission.add("user_birthday");
permission.add("user_friends");
progressDialog = new ProgressDialog(activity);
OkHttpClient okHttpClient = new OkHttpClient.Builder()
.connectTimeout(30, TimeUnit.SECONDS)
.readTimeout(30, TimeUnit.SECONDS)
.writeTimeout(30, TimeUnit.SECONDS)
.build();
retrofit = new Retrofit.Builder()
.baseUrl(myLinks.DEFAULT_URL)
.client(okHttpClient)
.addConverterFactory(GsonConverterFactory.create())
.build();
apiServices = retrofit.create(ApiServices.class);
loginButton = (LoginButton) findViewById(R.id.login_button);
loginButton.setReadPermissions(permission);
getLoginDetails(loginButton);
}
private void requestPermission() {
if (ContextCompat.checkSelfPermission(activity, Manifest.permission.WRITE_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED ||
ContextCompat.checkSelfPermission(activity, Manifest.permission.READ_EXTERNAL_STORAGE)
== PackageManager.PERMISSION_GRANTED) {
isReadWritePermitted = true;
} else {
// Show rationale and request permission.
ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
Manifest.permission.READ_EXTERNAL_STORAGE}, REQUEST_READ_WRITE_PERMISSION);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_READ_WRITE_PERMISSION) {
if (permissions.length > 0) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
isReadWritePermitted = true;
getLoginDetails(loginButton);
} else {
isReadWritePermitted = false;
}
}
} else {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
private void facebookSDKInitialize() {
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
private void getLoginDetails(final LoginButton loginButton) {
loginButton.registerCallback(callbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
loginButton.setVisibility(View.INVISIBLE);
progressDialog.show();
Log.d("msg", "Facebook");
accessToken = AccessToken.getCurrentAccessToken();
SharedPreferences.Editor editor = Constants.loginSharedPreferences
.edit();
editor.putString(constants.LoginId, accessToken.getUserId());
editor.apply();
Log.d("msg", "fbid : " + accessToken.getUserId());
onSuccessFullLogIn(accessToken);
GraphRequestAsyncTask graphRequestAsyncTask = new GraphRequest(
loginResult.getAccessToken(),
//AccessToken.getCurrentAccessToken(),
"/me/friends",
null,
HttpMethod.GET,
new GraphRequest.Callback() {
public void onCompleted(GraphResponse response) {
Intent intent = new Intent(LoginActivity.this,MainActivity.class);
try {
JSONArray rawName = response.getJSONObject().getJSONArray("data");
intent.putExtra("jsondata", rawName.toString());
startActivity(intent);
} catch (JSONException e) {
e.printStackTrace();
}
}
}
).executeAsync();
}
#Override
public void onCancel() {
}
#Override
public void onError(FacebookException error) {
}
});
}
public void onSuccessFullLogIn(final AccessToken accessToken) {
Bundle params = new Bundle();
params.putString("fields", "id,name,location,email,picture.type(large)");
new GraphRequest(accessToken, "me", params, HttpMethod.GET, new GraphRequest.Callback() {
#Override
public void onCompleted(GraphResponse response) {
if (response != null) {
try {
Log.d("msg", "Fb data1 : " + response.toString() + "");
JSONObject data = response.getJSONObject();
Log.d("msg", "Fb data : " + data.toString() + "");
SharedPreferences.Editor editor = Constants.loginSharedPreferences
.edit();
if (data.has("picture")) {
profileUri = data.getJSONObject("picture")
.getJSONObject("data")
.getString("url");
if (profileUri.startsWith("http://")
|| profileUri
.startsWith("https://")) {
profileUri = profileUri.replace(
"http://", "").trim();
profileUri = profileUri.replace(
"https://", "").trim();
}
editor.putString(constants.LoginImage, profileUri);
}
if (data.has("name")) {
editor.putString(constants.LoginName, data.getString("name"));
}
//if (data.has("email")) {
// Log.d("email", data.getString("email"));
// editor.putString(constants.LoginEmail, data.getString("email"));
//}
//if (data.has("location")) {
// editor.putString("city", data
// .getJSONObject("location")
// .getString("name"));
//}
editor.putBoolean(constants.LoginStatus, true);
editor.apply();
LoginManager.getInstance().logOut();
} catch (Exception e) {
e.printStackTrace();
} finally {
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
progressDialog.dismiss();
// final ProgressDialog progressDialog = new ProgressDialog(LoginActivity.this);
// progressDialog.show();
// Call<ResponseBody> call = apiServices.socialCall(Constants.loginSharedPreferences.getString(constants.LoginName, ""),
// Constants.loginSharedPreferences.getString(constants.LoginId, ""),
// Constants.loginSharedPreferences.getString(constants.LoginEmail, ""),
// Constants.loginSharedPreferences.getString(constants.LoginImage, "")
// );
//
// call.enqueue(new Callback<ResponseBody>() {
// #Override
// public void onResponse(Call<ResponseBody> call, retrofit2.Response<ResponseBody> response) {
// try {
//
// String result = response.body().string();
//
// Log.d("msg", "Result : " + result);
//
//
// JSONObject jsonObject = new JSONObject(result);
//// progressDialog.dismiss();
//
//
// if (jsonObject != null && jsonObject.length() > 0) {
//
// JSONArray jsonArray = jsonObject.getJSONArray("response");
//
// Log.d("msg", "Json : " + jsonArray.toString());
//
// if (jsonArray != null && jsonArray.length() > 0) {
//
// for (int i = 0; i < jsonArray.length(); i++) {
//
// JSONObject jsonObject1 = jsonArray.getJSONObject(i);
//
// String status = jsonObject1.getString("status");
// String id = jsonObject1.getString("id");
//
// SharedPreferences.Editor editor = Constants.loginSharedPreferences.edit();
// editor.putString(constants.UserId, id);
// editor.apply();
//
// if (status.equals("one") || status.equals("zero")) {
// startActivity(new Intent(activity, MainActivity.class));
// finish();
//
// } else {
// Toast.makeText(activity, "Invalid login", Toast.LENGTH_LONG).show();
// }
// }
// }
// }
//
// } catch (IOException e) {
// e.getStackTrace();
//
// Log.d("msg", "IO " + e.getMessage());
// progressDialog.dismiss();
// } catch (JSONException e) {
//
// e.printStackTrace();
// Log.d("msg", "JSON " + e.getMessage());
// progressDialog.dismiss();
// }
// }
//
// #Override
// public void onFailure(Call<ResponseBody> call, Throwable t) {
// Log.d("msg", "JSON " + t.getMessage());
//
// progressDialog.dismiss();
// }
// });
}
}
}
}).executeAsync();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
callbackManager.onActivityResult(requestCode, resultCode, data);
// Log.d("data",data.toString());
}
#Override
protected void onResume() {
super.onResume();
AppEventsLogger.activateApp(LoginActivity.this, "369622066719726");
}
#Override
protected void onPause() {
super.onPause();
AppEventsLogger.deactivateApp(LoginActivity.this, "369622066719726");
}
public String printKeyHash() {
PackageInfo packageInfo;
String key = null;
try {
//getting application package name, as defined in manifest
String packageName = getApplicationContext().getPackageName();
//Retriving package info
packageInfo = getPackageManager().getPackageInfo(packageName,
PackageManager.GET_SIGNATURES);
Log.d("Package Name=", getApplicationContext().getPackageName());
for (Signature signature : packageInfo.signatures) {
MessageDigest md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
key = new String(Base64.encode(md.digest(), 0));
// String key = new String(Base64.encodeBytes(md.digest()));
Log.d("Key Hash=", key);
// ST4ot689mPBUodJzQxMIutXIkKw=
}
} catch (PackageManager.NameNotFoundException e1) {
Log.e("Name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.d("No such an algorithm", e.toString());
} catch (Exception e) {
Log.d("Exception", e.toString());
}
return key;
}
}
MainActivity:
package com.phinder.phinder;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import org.json.JSONArray;
import org.json.JSONException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
ImageView imageView_picture_profile;
TextView textview_nameprofile,textview_emailprofile;
public com.phinder.phinder.utils.Constants constants;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// User Information
constants = new com.phinder.phinder.utils.Constants();
imageView_picture_profile = (ImageView)findViewById(R.id.imageView_picture_profile);
//textview_emailprofile = (TextView) findViewById(R.id.textview_emailprofile);
textview_nameprofile = (TextView)findViewById(R.id.textview_nameprofile);
//textview_emailprofile.setText(constants.loginSharedPreferences.getString(constants.LoginEmail, ""));
textview_nameprofile.setText(constants.loginSharedPreferences.getString(constants.LoginName, ""));
try {
Glide.with(getApplicationContext())
.load("http://" + constants.loginSharedPreferences.getString(constants.LoginImage, ""))
.placeholder(R.mipmap.ic_launcher)
.thumbnail(.1F)
.error(R.mipmap.ic_launcher)
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(imageView_picture_profile);
} catch (Exception e) {
e.getStackTrace();
Log.d("msg", "Photo " + e.getMessage());
}
//ListView Facebook Friends
Intent intent = getIntent();
String jsondata = intent.getStringExtra("jsondata");
JSONArray friendslist;
ArrayList<String> friends = new ArrayList<String>();
try {
friendslist = new JSONArray(jsondata);
for (int l=0; l < friendslist.length(); l++) {
friends.add(friendslist.getJSONObject(l).getString("name"));
}
} catch (JSONException e) {
e.printStackTrace();
}
ArrayAdapter adapter = new ArrayAdapter<String>(this, R.layout.activity_listview, friends); // simple textview for list item
ListView listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
}
}
Okay guys, I was playing about with it and I found out what the issue was, finally!
I had a duplicate token access request in LoginActivity.java which was causing this issue.
onSuccessFullLogIn(accessToken);
when I commented this out, it worked perfectly
I know I'm answering my own question here, but I noticed this issue is around the internet a lot, with no real answer, so I hope it's useful for some people!
package com.example.notificationlistener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
public class NotificationService extends NotificationListenerService {
Context context;
#Override
public void onCreate() {
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn)
{
Log.i("From service","onNotificationPosted");
String pack = sbn.getPackageName();
// if("com.twitter.android".equalsIgnoreCase(pack))
// if("com.google.android.gm".equalsIgnoreCase(pack))
{
String ticker = sbn.getNotification().tickerText.toString();
Bundle extras = sbn.getNotification().extras;
String title = extras.getString("android.title");
String text = extras.getCharSequence("android.text").toString();
Log.i("Package",pack);
Log.i("Ticker",ticker);
Log.i("Title",title);
Log.i("Text",text);
Intent msgrcv = new Intent("Msg");
msgrcv.putExtra("package", pack);
msgrcv.putExtra("ticker", ticker);
msgrcv.putExtra("title", title);
msgrcv.putExtra("text", text);
LocalBroadcastManager.getInstance(context).sendBroadcast(msgrcv);
}
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn)
{
Log.i("Msg","Notification Removed");
}
}
this is my service class
package com.example.notificationlistener;
import java.util.Locale;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.ActionBarActivity;
import android.text.Html;
import android.util.Log;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;
public class MainActivity extends ActionBarActivity implements TextToSpeech.OnInitListener{
TableLayout tableLayout;
TextToSpeech textToSpeech;
String text = "noText";
String title = "noTitle";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tableLayout = (TableLayout)findViewById(R.id.tab);
textToSpeech = new TextToSpeech(this, null);
LocalBroadcastManager.getInstance(this).registerReceiver(onNotice, new IntentFilter("Msg"));
}
private BroadcastReceiver onNotice= new BroadcastReceiver() {
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
Log.w("From MainActivity", "broadcast receiver is called");
String pack = intent.getStringExtra("package");
String ticker = intent.getStringExtra("ticker");
title = intent.getStringExtra("title");
text = intent.getStringExtra("text");
Log.d("mainActivity_pack", pack);
Log.d("mainActivity_title", title);
Log.d("mainActivity_text", text);
Log.d("mainActivity_ticker", ticker);
// Log.d("mainActivity", sender);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.ic_launcher, "New Message", System.currentTimeMillis()+5000);
notification.setLatestEventInfo(context, title, text, null);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
notificationManager.notify(2, notification);
speak();
TableRow tr = new TableRow(getApplicationContext());
tr.setLayoutParams(new TableRow.LayoutParams( TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT));
TextView textview = new TextView(getApplicationContext());
textview.setLayoutParams(new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT,1.0f));
textview.setTextSize(20);
textview.setTextColor(Color.parseColor("#0B0719"));
textview.setText(Html.fromHtml(pack +"<br><b>" + title + " : </b>" + text));
tr.addView(textview);
tableLayout.addView(tr);
}
};
protected void onDestroy()
{
super.onDestroy();
if (textToSpeech != null)
{
textToSpeech.stop();
textToSpeech.shutdown();
}
LocalBroadcastManager.getInstance(this).unregisterReceiver(onNotice);
}
#Override
public void onInit(int status) {
if (status == TextToSpeech.SUCCESS) {
int result = textToSpeech.setLanguage(Locale.US);
if (result == TextToSpeech.LANG_MISSING_DATA
|| result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e("TTS", "This Language is not supported");
} else
{
speak();
}
} else {
Log.e("TTS", "Initilization Failed!");
}
}
private void speak()
{
textToSpeech.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}`enter code here`
}
this is my activity. i am trying to read notification and resend them through my app so done this and i am able to get the notifications but when my app is closed its not working so please suggest me some changes or suggestions...thanks
Put your broadcast receiver into a service. Activities don't run when the app is closed. Services do. Start your services from your activity. Then they will continue to run even after closing the app.