Now that FusedLocationApi is deprecated how can i implement FusedLocationProvideClient when i also have location listener? - locationlistener

I'm building a class that tracks orders origin to deliver packages, im getting an error message that states that FusedLocationProviderApi is deprecated and seems now i have to use FusedLocationProviderClient instead, when i applied FusedLocationProviderApi i also implemented a LocationListener a ConnectionCallback and GoogleaApiClient which i suppose should be removed.
how can i implemente this here
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracking_order);
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
requestRuntimePermission();
}
else
{
if (checkPlayServices())
{
buildGoogleApiClient();
createLocationRequest();
}
}
displayLocation();
}
private void displayLocation() {
if(ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&& ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
{
requestRuntimePermission();
}
else
{
mLastLocation = LocationServices.fused(null).getLastLocation(mGoogleApiClient);
if (mLastLocation != null)
{
double latitude = mLastLocation.getLatitude();
double longitude = mLastLocation.getLongitude();
LatLng yourLocation = new LatLng(latitude,longitude);
mMap.addMarker(new MarkerOptions().position(yourLocation).title("Tu ubicacion"));
mMap.moveCamera(CameraUpdateFactory.newLatLng(yourLocation));
mMap.animateCamera(CameraUpdateFactory.zoomTo(17.0f));
}
else
{
Toast.makeText(this, "No se pudo obtener ubicacion", Toast.LENGTH_SHORT).show();
}
}
}

ended up with a new approach that worked finer
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tracking_order);
mService = Common.geoCodeService();
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
mapFrag = (SupportMapFragment)getSupportFragmentManager().findFragmentById(R.id.map);
mapFrag.getMapAsync(this);
}
public void onMapReady(GoogleMap googleMap)
{
mMap=googleMap;
mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(120000); // two minute interval
mLocationRequest.setFastestInterval(120000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Location Permission already granted
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);
} else {
//Request Location Permission
checkLocationPermission();
}
}
else {
mFusedLocationClient.requestLocationUpdates(mLocationRequest, mLocationCallback, Looper.myLooper());
mMap.setMyLocationEnabled(true);
}
}
LocationCallback mLocationCallback = new LocationCallback(){
#Override
public void onLocationResult(LocationResult locationResult) {
for (Location location : locationResult.getLocations()) {
Log.i("MapsActivity", "Location: " + location.getLatitude() + " " + location.getLongitude());
mLastLocation = location;
if (mCurrLocationMarker != null) {
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng yourLocation = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(yourLocation);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mMap.addMarker(markerOptions);
//move map camera
mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(yourLocation, 11));
//after add marker for your location add marker for this order
drawRoute(yourLocation,Common.currentRequest.getAddress());
}
}
};

Related

Passing values from android to flutter but not from main activity

