Facebook friend picker SDK sample not working Android - java

Please help me to get the facebook friends from my profile using 3.14 SDK. There is no error in the code but the problem is getting empty list while fetching friends in my profile. I am getting the error in logcat saying .
05-08 16:18:49.252: E/ActivityThread(25644): Failed to find provider info for com.facebook.orca.provider.PlatformProvider<br>
05-08 16:42:20.453: I/QCNEA(28696): |NIMS| getaddrinfo: hostname graph.facebook.com servname NULL numeric 4 appname <br>
05-08 16:51:32.482: D/Request(31861): Warning: Sessionless Request needs token but missing either application ID or client token<br>
Also i am producing the complete code for your reference below
FriendPickerApplication.java*
package com.facebook.samples.friendpicker;
import android.app.Application;
import com.facebook.model.GraphUser;
import java.util.List;
// We use a custom Application class to store our minimal state data (which users have been selected).
// A real-world application will likely require a more robust data model.
public class FriendPickerApplication extends Application {
private List<GraphUser> selectedUsers;
public List<GraphUser> getSelectedUsers() {
return selectedUsers;
}
public void setSelectedUsers(List<GraphUser> selectedUsers) {
this.selectedUsers = selectedUsers;
}
}<br>
FriendPickerSampleActivity.java
package com.facebook.samples.friendpicker;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.facebook.AppEventsLogger;
import com.facebook.Session.NewPermissionsRequest;
import com.facebook.SessionState;
import com.facebook.UiLifecycleHelper;
import com.facebook.model.GraphUser;
import com.facebook.Session;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
public class FriendPickerSampleActivity extends FragmentActivity {
private static final List<String> PERMISSIONS = new ArrayList<String>() {
{
add("user_friends");
add("public_profile");
}
};
private static final int PICK_FRIENDS_ACTIVITY = 1;
private Button pickFriendsButton;
private TextView resultsTextView;
private UiLifecycleHelper lifecycleHelper;
boolean pickFriendsWhenSessionOpened;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
resultsTextView = (TextView) findViewById(R.id.resultsTextView);
pickFriendsButton = (Button) findViewById(R.id.pickFriendsButton);
pickFriendsButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
onClickPickFriends();
}
});
lifecycleHelper = new UiLifecycleHelper(this, new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChanged(session, state, exception);
}
});
lifecycleHelper.onCreate(savedInstanceState);
ensureOpenSession();
}
#Override
protected void onStart() {
super.onStart();
// Update the display every time we are started.
displaySelectedFriends(RESULT_OK);
}
#Override
protected void onResume() {
super.onResume();
// Call the 'activateApp' method to log an app event for use in analytics and advertising reporting. Do so in
// the onResume methods of the primary Activities that an app may be launched into.
AppEventsLogger.activateApp(this);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case PICK_FRIENDS_ACTIVITY:
displaySelectedFriends(resultCode);
break;
default:
Session.getActiveSession().onActivityResult(this, requestCode, resultCode, data);
break;
}
}
private boolean ensureOpenSession() {
if (Session.getActiveSession() == null ||
!Session.getActiveSession().isOpened()) {
Session.openActiveSession(
this,
true,
PERMISSIONS,
new Session.StatusCallback() {
#Override
public void call(Session session, SessionState state, Exception exception) {
onSessionStateChanged(session, state, exception);
}
});
return false;
}
return true;
}
private boolean sessionHasNecessaryPerms(Session session) {
if (session != null && session.getPermissions() != null) {
for (String requestedPerm : PERMISSIONS) {
if (!session.getPermissions().contains(requestedPerm)) {
return false;
}
}
return true;
}
return false;
}
private List<String> getMissingPermissions(Session session) {
List<String> missingPerms = new ArrayList<String>(PERMISSIONS);
if (session != null && session.getPermissions() != null) {
for (String requestedPerm : PERMISSIONS) {
if (session.getPermissions().contains(requestedPerm)) {
missingPerms.remove(requestedPerm);
}
}
}
return missingPerms;
}
private void onSessionStateChanged(final Session session, SessionState state, Exception exception) {
if (state.isOpened() && !sessionHasNecessaryPerms(session)) {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage(R.string.need_perms_alert_text);
builder.setPositiveButton(
R.string.need_perms_alert_button_ok,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
session.requestNewReadPermissions(
new NewPermissionsRequest(
FriendPickerSampleActivity.this,
getMissingPermissions(session)));
}
});
builder.setNegativeButton(
R.string.need_perms_alert_button_quit,
new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
});
builder.show();
} else if (pickFriendsWhenSessionOpened && state.isOpened()) {
pickFriendsWhenSessionOpened = false;
startPickFriendsActivity();
}
}
private void displaySelectedFriends(int resultCode) {
String results = "";
FriendPickerApplication application = (FriendPickerApplication) getApplication();
Collection<GraphUser> selection = application.getSelectedUsers();
if (selection != null && selection.size() > 0) {
ArrayList<String> names = new ArrayList<String>();
for (GraphUser user : selection) {
names.add(user.getName());
}
results = TextUtils.join(", ", names);
} else {
results = "<No friends selected>";
}
resultsTextView.setText(results);
}
private void onClickPickFriends() {
startPickFriendsActivity();
}
private void startPickFriendsActivity() {
if (ensureOpenSession()) {
Intent intent = new Intent(this, PickFriendsActivity.class);
// Note: The following line is optional, as multi-select behavior is the default for
// FriendPickerFragment. It is here to demonstrate how parameters could be passed to the
// friend picker if single-select functionality was desired, or if a different user ID was
// desired (for instance, to see friends of a friend).
PickFriendsActivity.populateParameters(intent, null, true, true);
startActivityForResult(intent, PICK_FRIENDS_ACTIVITY);
} else {
pickFriendsWhenSessionOpened = true;
}
}
} <br>
PickFriendsActivity.java
package com.facebook.samples.friendpicker;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.widget.Toast;
import com.facebook.FacebookException;
import com.facebook.model.GraphUser;
import com.facebook.widget.FriendPickerFragment;
import com.facebook.widget.PickerFragment;
import java.util.List;
public class PickFriendsActivity extends FragmentActivity {
FriendPickerFragment friendPickerFragment;
public static void populateParameters(Intent intent, String userId,
boolean multiSelect, boolean showTitleBar) {
intent.putExtra(FriendPickerFragment.USER_ID_BUNDLE_KEY, userId);
intent.putExtra(FriendPickerFragment.MULTI_SELECT_BUNDLE_KEY,
multiSelect);
intent.putExtra(FriendPickerFragment.SHOW_TITLE_BAR_BUNDLE_KEY,
showTitleBar);
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.pick_friends_activity);
FragmentManager fm = getSupportFragmentManager();
if (savedInstanceState == null) {
// First time through, we create our fragment programmatically.
final Bundle args = getIntent().getExtras();
friendPickerFragment = new FriendPickerFragment(args);
fm.beginTransaction()
.add(R.id.friend_picker_fragment, friendPickerFragment)
.commit();
} else {
// Subsequent times, our fragment is recreated by the framework and
// already has saved and
// restored its state, so we don't need to specify args again. (In
// fact, this might be
// incorrect if the fragment was modified programmatically since it
// was created.)
friendPickerFragment = (FriendPickerFragment) fm
.findFragmentById(R.id.friend_picker_fragment);
}
friendPickerFragment
.setOnErrorListener(new PickerFragment.OnErrorListener() {
#Override
public void onError(PickerFragment<?> fragment,
FacebookException error) {
PickFriendsActivity.this.onError(error);
}
});
friendPickerFragment
.setOnDoneButtonClickedListener(new PickerFragment.OnDoneButtonClickedListener() {
#Override
public void onDoneButtonClicked(PickerFragment<?> fragment) {
// We just store our selection in the Application for
// other activities to look at.
FriendPickerApplication application = (FriendPickerApplication) getApplication();
application.setSelectedUsers(friendPickerFragment
.getSelection());
setResult(RESULT_OK, null);
finish();
}
});
}
private void onError(Exception error) {
String text = getString(R.string.exception, error.getMessage());
Toast toast = Toast.makeText(this, text, Toast.LENGTH_SHORT);
toast.show();
}
#Override
protected void onStart() {
super.onStart();
try {
FriendPickerApplication application = (FriendPickerApplication) getApplication();
List<GraphUser> selectedUsers = application.getSelectedUsers();
if (selectedUsers != null && !selectedUsers.isEmpty()) {
friendPickerFragment.setSelection(selectedUsers);
}
// Load data, unless a query has already taken place.
friendPickerFragment.loadData(false);
} catch (Exception ex) {
onError(ex);
}
}
}<br>
Androidmanifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.facebook.samples.friendpicker"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:name=".FriendPickerApplication"
android:icon="#drawable/icon"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar" >
<activity
android:name="FriendPickerSampleActivity"
android:label="#string/app_name"
android:windowSoftInputMode="adjustResize" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="PickFriendsActivity"
android:label="Pick Friends" >
</activity>
<activity
android:name="com.facebook.LoginActivity"
android:label="#string/app_name"
android:theme="#android:style/Theme.Translucent.NoTitleBar" />
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/app_id" />
<provider
android:name="com.facebook.NativeAppCallContentProvider"
android:authorities="com.facebook.app.NativeAppCallContentProvider1441068969495032"
android:exported="true" />
</application>
</manifest>

After a long struggle I found my own solution to the above question. Facebook have released their new SDK recently to enhance the level of security. There are a few requirements to use facebook SDK in your app.
The app should be sent for submission and needs to be approved by facebook to be use inside facebook, to enable your own app to show friends details, access locations and other special permissions The approval formalities are similar to the ones for app store in Google Play.
The application must be listed in Google Play, or you may be able to integrate it as a test user (i.e like beta testing in Google Play).
The application should have a proper package name, launching activity, domain name, website url and email.
The app id registered must match with an app name and hash key that must be generated for a user developing on different machines
The basic application information, including screenshots, description, and app logo needs to be added
Once after the successful approval, an "active" symbol will be displayed near your app name.
I hope this will be useful for others!!!
More information on Facebook site.

After spending a good number of hours trying to resolve this, I would like to add the following for anyone still looking:
The only friends you will see in the list with user_friend permissions is other users that have logged in and approved your app. I.e. if no-one else is using it, you will se noone in the list (I know, if you read it all, this is obvious)
The easiest way of testing this is to set up a test app, add test users in the dev interface for facebook under "Roles", make sure that the test users are friends and then log in with each use on your app. Only then will they show up in the list.
Unless you ask for it specifically, your app will not have the user_friends permission (you do not, however, need to review this with Facebook as it is part of the basic permissions) - I added it to the onCreateView in the Splash Segment (from the Scrumptios/Login sample in the SDK) like this:
LoginButton loginButton = (LoginButton) view.findViewById(R.id.login_button);
loginButton.setReadPermissions(Arrays.asList("user_friends"));
Use the Facebook test user interface to login on facebook as your test user to validate that they have been accepting the correct permissions (under apps).

Related

How to show custom UI / widget on Lock Screen in Android