i'm implementing a third party android sdk in flutter and i want a message to be passed from android to flutter when sdk starts
i have implemented the sdk using platform channel just need to work on the callback code. In the code there is a function called onChannelJoin i want to send message to flutter when this function is called
Main Activity
public class MainActivity extends FlutterActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
final String CHANNEL = "samples.flutter.io/screen_record";
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(
new MethodChannel.MethodCallHandler() {
#Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
// TODO
if (call.method.equals("startScreenShare")) {
Intent intent = new Intent(MainActivity.this , HelloAgoraScreenSharingActivity.class);
startActivity(intent);
} else {
result.notImplemented();
}
}
});
}
}
ScreenSharingActivity
public class HelloAgoraScreenSharingActivity extends Activity {
private static final String LOG_TAG = "AgoraScreenSharing";
private static final int PERMISSION_REQ_ID_RECORD_AUDIO = 22;
private ScreenCapture mScreenCapture;
private GLRender mScreenGLRender;
private RtcEngine mRtcEngine;
private boolean mIsLandSpace = false;
private void initModules() {
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
if (mScreenGLRender == null) {
mScreenGLRender = new GLRender();
}
if (mScreenCapture == null) {
mScreenCapture = new ScreenCapture(getApplicationContext(), mScreenGLRender, metrics.densityDpi);
}
mScreenCapture.mImgTexSrcConnector.connect(new SinkConnector<ImgTexFrame>() {
#Override
public void onFormatChanged(Object obj) {
Log.d(LOG_TAG, "onFormatChanged " + obj.toString());
}
#Override
public void onFrameAvailable(ImgTexFrame frame) {
Log.d(LOG_TAG, "onFrameAvailable " + frame.toString());
if (mRtcEngine == null) {
return;
}
AgoraVideoFrame vf = new AgoraVideoFrame();
vf.format = AgoraVideoFrame.FORMAT_TEXTURE_OES;
vf.timeStamp = frame.pts;
vf.stride = frame.mFormat.mWidth;
vf.height = frame.mFormat.mHeight;
vf.textureID = frame.mTextureId;
vf.syncMode = true;
vf.eglContext14 = mScreenGLRender.getEGLContext();
vf.transform = frame.mTexMatrix;
mRtcEngine.pushExternalVideoFrame(vf);
}
});
mScreenCapture.setOnScreenCaptureListener(new ScreenCapture.OnScreenCaptureListener() {
#Override
public void onStarted() {
Log.d(LOG_TAG, "Screen Record Started");
}
#Override
public void onError(int err) {
Log.d(LOG_TAG, "onError " + err);
switch (err) {
case ScreenCapture.SCREEN_ERROR_SYSTEM_UNSUPPORTED:
break;
case ScreenCapture.SCREEN_ERROR_PERMISSION_DENIED:
break;
}
}
});
WindowManager wm = (WindowManager) getApplicationContext()
.getSystemService(Context.WINDOW_SERVICE);
int screenWidth = wm.getDefaultDisplay().getWidth();
int screenHeight = wm.getDefaultDisplay().getHeight();
if ((mIsLandSpace && screenWidth < screenHeight) ||
(!mIsLandSpace) && screenWidth > screenHeight) {
screenWidth = wm.getDefaultDisplay().getHeight();
screenHeight = wm.getDefaultDisplay().getWidth();
}
setOffscreenPreview(screenWidth, screenHeight);
if (mRtcEngine == null) {
try {
mRtcEngine = RtcEngine.create(getApplicationContext(), "Agora_id", new IRtcEngineEventHandler() {
#Override
public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
Log.d(LOG_TAG, "onJoinChannelSuccess " + channel + " " + elapsed);
}
#Override
public void onWarning(int warn) {
Log.d(LOG_TAG, "onWarning " + warn);
}
#Override
public void onError(int err) {
Log.d(LOG_TAG, "onError " + err);
}
#Override
public void onAudioRouteChanged(int routing) {
Log.d(LOG_TAG, "onAudioRouteChanged " + routing);
}
});
} catch (Exception e) {
Log.e(LOG_TAG, Log.getStackTraceString(e));
throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + Log.getStackTraceString(e));
}
mRtcEngine.setChannelProfile(Constants.CHANNEL_PROFILE_LIVE_BROADCASTING);
mRtcEngine.enableVideo();
if (mRtcEngine.isTextureEncodeSupported()) {
mRtcEngine.setExternalVideoSource(true, true, true);
} else {
throw new RuntimeException("Can not work on device do not supporting texture" + mRtcEngine.isTextureEncodeSupported());
}
mRtcEngine.setVideoProfile(Constants.VIDEO_PROFILE_360P, true);
mRtcEngine.setClientRole(Constants.CLIENT_ROLE_BROADCASTER);
}
}
private void deInitModules() {
RtcEngine.destroy();
mRtcEngine = null;
if (mScreenCapture != null) {
mScreenCapture.release();
mScreenCapture = null;
}
if (mScreenGLRender != null) {
mScreenGLRender.quit();
mScreenGLRender = null;
}
}
/**
* Set offscreen preview.
*
* #param width offscreen width
* #param height offscreen height
* #throws IllegalArgumentException
*/
public void setOffscreenPreview(int width, int height) throws IllegalArgumentException {
if (width <= 0 || height <= 0) {
throw new IllegalArgumentException("Invalid offscreen resolution");
}
mScreenGLRender.init(width, height);
}
private void startCapture() {
mScreenCapture.start();
}
private void stopCapture() {
mScreenCapture.stop();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_agora_screen_sharing);
}
public void onLiveSharingScreenClicked(View view) {
Button button = (Button) view;
boolean selected = button.isSelected();
button.setSelected(!selected);
if (button.isSelected()) {
initModules();
startCapture();
String channel = "ss_test" + System.currentTimeMillis();
channel = "ss_test";
button.setText("stop");
mRtcEngine.muteAllRemoteAudioStreams(true);
mRtcEngine.muteAllRemoteVideoStreams(true);
mRtcEngine.joinChannel(null, channel, "", 0);
} else {
button.setText("start");
mRtcEngine.leaveChannel();
stopCapture();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
deInitModules();
}
}
Dart Code
const platform = const MethodChannel('samples.flutter.io/screen_record');
try {
final int result = await platform.invokeMethod('startScreenShare');
} on PlatformException catch (e) {}
setState(() {
});