I have a requirement to show a customised screen over/on the lock screen in android. logically I want to show a screen (an activity) when phone is locked.
[]
I have tried multiple ways to achieve this functionality but no luck yet.
some links which I have followed are :
https://github.com/ShakeebM/Android-LockScreen
Create custom lockscreen for android 4.0 or above?
show web site on Android lock screen
Creating custom LockScreen in android
https://github.com/Kirk-Str/LockScreenApp
As of now I am able to show a custom screen over the lock screen when app is in foreground state but when app is in background/killed state not able to show the custom screen over the lock screen. Please suggest me what I am missing in my code snippet.
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.lockscreen">
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE"/>
<application
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round">
<activity
android:name=".sample2.screen.LockScreenActivity"
android:excludeFromRecents="true"
android:label="#string/app_name"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.NoTitleBar.Fullscreen"
android:showOnLockScreen="true"
android:turnScreenOn="false"
android:noHistory="true"
android:exported="true">
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".sample2.utils.LockscreenService" >
</service>
<receiver
android:name=".sample2.utils.LockscreenIntentReceiver"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
LockscreenService Class:
package com.example.lockscreen.sample2.utils;
import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import androidx.core.app.NotificationCompat;
import com.example.lockscreen.R;
public class LockscreenService extends Service {
private BroadcastReceiver mReceiver;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
// Register for Lockscreen event intents
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("LockScreen ::: ","onStartCommand");
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new LockscreenIntentReceiver();
registerReceiver(mReceiver, filter);
startForeground();
return START_STICKY;
}
// Run service in foreground so it is less likely to be killed by system
private void startForeground() {
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(getResources().getString(R.string.app_name))
.setTicker(getResources().getString(R.string.app_name))
.setContentText("Running")
.setSmallIcon(R.drawable.ic_launcher_foreground)
.setContentIntent(null)
.setOngoing(true)
.build();
startForeground(9999,notification);
}
// Unregister receiver
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
LockscreenIntentReceiver Class:
package com.example.lockscreen.sample2.utils;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.example.lockscreen.sample2.screen.LockScreenActivity;
public class LockscreenIntentReceiver extends BroadcastReceiver {
// Handle actions and display Lockscreen
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)
|| intent.getAction().equals(Intent.ACTION_SCREEN_ON)
|| intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
start_lockscreen(context);
}
}
// Display lock screen
private void start_lockscreen(Context context) {
Intent mIntent = new Intent(context, LockScreenActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mIntent);
}
}
LockScreenActivity Class:
package com.example.lockscreen.sample2.screen;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.view.KeyEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
import com.example.lockscreen.R;
import com.example.lockscreen.sample2.utils.LockscreenService;
import com.example.lockscreen.sample2.utils.LockscreenUtils;
public class LockScreenActivity extends Activity implements
LockscreenUtils.OnLockStatusChangedListener {
// User-interface
private Button btnUnlock;
// Member variables
private LockscreenUtils mLockscreenUtils;
// Set appropriate flags to make the screen appear over the keyguard
#Override
public void onAttachedToWindow() {
this.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
);
super.onAttachedToWindow();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
);
setContentView(R.layout.activity_lockscreen);
init();
// unlock screen in case of app get killed by system
if (getIntent() != null && getIntent().hasExtra("kill")
&& getIntent().getExtras().getInt("kill") == 1) {
enableKeyguard();
unlockHomeButton();
}
try {
// disable keyguard
disableKeyguard();
// lock home button
lockHomeButton();
Toast.makeText(getApplicationContext(),"lockHomeButton startService", Toast.LENGTH_LONG).show();
// start service for observing intents
startService(new Intent(this, LockscreenService.class));
// listen the events get fired during the call
StateListener phoneStateListener = new StateListener();
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
} catch (Exception e) {
}
}
private void init() {
mLockscreenUtils = new LockscreenUtils();
btnUnlock = (Button) findViewById(R.id.btnUnlock);
btnUnlock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// unlock home button and then screen on button press
unlockHomeButton();
}
});
}
// Handle events of calls and unlock screen if necessary
private class StateListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
unlockHomeButton();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
break;
case TelephonyManager.CALL_STATE_IDLE:
break;
}
}
};
// Don't finish Activity on Back press
#Override
public void onBackPressed() {
return;
}
// Handle button clicks
#Override
public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
|| (keyCode == KeyEvent.KEYCODE_POWER)
|| (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
|| (keyCode == KeyEvent.KEYCODE_CAMERA)) {
return true;
}
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
return true;
}
return false;
}
// handle the key press events here itself
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP
|| (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN)
|| (event.getKeyCode() == KeyEvent.KEYCODE_POWER)) {
return false;
}
if ((event.getKeyCode() == KeyEvent.KEYCODE_HOME)) {
return true;
}
return false;
}
// Lock home button
public void lockHomeButton() {
mLockscreenUtils.lock(LockScreenActivity.this);
}
// Unlock home button and wait for its callback
public void unlockHomeButton() {
mLockscreenUtils.unlock();
}
// Simply unlock device when home button is successfully unlocked
#Override
public void onLockStatusChanged(boolean isLocked) {
if (!isLocked) {
unlockDevice();
}
}
#Override
protected void onStop() {
super.onStop();
unlockHomeButton();
}
#SuppressWarnings("deprecation")
private void disableKeyguard() {
KeyguardManager mKM = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock mKL = mKM.newKeyguardLock("IN");
mKL.disableKeyguard();
}
#SuppressWarnings("deprecation")
private void enableKeyguard() {
KeyguardManager mKM = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock mKL = mKM.newKeyguardLock("IN");
mKL.reenableKeyguard();
}
//Simply unlock device by finishing the activity
private void unlockDevice()
{
finish();
}
}
Please help me how can I achieve this?

Right way of requesting permissions for location coordinates in Android 10

Below code does not work on Android 10 until you manually enable the location from settings. When I go through the Android 10 documentation, it says if you are fetching location from the visible activity, if that was the case you don't need any foreground service, that's the reason I haven't used any service here.
And also as per Android 10 guidelines, after permission getting granted I am calling getLastLocation function.
Implementation is like, on main activity I am fetching location coordinates.
Please help, where in the code am I going wrong?
MainActivity.java
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import androidx.annotation.NonNull;
import com.google.android.material.snackbar.Snackbar;
import androidx.core.app.ActivityCompat;
import androidx.appcompat.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;
private FusedLocationProviderClient mFusedLocationClient;
protected Location mLastLocation;
private String mLatitudeLabel;
private String mLongitudeLabel;
private TextView mLatitudeText;
private TextView mLongitudeText;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
mLatitudeLabel = getResources().getString(R.string.latitude_label);
mLongitudeLabel = getResources().getString(R.string.longitude_label);
mLatitudeText = (TextView) findViewById((R.id.latitude_text));
mLongitudeText = (TextView) findViewById((R.id.longitude_text));
mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
}
#Override
public void onStart() {
super.onStart();
if (!checkPermissions()) {
requestPermissions();
} else {
getLastLocation();
}
}
#SuppressWarnings("MissingPermission")
private void getLastLocation() {
mFusedLocationClient.getLastLocation()
.addOnCompleteListener(this, new OnCompleteListener<Location>() {
#Override
public void onComplete(#NonNull Task<Location> task) {
if (task.isSuccessful() && task.getResult() != null) {
mLastLocation = task.getResult();
Log.d("raviraj", "lat is " +mLastLocation.getLatitude());
Log.d("raviraj", "long is " +mLastLocation.getLongitude());
mLatitudeText.setText(String.format(Locale.ENGLISH, "%s: %f",
mLatitudeLabel,
mLastLocation.getLatitude()));
mLongitudeText.setText(String.format(Locale.ENGLISH, "%s: %f",
mLongitudeLabel,
mLastLocation.getLongitude()));
} else {
Log.w("RAVIRAJ", "getLastLocation:exception" +task.getException());
showSnackbar(getString(R.string.no_location_detected));
}
}
});
}
private void showSnackbar(final String text) {
View container = findViewById(R.id.main_activity_container);
if (container != null) {
Snackbar.make(container, text, Snackbar.LENGTH_LONG).show();
}
}
private void showSnackbar(final int mainTextStringId, final int actionStringId,
View.OnClickListener listener) {
Snackbar.make(findViewById(android.R.id.content),
getString(mainTextStringId),
Snackbar.LENGTH_INDEFINITE)
.setAction(getString(actionStringId), listener).show();
}
private boolean checkPermissions() {
int permissionState = ActivityCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION);
return permissionState == PackageManager.PERMISSION_GRANTED;
}
private void startLocationPermissionRequest() {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_PERMISSIONS_REQUEST_CODE);
}
private void requestPermissions() {
boolean shouldProvideRationale =
ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION);
if (shouldProvideRationale) {
Log.i(TAG, "Displaying permission rationale to provide additional context.");
showSnackbar(R.string.permission_rationale, android.R.string.ok,
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request permission
startLocationPermissionRequest();
}
});
} else {
Log.i(TAG, "Requesting permission");
startLocationPermissionRequest();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
Log.i(TAG, "onRequestPermissionResult");
if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
if (grantResults.length <= 0) {
// If user interaction was interrupted, the permission request is cancelled and you
// receive empty arrays.
Log.i(TAG, "User interaction was cancelled.");
} else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission granted.
getLastLocation();
} else {
showSnackbar(R.string.permission_denied_explanation, R.string.settings,
new View.OnClickListener() {
#Override
public void onClick(View view) {
// Build intent that displays the App settings screen.
Intent intent = new Intent();
intent.setAction(
Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
Uri uri = Uri.fromParts("package",
BuildConfig.APPLICATION_ID, null);
intent.setData(uri);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
}
}
}
}
Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.gms.location.sample.basiclocationsample" >
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/Theme.Base" >
<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="#string/google_maps_key" />
<activity
android:name=".NewMain"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Well there is a problem. Official documentation states that it can be null in some cases
https://developer.android.com/training/location/retrieve-current
Location is turned off in the device settings. The result could be null even if the last location was previously retrieved because disabling location also clears the cache.
The device never recorded its location, which could be the case of a new device or a device that has been restored to factory settings.
Google Play services on the device has restarted, and there is no active Fused Location Provider client that has requested location after the services restarted. To avoid this situation you can create a new client and request location updates yourself. For more information, see Receiving Location Updates.
In your case you can get location only if GPS is ON. Even for last known location.
https://developer.android.com/training/location/retrieve-current#last-known
Please add this permission in AndroidManifest.xml
<uses-permission android:name="android.permission.INTERNET" />
and add this to application tag
android:usesCleartextTraffic="true"

PendingIntent with implicit intent returning cancelled exception when using OpenId AppAuth-Android library

I am trying to implement oauth2 to enable users to login with Reddit. I have created my app on reddit with the appropriate redirect uri.
What I did:
A MainActivity with a login button. Clicking the login button, starts the authorization flow. To create the authorization request, we need to pass a pending intent that the library uses to call the appropriate component that we want it to call after authorization is successful.
Problem:
When the pending intent is made using an implicit intent (setting only action string while creating intent), the library gets a cancelled exception while invoking the pending intent. I have mentioned the action string in the intent filter for the MainActivity in manifest file also.
What I have tried:
1. I tried creating pending intent using an explicit intent (defining the activity class I want to open while creating intent), my activity's onStart is getting called with the correct intent.
2. I tried by directly invoking the pending intent (with implicit intent) from the activity itself and it got called successfully.
Observation:
1. If I use an older version of the library (v0.2.0), the pending intent with implicit intent works fine.
Current version of OpenId AppAuth library - 0.7.1
Tested on Android 9 (Pie) - OnePlus 3T
Below is my MainActivity.java
package com.prateekgrover.redditline;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import com.prateekgrover.redditline.services.RedditAuthService;
import net.openid.appauth.AuthState;
import net.openid.appauth.AuthorizationException;
import net.openid.appauth.AuthorizationRequest;
import net.openid.appauth.AuthorizationResponse;
import net.openid.appauth.AuthorizationService;
import net.openid.appauth.AuthorizationServiceConfiguration;
import net.openid.appauth.TokenRequest;
import net.openid.appauth.TokenResponse;
import java.util.UUID;
public class MainActivity extends AppCompatActivity {
private String USED_INTENT = "1";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button loginButton = findViewById(R.id.reddit_login);
loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Intent intent = new Intent(MainActivity.this, RedditAuthService.class);
// startService(intent);
performRedditAuthAction(MainActivity.this, "com.prateekgrover.redditline.HANDLE_AUTHORIZATION_RESPONSE");
}
});
}
public void performRedditAuthAction(Context context, String actionRedirect) {
String uuid = UUID.randomUUID().toString();
AuthorizationServiceConfiguration serviceConfiguration = new AuthorizationServiceConfiguration(
Uri.parse("https://www.reddit.com/api/v1/authorize") /* auth endpoint */,
Uri.parse("https://www.reddit.com/api/v1/access_token") /* token endpoint */
);
String clientId = "<my client id>";
Uri redirectUri = Uri.parse("com.prateekgrover.redditline://oauth2callback");
AuthorizationRequest.Builder builder = new AuthorizationRequest.Builder(
serviceConfiguration,
clientId,
"code",
redirectUri
);
builder.setState(uuid);
builder.setScopes("identity", "mysubreddits", "read", "save", "submit", "subscribe", "vote");
AuthorizationRequest request = builder.build();
AuthorizationService authorizationService = new AuthorizationService(context);
String action = actionRedirect;
Intent postAuthorizationIntent = new Intent("com.prateekgrover.redditline.HANDLE_AUTHORIZATION_RESPONSE");
PendingIntent pendingIntent = PendingIntent.getActivity(this, request.hashCode(), postAuthorizationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
authorizationService.performAuthorizationRequest(request, pendingIntent);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
if (intent != null && intent.getAction() != null) {
String action = intent.getAction();
switch (action) {
case "com.prateekgrover.redditline.HANDLE_AUTHORIZATION_RESPONSE":
redirectIntent(intent);
break;
default:
}
}
}
private void redirectIntent(#Nullable Intent intent) {
if (!intent.hasExtra(USED_INTENT)) {
handleAuthorizationResponse(intent);
intent.putExtra(USED_INTENT, true);
}
}
private void handleAuthorizationResponse(Intent intent) {
AuthorizationResponse response = AuthorizationResponse.fromIntent(intent);
AuthorizationException error = AuthorizationException.fromIntent(intent);
final AuthState authState = new AuthState(response, error);
if (response != null) {
AuthorizationService service = new AuthorizationService(this);
service.performTokenRequest(response.createTokenExchangeRequest(), new AuthorizationService.TokenResponseCallback() {
#Override
public void onTokenRequestCompleted(#Nullable TokenResponse tokenResponse, #Nullable AuthorizationException exception) {
if (exception != null) {
} else {
if (tokenResponse != null) {
authState.update(tokenResponse, exception);
System.out.println(tokenResponse.accessToken + " refresh_token " + tokenResponse.refreshToken);
}
}
}
});
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
#Override
protected void onStart() {
super.onStart();
Intent intent = getIntent();
if (intent != null && intent.getAction() != null) {
String action = intent.getAction();
switch (action) {
case "com.prateekgrover.redditline.HANDLE_AUTHORIZATION_RESPONSE":
redirectIntent(intent);
break;
default:
}
}
}
}
Manifest File:
<activity android:name=".MainActivity" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="com.prateekgrover.redditline.HANDLE_AUTHORIZATION_RESPONSE"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
Relevant parts of the library - mCompleteIntent is the PendingIntent that I sending to the library
private void extractState(Bundle state) {
if (state == null) {
Logger.warn("No stored state - unable to handle response");
finish();
return;
}
mAuthIntent = state.getParcelable(KEY_AUTH_INTENT);
mAuthorizationStarted = state.getBoolean(KEY_AUTHORIZATION_STARTED, false);
try {
String authRequestJson = state.getString(KEY_AUTH_REQUEST, null);
mAuthRequest = authRequestJson != null
? AuthorizationRequest.jsonDeserialize(authRequestJson)
: null;
} catch (JSONException ex) {
throw new IllegalStateException("Unable to deserialize authorization request", ex);
}
mCompleteIntent = state.getParcelable(KEY_COMPLETE_INTENT);
mCancelIntent = state.getParcelable(KEY_CANCEL_INTENT);
}
private void handleAuthorizationComplete() {
Uri responseUri = getIntent().getData();
Intent responseData = extractResponseData(responseUri);
if (responseData == null) {
Logger.error("Failed to extract OAuth2 response from redirect");
return;
}
responseData.setData(responseUri);
if (mCompleteIntent != null) {
Logger.debug("Authorization complete - invoking completion intent");
try {
mCompleteIntent.send(this, 0, responseData);
} catch (CanceledException ex) {
Logger.error("Failed to send completion intent", ex);
}
} else {
setResult(RESULT_OK, responseData);
}
}
In case anybody else stumbles upon this issue.
Use the example app within app-auth android github project.
Don't use Google CodeLabs app-auth example! The code from the question above is from Google CodeLabs, it is very old and no longer works (state at July 2020).
I did the same mistake, app-auth links codelabs on their own page/readme, so I started using codelabs code and ended up with lots of problems and errors.
The new app-auth version 0.7.x uses a json configuration file and the example app shows how to handle errors around pending intents etc. .

App Crashes On Clicking To Start Location Update

I am developing an app that uses fingerprint authentication to send the location of user over certain duration ex 30 mins in form of intervals of 10 mins. i have used certain code to develop the app. But app crashes on clicking start update button.
Note : Summary of app crash says java.lang.SecurityException: Client must have ACCESS_Fine_LOCATION permission to request PRIORITY_HIGH_ACCURACY locations.
Following is the code
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.google.android.gms.location.sample.locationupdates">
<uses-permission android:name="android.permission.USE_FINGERPRINT" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-feature android:name="android.hardware.location.gps" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme.NoActionBar">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".FingerprintActivity"
android:label="Fingerprint">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity">
</activity>
</application>
</manifest>
FingerprintActivity.java
import android.Manifest;
import android.annotation.TargetApi;
import android.app.KeyguardManager;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.Build;
import android.security.keystore.KeyGenParameterSpec;
import android.security.keystore.KeyPermanentlyInvalidatedException;
import android.security.keystore.KeyProperties;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;
import java.io.IOException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.UnrecoverableKeyException;
import java.security.cert.CertificateException;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class FingerprintActivity extends AppCompatActivity {
private KeyStore keyStore;
// Variable used for storing the key in the Android Keystore container
private static final String KEY_NAME = "androidHive";
private Cipher cipher;
private TextView textView;
public void sendMessage(View view)
{
Intent intent = new Intent(FingerprintActivity.this, MainActivity.class);
startActivity(intent);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_fingerprint);
// Initializing both Android Keyguard Manager and Fingerprint Manager
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
FingerprintManager fingerprintManager = (FingerprintManager) getSystemService(FINGERPRINT_SERVICE);
textView = (TextView) findViewById(R.id.errorText);
// Check whether the device has a Fingerprint sensor.
if(!fingerprintManager.isHardwareDetected()){
/**
* An error message will be displayed if the device does not contain the fingerprint hardware.
* However if you plan to implement a default authentication method,
* you can redirect the user to a default authentication activity from here.
* Example:
* Intent intent = new Intent(this, DefaultAuthenticationActivity.class);
* startActivity(intent);
*/
textView.setText("Your Device does not have a Fingerprint Sensor");
}else {
// Checks whether fingerprint permission is set on manifest
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
textView.setText("Fingerprint authentication permission not enabled");
}else{
// Check whether at least one fingerprint is registered
if (!fingerprintManager.hasEnrolledFingerprints()) {
textView.setText("Register at least one fingerprint in Settings");
}else{
// Checks whether lock screen security is enabled or not
if (!keyguardManager.isKeyguardSecure()) {
textView.setText("Lock screen security not enabled in Settings");
}else{
generateKey();
if (cipherInit()) {
FingerprintManager.CryptoObject cryptoObject = new FingerprintManager.CryptoObject(cipher);
FingerprintHandler helper = new FingerprintHandler(this);
helper.startAuth(fingerprintManager, cryptoObject);
}
}
}
}
}
}
#TargetApi(Build.VERSION_CODES.M)
protected void generateKey() {
try {
keyStore = KeyStore.getInstance("AndroidKeyStore");
} catch (Exception e) {
e.printStackTrace();
}
KeyGenerator keyGenerator;
try {
keyGenerator = KeyGenerator.getInstance(KeyProperties.KEY_ALGORITHM_AES, "AndroidKeyStore");
} catch (NoSuchAlgorithmException | NoSuchProviderException e) {
throw new RuntimeException("Failed to get KeyGenerator instance", e);
}
try {
keyStore.load(null);
keyGenerator.init(new
KeyGenParameterSpec.Builder(KEY_NAME,
KeyProperties.PURPOSE_ENCRYPT |
KeyProperties.PURPOSE_DECRYPT)
.setBlockModes(KeyProperties.BLOCK_MODE_CBC)
.setUserAuthenticationRequired(true)
.setEncryptionPaddings(
KeyProperties.ENCRYPTION_PADDING_PKCS7)
.build());
keyGenerator.generateKey();
} catch (NoSuchAlgorithmException |
InvalidAlgorithmParameterException
| CertificateException | IOException e) {
throw new RuntimeException(e);
}
}
#TargetApi(Build.VERSION_CODES.M)
public boolean cipherInit() {
try {
cipher = Cipher.getInstance(KeyProperties.KEY_ALGORITHM_AES + "/" + KeyProperties.BLOCK_MODE_CBC + "/" + KeyProperties.ENCRYPTION_PADDING_PKCS7);
} catch (NoSuchAlgorithmException | NoSuchPaddingException e) {
throw new RuntimeException("Failed to get Cipher", e);
}
try {
keyStore.load(null);
SecretKey key = (SecretKey) keyStore.getKey(KEY_NAME,
null);
cipher.init(Cipher.ENCRYPT_MODE, key);
return true;
} catch (KeyPermanentlyInvalidatedException e) {
return false;
} catch (KeyStoreException | CertificateException | UnrecoverableKeyException | IOException | NoSuchAlgorithmException | InvalidKeyException e) {
throw new RuntimeException("Failed to init Cipher", e);
}
}
}
FingerprintHandler
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.hardware.fingerprint.FingerprintManager;
import android.os.CancellationSignal;
import android.support.v4.app.ActivityCompat;
import android.widget.TextView;
public class FingerprintHandler extends FingerprintManager.AuthenticationCallback {
private Context context;
// Constructor
public FingerprintHandler(Context mContext) {
context = mContext;
}
public void startAuth(FingerprintManager manager, FingerprintManager.CryptoObject cryptoObject) {
CancellationSignal cancellationSignal = new CancellationSignal();
if (ActivityCompat.checkSelfPermission(context, Manifest.permission.USE_FINGERPRINT) != PackageManager.PERMISSION_GRANTED) {
return;
}
manager.authenticate(cryptoObject, cancellationSignal, 0, this, null);
}
#Override
public void onAuthenticationError(int errMsgId, CharSequence errString) {
this.update("Fingerprint Authentication error\n" + errString);
}
#Override
public void onAuthenticationHelp(int helpMsgId, CharSequence helpString) {
this.update("Fingerprint Authentication help\n" + helpString);
}
#Override
public void onAuthenticationFailed() {
this.update("Fingerprint Authentication failed.");
}
#Override
public void onAuthenticationSucceeded(FingerprintManager.AuthenticationResult result) {
((Activity) context).finish();
Intent intent = new Intent(context, MainActivity.class);
context.startActivity(intent);
}
private void update(String e){
TextView textView = (TextView) ((Activity)context).findViewById(R.id.errorText);
textView.setText(e);
}
}
MainActivity
import android.app.Activity;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.common.api.GoogleApiClient.ConnectionCallbacks;
import com.google.android.gms.common.api.GoogleApiClient.OnConnectionFailedListener;
import com.google.android.gms.common.api.ResultCallback;
import com.google.android.gms.common.api.Status;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResult;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import java.text.DateFormat;
import java.util.Date;
public class MainActivity extends AppCompatActivity implements
ConnectionCallbacks,
OnConnectionFailedListener,
LocationListener {
protected static final String TAG = "MainActivity";
/**
* Constant used in the location settings dialog.
*/
protected static final int REQUEST_CHECK_SETTINGS = 0x1;
public static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;
public static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS =
UPDATE_INTERVAL_IN_MILLISECONDS / 2;
// Keys for storing activity state in the Bundle.
protected final static String KEY_REQUESTING_LOCATION_UPDATES = "requesting-location-updates";
protected final static String KEY_LOCATION = "location";
protected final static String KEY_LAST_UPDATED_TIME_STRING = "last-updated-time-string";
protected GoogleApiClient mGoogleApiClient;
protected LocationRequest mLocationRequest;
protected LocationSettingsRequest mLocationSettingsRequest;
protected Location mCurrentLocation;
// UI Widgets.
protected Button mStartUpdatesButton;
protected Button mStopUpdatesButton;
protected TextView mLastUpdateTimeTextView;
protected TextView mLatitudeTextView;
protected TextView mLongitudeTextView;
protected TextView mLocationInadequateWarning;
// Labels.
protected String mLatitudeLabel;
protected String mLongitudeLabel;
protected String mLastUpdateTimeLabel;
protected Boolean mRequestingLocationUpdates;
protected String mLastUpdateTime;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// Locate the UI widgets.
mStartUpdatesButton = (Button) findViewById(R.id.start_updates_button);
mStopUpdatesButton = (Button) findViewById(R.id.stop_updates_button);
mLatitudeTextView = (TextView) findViewById(R.id.latitude_text);
mLongitudeTextView = (TextView) findViewById(R.id.longitude_text);
mLastUpdateTimeTextView = (TextView) findViewById(R.id.last_update_time_text);
mLocationInadequateWarning = (TextView) findViewById(R.id.location_inadequate_warning);
// Set labels.
mLatitudeLabel = getResources().getString(R.string.latitude_label);
mLongitudeLabel = getResources().getString(R.string.longitude_label);
mLastUpdateTimeLabel = getResources().getString(R.string.last_update_time_label);
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
// Update values using data stored in the Bundle.
updateValuesFromBundle(savedInstanceState);
// Kick off the process of building the GoogleApiClient, LocationRequest, and
// LocationSettingsRequest objects.
buildGoogleApiClient();
createLocationRequest();
buildLocationSettingsRequest();
}
private void updateValuesFromBundle(Bundle savedInstanceState) {
if (savedInstanceState != null) {
// Update the value of mRequestingLocationUpdates from the Bundle, and make sure that
// the Start Updates and Stop Updates buttons are correctly enabled or disabled.
if (savedInstanceState.keySet().contains(KEY_REQUESTING_LOCATION_UPDATES)) {
mRequestingLocationUpdates = savedInstanceState.getBoolean(
KEY_REQUESTING_LOCATION_UPDATES);
}
// Update the value of mCurrentLocation from the Bundle and update the UI to show the
// correct latitude and longitude.
if (savedInstanceState.keySet().contains(KEY_LOCATION)) {
// Since KEY_LOCATION was found in the Bundle, we can be sure that mCurrentLocation
// is not null.
mCurrentLocation = savedInstanceState.getParcelable(KEY_LOCATION);
}
// Update the value of mLastUpdateTime from the Bundle and update the UI.
if (savedInstanceState.keySet().contains(KEY_LAST_UPDATED_TIME_STRING)) {
mLastUpdateTime = savedInstanceState.getString(KEY_LAST_UPDATED_TIME_STRING);
}
updateUI();
}
}
/**
* Builds a GoogleApiClient. Uses the {#code #addApi} method to request the
* LocationServices API.
*/
protected synchronized void buildGoogleApiClient() {
Log.i(TAG, "Building GoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
// Sets the desired interval for active location updates. This interval is
// inexact. You may not receive updates at all if no location sources are available, or
// you may receive them slower than requested. You may also receive updates faster than
// requested if other applications are requesting location at a faster interval.
mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
// Sets the fastest rate for active location updates. This interval is exact, and your
// application will never receive updates faster than this value.
mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
/**
* Uses a {#link com.google.android.gms.location.LocationSettingsRequest.Builder} to build
* a {#link com.google.android.gms.location.LocationSettingsRequest} that is used for checking
* if a device has the needed location settings.
*/
protected void buildLocationSettingsRequest() {
LocationSettingsRequest.Builder builder = new LocationSettingsRequest.Builder();
builder.addLocationRequest(mLocationRequest);
mLocationSettingsRequest = builder.build();
}
/**
* The callback invoked when
* {#link com.google.android.gms.location.SettingsApi#checkLocationSettings(GoogleApiClient,
* LocationSettingsRequest)} is called. Examines the
* {#link com.google.android.gms.location.LocationSettingsResult} object and determines if
* location settings are adequate. If they are not, begins the process of presenting a location
* settings dialog to the user.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
// Check for the integer request code originally supplied to startResolutionForResult().
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
Log.i(TAG, "User agreed to make required location settings changes.");
// Nothing to do. startLocationupdates() gets called in onResume again.
break;
case Activity.RESULT_CANCELED:
Log.i(TAG, "User chose not to make required location settings changes.");
mRequestingLocationUpdates = false;
updateUI();
break;
}
break;
}
}
/**
* Handles the Start Updates button and requests start of location updates. Does nothing if
* updates have already been requested.
*/
public void startUpdatesButtonHandler(View view) {
if (!mRequestingLocationUpdates) {
mRequestingLocationUpdates = true;
setButtonsEnabledState();
startLocationUpdates();
}
}
/**
* Handles the Stop Updates button, and requests removal of location updates.
*/
public void stopUpdatesButtonHandler(View view) {
// It is a good practice to remove location requests when the activity is in a paused or
// stopped state. Doing so helps battery performance and is especially
// recommended in applications that request frequent location updates.
stopLocationUpdates();
}
/**
* Requests location updates from the FusedLocationApi.
*/
protected void startLocationUpdates() {
LocationServices.SettingsApi.checkLocationSettings(
mGoogleApiClient,
mLocationSettingsRequest
).setResultCallback(new ResultCallback<LocationSettingsResult>() {
#Override
public void onResult(LocationSettingsResult locationSettingsResult) {
final Status status = locationSettingsResult.getStatus();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
Log.i(TAG, "All location settings are satisfied.");
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, MainActivity.this);
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
Log.i(TAG, "Location settings are not satisfied. Attempting to upgrade " +
"location settings ");
try {
// Show the dialog by calling startResolutionForResult(), and check the
// result in onActivityResult().
status.startResolutionForResult(MainActivity.this, REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
Log.i(TAG, "PendingIntent unable to execute request.");
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
String errorMessage = "Location settings are inadequate, and cannot be " +
"fixed here. Fix in Settings.";
Log.e(TAG, errorMessage);
Toast.makeText(MainActivity.this, errorMessage, Toast.LENGTH_LONG).show();
mRequestingLocationUpdates = false;
}
updateUI();
}
});
}
/**
* Updates all UI fields.
*/
private void updateUI() {
setButtonsEnabledState();
updateLocationUI();
}
/**
* Disables both buttons when functionality is disabled due to insuffucient location settings.
* Otherwise ensures that only one button is enabled at any time. The Start Updates button is
* enabled if the user is not requesting location updates. The Stop Updates button is enabled
* if the user is requesting location updates.
*/
private void setButtonsEnabledState() {
if (mRequestingLocationUpdates) {
mStartUpdatesButton.setEnabled(false);
mStopUpdatesButton.setEnabled(true);
} else {
mStartUpdatesButton.setEnabled(true);
mStopUpdatesButton.setEnabled(false);
}
}
/**
* Sets the value of the UI fields for the location latitude, longitude and last update time.
*/
private void updateLocationUI() {
if (mCurrentLocation != null) {
mLatitudeTextView.setText(String.format("%s: %f", mLatitudeLabel,
mCurrentLocation.getLatitude()));
mLongitudeTextView.setText(String.format("%s: %f", mLongitudeLabel,
mCurrentLocation.getLongitude()));
mLastUpdateTimeTextView.setText(String.format("%s: %s", mLastUpdateTimeLabel,
mLastUpdateTime));
}
}
/**
* Removes location updates from the FusedLocationApi.
*/
protected void stopLocationUpdates() {
// It is a good practice to remove location requests when the activity is in a paused or
// stopped state. Doing so helps battery performance and is especially
// recommended in applications that request frequent location updates.
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient,
this
).setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(Status status) {
mRequestingLocationUpdates = false;
setButtonsEnabledState();
}
});
}
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
#Override
public void onResume() {
super.onResume();
// Within {#code onPause()}, we pause location updates, but leave the
// connection to GoogleApiClient intact. Here, we resume receiving
// location updates if the user has requested them.
if (mGoogleApiClient.isConnected() && mRequestingLocationUpdates) {
startLocationUpdates();
}
updateUI();
}
#Override
protected void onPause() {
super.onPause();
// Stop location updates to save battery, but don't disconnect the GoogleApiClient object.
if (mGoogleApiClient.isConnected()) {
stopLocationUpdates();
}
}
#Override
protected void onStop() {
super.onStop();
mGoogleApiClient.disconnect();
}
/**
* Runs when a GoogleApiClient object successfully connects.
*/
#Override
public void onConnected(Bundle connectionHint) {
// If the initial location was never previously requested, we use
// FusedLocationApi.getLastLocation() to get it. If it was previously requested, we store
// its value in the Bundle and check for it in onCreate(). We
// do not request it again unless the user specifically requests location updates by pressing
// the Start Updates button.
//
// Because we cache the value of the initial location in the Bundle, it means that if the
// user launches the activity,
// moves to a new location, and then changes the device orientation, the original location
// is displayed as the activity is re-created.
if (mCurrentLocation == null) {
mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateLocationUI();
}
if (mRequestingLocationUpdates) {
Log.i(TAG, "in onConnected(), starting location updates");
startLocationUpdates();
}
}
/**
* Callback that fires when the location changes.
*/
#Override
public void onLocationChanged(Location location) {
mCurrentLocation = location;
mLastUpdateTime = DateFormat.getTimeInstance().format(new Date());
updateLocationUI();
}
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "Connection suspended");
}
#Override
public void onConnectionFailed(ConnectionResult result) {
// Refer to the javadoc for ConnectionResult to see what error codes might be returned in
// onConnectionFailed.
Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
}
/**
* Stores activity data in the Bundle.
*/
public void onSaveInstanceState(Bundle savedInstanceState) {
savedInstanceState.putBoolean(KEY_REQUESTING_LOCATION_UPDATES, mRequestingLocationUpdates);
savedInstanceState.putParcelable(KEY_LOCATION, mCurrentLocation);
savedInstanceState.putString(KEY_LAST_UPDATED_TIME_STRING, mLastUpdateTime);
super.onSaveInstanceState(savedInstanceState);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
minSdkVersion 23 targetSdkVersion 24
Targeting SDK 23+ require you support Runtime Permissions. Your manifest is <uses-permission>s are irrelevant in such case (and can be removed if you not targetting lower SDKs). As you have no support for Runtime Permissions your app is not granted GPS access hence the crash with SecurityException.
Docs: https://developer.android.com/training/permissions/requesting.html
Quick solution: if you can, lower targetSdk (and minSdk) below 23. If you for any reason cannot, you must have Runtime Permissions implemented. There are some libs helping with the task - just google for it.

Auto Launch on Eddystone-UID within 1 meter

I want to auto-launch my activity when a beacon comes within 1 meter. This question has been posed before, but I am unable to get mine to work using/modifying his code.
Just like that post, I followed the same steps with the android beacon library through the altbeacon github but still have been unsuccessful.
I also have "compile 'org.altbeacon:android-beacon-library:2.7+'" in build.gradle file.
AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.communionchapelefca.ccsatx" android:versionCode="1" android:versionName="1.0">
<uses-sdk android:minSdkVersion="19" android:targetSdkVersion="23"/>
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
"android.hardware.bluetooth_le" android:required="false"/>
<uses-permission-sdk-23 android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme">
<activity
android:name="org.communionchapelefca.ccsatx.SplashScreen" android:label="#string/app_name"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name="org.communionchapelefca.ccsatx.MainActivity" android:label="#string/app_name"
android:launchMode="singleInstance">
<intent-filter>
<action android:name="org.communionchapelefca.ccsatx.MAINACTIVITY"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
MainActivity.java
import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Application;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Build;
import android.os.Bundle;
import android.os.RemoteException;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;
import org.altbeacon.beacon.Beacon;
import org.altbeacon.beacon.BeaconManager;
import org.altbeacon.beacon.BeaconParser;
import org.altbeacon.beacon.RangeNotifier;
import org.altbeacon.beacon.Region;
import org.altbeacon.beacon.powersave.BackgroundPowerSaver;
import org.altbeacon.beacon.startup.BootstrapNotifier;
import org.altbeacon.beacon.startup.RegionBootstrap;
import java.util.Collection;
public class MainActivity extends Activity implements BootstrapNotifier, RangeNotifier {
public static final String TAG = "MainActivityCCSATX";
private WebView mWebView;
ProgressBar progressBar;
private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mWebView = (WebView) findViewById(R.id.activity_main_webview);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
WebSettings webSettings = mWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mWebView.loadUrl("http://communionchapelefca.org/edy-home");
mWebView.setWebViewClient(new HelloWebViewClient());
// begin code for bluetooth permission for android 6
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
// Android M Permission check

if (this.checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("This app needs location access to find Communion Chapel beacons");
builder.setMessage("Please grant location access so this app can detect Communion Chapel beacons.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
requestPermissions(new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);
}
});
builder.show();
}
}
mAllBeaconsRegion = new Region("all beacons", null, null, null);
mBeaconManager = BeaconManager.getInstanceForApplication(this);
mBackgroundPowerSaver = new BackgroundPowerSaver(this);
mRegionBootstrap = new RegionBootstrap(this, mAllBeaconsRegion);
// By default the AndroidBeaconLibrary will only find AltBeacons. If you wish to make it
// find a different type of beacon, you must specify the byte layout for that beacon's
// advertisement with a line like below. The example shows how to find a beacon with the
// same byte layout as AltBeacon but with a beaconTypeCode of 0xaabb
//
Log.d(TAG, " region. starting ranging");
mBeaconManager.getBeaconParsers().add(new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));
mBeaconManager.setBackgroundScanPeriod(11000l);
}
#Override
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_COARSE_LOCATION: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d(TAG, "coarse location permission granted");
} else {
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Functionality limited");
builder.setMessage("Since location access has not been granted, this app will not be able to discover beacons when in the background.");
builder.setPositiveButton(android.R.string.ok, null);
builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
}
});
builder.show();
}
return;
}
}
}
// end code for bluetooth permission for android 6
private class HelloWebViewClient extends WebViewClient{
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
webView.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
progressBar.setVisibility(view.GONE);
}
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{ //if back key is pressed
if((keyCode == KeyEvent.KEYCODE_BACK)&& mWebView.canGoBack())
{
mWebView.goBack();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
public void onBackPressed() {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, close
// current activity
MainActivity.this.finish();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
// if this button is clicked, just close
// the dialog box and do nothing
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
private RegionBootstrap regionBootstrap;
private BeaconManager mBeaconManager;
private Region region;
private Region mAllBeaconsRegion;
private BackgroundPowerSaver mBackgroundPowerSaver;
private RegionBootstrap mRegionBootstrap;
#Override
public void didDetermineStateForRegion(int arg0, Region arg1) {
// Don't care
}
#Override
public void didEnterRegion(Region arg0) {
mRegionBootstrap.disable();
// This call to disable will make it so the activity below only gets launched the first time a beacon is seen (until the next time the app is launched)
// if you want the Activity to launch every single time beacons come into view, remove this call.
try {
mBeaconManager.startRangingBeaconsInRegion(new Region("all beacons", null, null, null));
mBeaconManager.setRangeNotifier(this);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Log.d(TAG, "Got a didEnterRegion call");
}
#Override
public void didExitRegion(Region arg0) {
// Don't care
}
#Override
public void didRangeBeaconsInRegion(Collection<Beacon> beacons, Region region) {
// TODO Auto-generated method stub
if (beacons.size() > 0) {
for (Beacon beacon: beacons) {
Log.d(TAG, "Found a beacon, getting distance");
if(beacon.getDistance()<1)
{
Log.d(TAG, "within 1 minute call");
Intent intent = new Intent(this, MainActivity.class);
// IMPORTANT: in the AndroidManifest.xml definition of this activity, you must set android:launchMode="singleInstance" or you will get two instances
// created when a user launches the activity manually and it gets launched from here.
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startActivity(intent);
}
}
}
}
}
LogCat from fatal error:
01-28 17:23:38.819 6549 6724 D MainActivityCCSATX: Got a didEnterRegion call
01-28 17:23:38.824 6549 6549 D BluetoothAdapter: STATE_ON
01-28 17:23:38.824 6549 6549 D BluetoothLeScanner: could not find callback wrapper
01-28 17:23:38.824 6549 6549 D BluetoothAdapter: STATE_ON
01-28 17:23:38.824 6549 6549 D BluetoothLeScanner: could not find callback wrapper
01-28 17:23:39.444 6549 6549 W cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 6549
01-28 17:23:40.023 6549 6549 W cr_BindingManager: Cannot call determinedVisibility() - never saw a connection for the pid: 6549
A few tips:
Try adding a debug line Log.d("Distance:"+beacon.get Distance()); before you check for Distance < 1. Then run the app while watching LogCat output looking for that log line.
Understand that if you have Android 4.x, it may take up to five minutes to detect in the background.
It is always easier to get apps working in the foreground first, and then add background capability. Make sure you can write code to detect your beacon in the foreground.
With help from davidgyoung's code posted on github, I was able to solve the problem.

Categories