AutoCompleteTextField list does not always scroll to top?

The AutoCompleteTextField seems to work exactly as intended until I start backspacing in the TextField. I am not sure what the difference is, but if I type in something like "123 M" then I get values that start with "123 M". If I backspace and delete the M leaving "123 " in the field, the list changes, but it does not scroll to the top of the list.
I should note that everything works fine on the simulator and that I am experiencing this behavior when running a debug build on my iPhone.
EDIT: So this does not only seem to happen when backspacing. This image shows the results I have when typing in an address key by key. In any of the pictures where the list isn't viewable or is clipped, I am able to drag down on the list to get it to then display properly. I have not tried this on an Android device.
EDIT2:
public class CodenameOneTest {
private Form current;
private Resources theme;
private WaitingClass w;
private String[] properties = {"1 MAIN STREET", "123 E MAIN STREET", "12 EASTER ROAD", "24 MAIN STREET"};
public void init(Object context) {
theme = UIManager.initFirstTheme("/theme");
// Enable Toolbar on all Forms by default
Toolbar.setGlobalToolbar(true);
}
public void start() {
if(current != null) {
current.show();
return;
}
Form form = new Form("AutoCompleteTextField");
form.setLayout(new BorderLayout());
final DefaultListModel<String> options = new DefaultListModel<>();
AutoCompleteTextField ac = new AutoCompleteTextField(options) {
protected boolean filter(String text) {
if(text.length() == 0) {
options.removeAll();
return false;
}
String[] l = searchLocations(text);
if(l == null || l.length == 0) {
return false;
}
options.removeAll();
for(String s : l) {
options.addItem(s);
}
return true;
};
};
Container container = new Container(BoxLayout.y());
container.setScrollableY(true); // If you comment this out then the field works fine
container.add(ac);
form.addComponent(BorderLayout.CENTER, container);
form.show();
}
String[] searchLocations(String text) {
try {
if(text.length() > 0) {
if(w != null) {
w.actionPerformed(null);
}
w = new WaitingClass();
String[] properties = getProperties(text);
if(Display.getInstance().isEdt()) {
Display.getInstance().invokeAndBlock(w);
}
else {
w.run();
}
return properties;
}
}
catch(Exception e) {
Log.e(e);
}
return null;
}
private String[] getProperties(String text) {
List<String> returnList = new ArrayList<>();
List<String> propertyList = Arrays.asList(properties);
for(String property : propertyList) {
if(property.startsWith(text)) {
returnList.add(property);
}
}
w.actionPerformed(null);
return returnList.toArray(new String[returnList.size()]);
}
class WaitingClass implements Runnable, ActionListener<ActionEvent> {
private boolean finishedWaiting;
public void run() {
while(!finishedWaiting) {
try {
Thread.sleep(30);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
public void actionPerformed(ActionEvent e) {
finishedWaiting = true;
return;
}
}
public void stop() {
current = Display.getInstance().getCurrent();
if(current instanceof Dialog) {
((Dialog)current).dispose();
current = Display.getInstance().getCurrent();
}
}
public void destroy() {
}
}
I used this code on an iPhone 4s:
public void start() {
if(current != null){
current.show();
return;
}
Form hi = new Form("AutoComplete", new BorderLayout());
if(apiKey == null) {
hi.add(new SpanLabel("This demo requires a valid google API key to be set in the constant apiKey, "
+ "you can get this key for the webservice (not the native key) by following the instructions here: "
+ "https://developers.google.com/places/web-service/get-api-key"));
hi.getToolbar().addCommandToRightBar("Get Key", null, e -> Display.getInstance().execute("https://developers.google.com/places/web-service/get-api-key"));
hi.show();
return;
}
Container box = new Container(new BoxLayout(BoxLayout.Y_AXIS));
box.setScrollableY(true);
for(int iter = 0 ; iter < 30 ; iter++) {
box.add(createAutoComplete());
}
hi.add(BorderLayout.CENTER, box);
hi.show();
}
private AutoCompleteTextField createAutoComplete() {
final DefaultListModel<String> options = new DefaultListModel<>();
AutoCompleteTextField ac = new AutoCompleteTextField(options) {
#Override
protected boolean filter(String text) {
if(text.length() == 0) {
return false;
}
String[] l = searchLocations(text);
if(l == null || l.length == 0) {
return false;
}
options.removeAll();
for(String s : l) {
options.addItem(s);
}
return true;
}
};
ac.setMinimumElementsShownInPopup(5);
return ac;
}
String[] searchLocations(String text) {
try {
if(text.length() > 0) {
ConnectionRequest r = new ConnectionRequest();
r.setPost(false);
r.setUrl("https://maps.googleapis.com/maps/api/place/autocomplete/json");
r.addArgument("key", apiKey);
r.addArgument("input", text);
NetworkManager.getInstance().addToQueueAndWait(r);
Map<String,Object> result = new JSONParser().parseJSON(new InputStreamReader(new ByteArrayInputStream(r.getResponseData()), "UTF-8"));
String[] res = Result.fromContent(result).getAsStringArray("//description");
return res;
}
} catch(Exception err) {
Log.e(err);
}
return null;
}
I was able to create this issue but not the issue you describe.

Camera in Android app

I am creating an app which required to perform from API 15 to API 23 using camera so what should be the best way to implement camera as camera class is deprecated in API 21 and also android.hardware.camera2 not able to implement on lower version then API 21.
The below code is something I have taken out of one of my projects, it has had a lot of stuff ripped out for the purpose of putting it on here so you will have to edit it for your needs. It uses the original camera api which is back compatible for your api needs.
public class RecordGameKam extends Fragment
implements TextureView.SurfaceTextureListener, View.OnClickListener {
private final static String TAG = "CameraRecordTexture";
private Camera mCamera;
private TextureView mTextureView;
int numberOfCameras;
int defaultCameraId;
private boolean isRecording = false;
protected MediaRecorder mediaRecorder;
#SuppressWarnings("ConstantConditions")
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
View rootView = new RelativeLayout(getActivity());
mTextureView = new TextureView(getActivity());
mTextureView.setSurfaceTextureListener(this);
//View parameters-----------------------------------------------------------------------
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
rootView.setLayoutParams(params);
((ViewGroup) rootView).addView(mTextureView);
return rootView;
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
mCamera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT);
// Find the total number of cameras available
numberOfCameras = Camera.getNumberOfCameras();
// Find the ID of the default camera
Camera.CameraInfo cameraInfo = new Camera.CameraInfo();
for (int i = 0; i < numberOfCameras; i++) {
Camera.getCameraInfo(i, cameraInfo);
if (cameraInfo.facing == Camera.CameraInfo.CAMERA_FACING_BACK) {
defaultCameraId = i;
}
}
try {
if (mCamera != null) {
//final Camera.Size previewSize = onMeasure();
//Camera.Size recorderSize = previewSize;
final Camera.Parameters params = mCamera.getParameters();
params.setPreviewSize(720, 480);
mCamera.setParameters(params);
mCamera.setDisplayOrientation(90);
mCamera.setPreviewTexture(surface);
mCamera.startPreview();
startContinuousAutoFocus();
}
} catch (IOException ioe) {
// Something bad happened
mCamera.release();
mCamera = null;
}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
// Ignored, Camera does all the work for us
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
try {
if (getActivity().getActionBar() != null) {
getActivity().getActionBar().show();
}
} catch (Exception e) {
e.printStackTrace();
}
releaseMediaRecorder();
return true;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
// Invoked every time there's a new Camera preview frame
}
private boolean setMediaRecorder() throws IllegalStateException {
try {
//Create a new instance of MediaRecorder.
mediaRecorder = new MediaRecorder();
//Unlock and set camera to Media recorder
mCamera.unlock();
mediaRecorder.setCamera(mCamera);
//Configure audio/video input
mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
CamcorderProfile profile = null;
if (CamcorderProfile.hasProfile(CamcorderProfile.QUALITY_480P)) {
profile = CamcorderProfile.get(CamcorderProfile.QUALITY_480P);
}
if (profile != null) {
mediaRecorder.setProfile(profile);
}
//Change oritentation
mediaRecorder.setOrientationHint(90 - 180 + 360);
mediaRecorder.setOutputFile(getFilename());
} catch (Exception e) {
e.printStackTrace();
}
//Attempt to prepare the configuration and record video.
try {
button.setBackgroundResource(R.drawable.camera_pressed);
mediaRecorder.prepare();
} catch (Exception e) {
e.printStackTrace();
mediaRecorder.release();
return false;
}
return true;
}
boolean startContinuousAutoFocus() {
Camera.Parameters params = mCamera.getParameters();
List<String> focusModes = params.getSupportedFocusModes();
assert focusModes != null;
String CAF_PICTURE = Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE,
CAF_VIDEO = Camera.Parameters.FOCUS_MODE_CONTINUOUS_VIDEO,
supportedMode = focusModes
.contains(CAF_PICTURE) ? CAF_PICTURE : focusModes
.contains(CAF_VIDEO) ? CAF_VIDEO : "";
if (!supportedMode.equals("")) {
params.setFocusMode(supportedMode);
mCamera.setParameters(params);
return true;
}
return false;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
enter code here

I am working with facebook game request

I finished working with sending the request with android reading https://developers.facebook.com/docs/howtos/androidsdk/3.0/send-requests/
but i'm having a problem with handling requests.
https://developers.facebook.com/docs/howtos/androidsdk/3.0/app-link-requests/
I think I did what it told me to do, but I can't get the uri and the requestid
they are all null.
I thing the problem is that when I receive a request I can't click the accept button.
It says that the playstore can't find the app. So the request doesn't disappear.
How can I solve the problem?
public class MainActivity extends Activity {
private static final List<String> PERMISSIONS = Arrays
.asList("read_requests");
private Bundle SIS;
private Session.StatusCallback logincallback = new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
if (session.isOpened()) {
updateview();
getp();
loginlogoutbutton.setText("Login");
onSessionStateChange(session, state, exception);
} else {
}
}
};
public void updateview() {
Session session = Session.getActiveSession();
if (session.isOpened()) {
Request.executeMeRequestAsync(session,
new Request.GraphUserCallback() {
public void onCompleted(GraphUser user,
Response response) {
if (user != null) {
tt.setText(user.getId());
}
}
});
} else
{
tt.setText("Login");
}
}
private Button loginlogoutbutton;
private Button sendrequestbutton;
private Button testbtn;
private TextView tt;
private String app_id = "APP ID";
private String requestId;
public void getp() {
Session session = Session.getActiveSession();
if (session == null || !session.isOpened()) {
return;
}
List<String> permissions = session.getPermissions();
if (!permissions.containsAll(PERMISSIONS)) {
session.requestNewPublishPermissions(new Session.NewPermissionsRequest(
this, PERMISSIONS)
.setCallback(new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state,
Exception exception) {
// TODO Auto-generated method stub
}
}));
} else {
}
}
#Override
public void onResume() {
super.onResume();
checkforrequest();
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
SIS = savedInstanceState;
tt = (TextView) findViewById(R.id.tex);
loginlogoutbutton = (Button) findViewById(R.id.loginlogoutbtn);
loginlogoutbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
onClickLoginLogout();
}
});
sendrequestbutton = (Button) findViewById(R.id.sendrequest);
sendrequestbutton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
sendRequestDialog();
}
});
testbtn = (Button) findViewById(R.id.button1);
testbtn.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
checkforrequest();
}
});
ConfirmLogin(app_id);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Session.getActiveSession().onActivityResult(this, requestCode,
resultCode, data);
}
public boolean ConfirmLogin(String iappid) {
app_id = iappid;
Session session = Session.getActiveSession();
boolean dd = true;
if (session == null) {
if (SIS != null) {
session = Session.restoreSession(this, null,
new Session.StatusCallback() {
#Override
public void call(Session session,
SessionState state, Exception exception) {
// TODO Auto-generated method stub
}
}, SIS);
}
if (session == null) {
session = new Session.Builder(this).setApplicationId(app_id)
.build();
}
Session.setActiveSession(session);
if (session.getState().equals(SessionState.CREATED_TOKEN_LOADED)) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
dd = true;
} else {
dd = false;
}
}
return dd;
}
public void onClickLoginLogout() {
Session session = Session.getActiveSession();
if (!session.isOpened() && !session.isClosed()) {
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
} else if (session.isClosed()) {
session = new Session.Builder(this).setApplicationId(app_id)
.build();
Session.setActiveSession(session);
session.openForRead(new Session.OpenRequest(this)
.setCallback(logincallback));
} else {
session.closeAndClearTokenInformation();
loginlogoutbutton.setText("Login");
}
}
private void sendRequestDialog() {
Bundle params = new Bundle();
params.putString("message",
"Learn how to make your Android apps social");
params.putString("data", "{\"badge_of_awesomeness\":\"1\","
+ "\"social_karma\":\"5\"}");
WebDialog requestsDialog = (new WebDialog.RequestsDialogBuilder(this,
Session.getActiveSession(), params)).setOnCompleteListener(
new OnCompleteListener() {
#Override
public void onComplete(Bundle values,
FacebookException error) {
if (error != null) {
if (error instanceof FacebookOperationCanceledException) {
} else {
}
} else {
final String requestId = values
.getString("request");
if (requestId != null) {
maketoast(requestId);
} else {
}
}
}
}).build();
requestsDialog.show();
}
public void checkforrequest() {
maketoast("0");
Uri intentUri = this.getIntent().getData();
if (intentUri != null) {
String requestIdParam = intentUri.getQueryParameter("request_ids");
maketoast("1 : " +requestIdParam);
if (requestIdParam != null) {
String array[] = requestIdParam.split(",");
requestId = array[0];
}
}
else
{
maketoast("uri = null");
}
}
public void maketoast(String message) {
Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
}
private void getRequestData(final String inRequestId) {
// Create a new request for an HTTP GET with the
// request ID as the Graph path.
maketoast("2");
Request request = new Request(Session.getActiveSession(), inRequestId,
null, HttpMethod.GET, new Request.Callback() {
#Override
public void onCompleted(Response response) {
// Process the returned response
GraphObject graphObject = response.getGraphObject();
FacebookRequestError error = response.getError();
// Default message
String message = "Incoming request";
if (graphObject != null) {
// Check if there is extra data
if (graphObject.getProperty("data") != null) {
try {
// Get the data, parse info to get the
// key/value info
JSONObject dataObject = new JSONObject(
(String) graphObject
.getProperty("data"));
// Get the value for the key -
// badge_of_awesomeness
String badge = dataObject
.getString("badge_of_awesomeness");
// Get the value for the key - social_karma
String karma = dataObject
.getString("social_karma");
// Get the sender's name
JSONObject fromObject = (JSONObject) graphObject
.getProperty("from");
String sender = fromObject
.getString("name");
String title = sender + " sent you a gift";
// Create the text for the alert based on
// the sender
// and the data
message = title + "\n\n" + "Badge: "
+ badge + " Karma: " + karma;
} catch (JSONException e) {
message = "Error getting request info";
}
} else if (error != null) {
message = "Error getting request info";
}
}
maketoast(message);
}
});
// Execute the request asynchronously.
Request.executeBatchAsync(request);
}
private void onSessionStateChange(Session session, SessionState state,
Exception exception) {
// Check if the user is authenticated and
// an incoming notification needs handling
if (state.isOpened() && requestId != null) {
maketoast("3");
getRequestData(requestId);
requestId = null;
} else if (requestId == null) {
maketoast("4");
}
if (state.isOpened()) {
} else if (state.isClosed()) {
}
}
}
this is the code.

WP - How to constantly update my location

Currently my location not updating when I change it to different location via emulator. But it will change after I restart my application. This is what I write when the app launch
private void Application_Launching(object sender, LaunchingEventArgs e)
{
IsolatedStorageSettings Settings = IsolatedStorageSettings.ApplicationSettings;
GeoCoordinate DefaultLocation = new GeoCoordinate(-6.595139, 106.793801);
Library.GPSServices MyGPS;
if (!Settings.Contains("FirstLaunch") || (bool)Settings["FirstLaunch"] == true)
{
Settings["FirstLaunch"] = false;
Settings["LastLocation"] = DefaultLocation;
Settings["SearchRadius"] = 1;
}
//If key not exist OR key value was set to false, ask for permission to use location
if (!Settings.Contains("LocationService") || (bool)Settings["LocationService"] == false)
{
var result = MessageBox.Show(
"Jendela Bogor need to know your location to work correctly, do you want to allow it?",
"Allow access to your location?",
MessageBoxButton.OKCancel);
if (result == MessageBoxResult.OK)
{
Settings["LocationService"] = true;
MyGPS = new Library.GPSServices();
}
else
{
Settings["LocationService"] = false;
}
Settings.Save();
}
else if ((bool)Settings["LocationService"] == true)
{
MyGPS = new Library.GPSServices();
}
}
I store my location in my application setting IsolatedStorage with name Settings["LastLocation"]
How should I do to constantly update my location in the Background using MVVM Pattern (MVVM-Light) so my PushPin on map in the ThirdPageView always updated?
EDIT
public GPSServices()
{
if ((bool)Settings["LocationService"] == true)
{
if (_watcher == null)
{
_watcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
_watcher.MovementThreshold = 20;
}
StartWatcher();
_watcher.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(watcher_PositionChanged);
_watcher.StatusChanged += new EventHandler<GeoPositionStatusChangedEventArgs>(watcher_StatusChanged);
}
else if ((bool)Settings["LocationService"] == false)
{
StopWatcher();
}
}
private void StartWatcher()
{
_watcher.Start();
}
private void StopWatcher()
{
if (_watcher != null)
_watcher.Stop();
}
private void watcher_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
if (e.Position.Location.IsUnknown)
{
MessageBox.Show("Please wait while your position is determined....");
return;
}
Settings["LastLocation"] = e.Position.Location;
Settings.Save();
}
System.Device.Location.GeoCoordinateWatcher provides what you need.
var geoWatcher = new GeoCoordinateWatcher(GeoPositionAccuracy.High);
// This event fires every time the device location changes
geoWatcher.PositionChanged += (s, e) => {
//e.Position.Location will contain the current GeoCoordinate
};
geoWatcher.TryStart(false, TimeSpan.FromMilliseconds(2000));
is this helpful for you ? using GeocoordinateWatcher.PositionChanged event?
public Location()
{
GeoCoordinateWatcher location == new GeoCoordinateWatcher();
location.PositionChanged += new EventHandler<GeoPositionChangedEventArgs<GeoCoordinate>>(location_PositionChanged);
location.Start();
}
//event to track the location change
public void location_PositionChanged(object sender, GeoPositionChangedEventArgs<GeoCoordinate> e)
{
}