Calling activity method from fragment showing null pointer exception - android

I have some methods in MainActivity and trying to access from fragment. But the activity is showing null.
MainActivity.java
public class MainActivity extends AppCompatActivity implements
PermissionResultListener, SwipeRefreshLayout.OnRefreshListener {
public boolean requestPermissionStorage() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this)
.setTitle(getString(R.string.storage_permission_request_title))
.setMessage(getString(R.string.storage_permission_request_summary))
.setNeutralButton(getString(R.string.ok), new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
Const.EXTDIR_REQUEST_CODE);
}
})
.setCancelable(false);
alert.create().show();
return false;
}
return true;
}
#TargetApi(23)
public void requestSystemWindowsPermission() {
if (!Settings.canDrawOverlays(this)) {
Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + getPackageName()));
startActivityForResult(intent, Const.SYSTEM_WINDOWS_CODE);
}
}
#TargetApi(23)
private void setSystemWindowsPermissionResult() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (Settings.canDrawOverlays(this)) {
mPermissionResultListener.onPermissionResult(Const.SYSTEM_WINDOWS_CODE,
new String[]{"System Windows Permission"},
new int[]{PackageManager.PERMISSION_GRANTED});
} else {
mPermissionResultListener.onPermissionResult(Const.SYSTEM_WINDOWS_CODE,
new String[]{"System Windows Permission"},
new int[]{PackageManager.PERMISSION_DENIED});
}
} else {
mPermissionResultListener.onPermissionResult(Const.SYSTEM_WINDOWS_CODE,
new String[]{"System Windows Permission"},
new int[]{PackageManager.PERMISSION_GRANTED});
}
}
public void requestPermissionAudio() {
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.RECORD_AUDIO) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.RECORD_AUDIO},
Const.AUDIO_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case Const.EXTDIR_REQUEST_CODE:
if ((grantResults.length > 0) &&
(grantResults[0] != PackageManager.PERMISSION_GRANTED)) {
Log.d(Const.TAG, "write storage Permission Denied");
fab.setEnabled(false);
} else {
Log.d(Const.TAG, "write storage Permission granted");
createDir();
}
}
if (mPermissionResultListener != null) {
mPermissionResultListener.onPermissionResult(requestCode, permissions, grantResults);
}
}
public void setPermissionResultListener(PermissionResultListener mPermissionResultListener) {
this.mPermissionResultListener = mPermissionResultListener;
}
}
SettingActivity.java
public class SettingActivity extends AppCompatPrefernceActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getFragmentManager().beginTransaction().replace(android.R.id.content, new SettingsPreferenceFragment()).commit();
}
public static class SettingsPreferenceFragment extends PreferenceFragment implements SharedPreferences.OnSharedPreferenceChangeListener
, PermissionResultListener, OnDirectorySelectedListerner {
/**
* SharedPreferences object to read the persisted settings
*/
SharedPreferences prefs;
/**
* ListPreference to choose the recording resolution
*/
private ListPreference res;
/**
* CheckBoxPreference to manage audio recording via mic setting
*/
private CheckBoxPreference recaudio;
/**
* CheckBoxPreference to manage onscreen floating control setting
*/
private CheckBoxPreference floatingControl;
/**
* FolderChooser object to choose the directory where the video has to be saved to.
*/
private FolderChooser dirChooser;
/**
* MainActivity object
*/
private MainActivity activity;
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activity = (MainActivity) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " Not MainActivity class instance");
}
}
/**
* Initialize various listeners and settings preferences.
*
* #param savedInstanceState default savedInstance bundle sent by Android runtime
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.settings);
setPermissionListener();
String defaultSaveLoc = (new File(Environment
.getExternalStorageDirectory() + File.separator + Const.APPDIR)).getPath();
prefs = getPreferenceScreen().getSharedPreferences();
res = (ListPreference) findPreference(getString(R.string.res_key));
ListPreference fps = (ListPreference) findPreference(getString(R.string.fps_key));
ListPreference bitrate = (ListPreference) findPreference(getString(R.string.bitrate_key));
recaudio = (CheckBoxPreference) findPreference(getString(R.string.audiorec_key));
ListPreference filenameFormat = (ListPreference) findPreference(getString(R.string.filename_key));
EditTextPreference filenamePrefix = (EditTextPreference) findPreference(getString(R.string.fileprefix_key));
dirChooser = (FolderChooser) findPreference(getString(R.string.savelocation_key));
floatingControl = (CheckBoxPreference) findPreference(getString(R.string.preference_floating_control_key));
CheckBoxPreference touchPointer = (CheckBoxPreference) findPreference("touch_pointer");
//Set previously chosen directory as initial directory
dirChooser.setCurrentDir(getValue(getString(R.string.savelocation_key), defaultSaveLoc));
ListPreference theme = (ListPreference) findPreference(getString(R.string.preference_theme_key));
theme.setSummary(theme.getEntry());
//Set the summary of preferences dynamically with user choice or default if no user choice is made
updateScreenAspectRatio();
updateResolution(res);
fps.setSummary(getValue(getString(R.string.fps_key), "30"));
float bps = bitsToMb(Integer.parseInt(getValue(getString(R.string.bitrate_key), "7130317")));
bitrate.setSummary(bps + " Mbps");
dirChooser.setSummary(getValue(getString(R.string.savelocation_key), defaultSaveLoc));
filenameFormat.setSummary(getFileSaveFormat());
filenamePrefix.setSummary(getValue(getString(R.string.fileprefix_key), "recording"));
//If record audio checkbox is checked, check for record audio permission
if (recaudio.isChecked())
requestAudioPermission();
//If floating controls is checked, check for system windows permission
if (floatingControl.isChecked())
requestSystemWindowsPermission();
//set callback for directory change
dirChooser.setOnDirectoryClickedListerner(this);
}
/**
* Updates the summary of resolution settings preference
*
* #param pref object of the resolution ListPreference
*/
private void updateResolution(ListPreference pref) {
pref.setSummary(getValue(getString(R.string.res_key), getNativeRes()));
}
/**
* Method to get the device's native resolution
*
* #return device resolution
*/
private String getNativeRes() {
DisplayMetrics metrics = getRealDisplayMetrics();
return getScreenWidth(metrics) + "x" + getScreenHeight(metrics);
}
/**
* Updates the available resolution based on aspect ratio
*/
private void updateScreenAspectRatio() {
Const.ASPECT_RATIO aspect_ratio = getAspectRatio();
Log.d(Const.TAG, "Aspect ratio: " + aspect_ratio);
CharSequence[] entriesValues = getResolutionEntriesValues(aspect_ratio);
res.setEntries(entriesValues);
res.setEntryValues(entriesValues);
}
/**
* Get resolutions based on the device's aspect ratio
*
* #param aspectRatio {#link com.orpheusdroid.screenrecorder.Const.ASPECT_RATIO} of the device
* #return entries for the resolution
*/
private CharSequence[] getResolutionEntriesValues(Const.ASPECT_RATIO aspectRatio) {
ArrayList<String> entries;
switch (aspectRatio) {
case AR16_9:
entries = buildEntries(R.array.resolutionsArray_16_9);
break;
case AR18_9:
entries = buildEntries(R.array.resolutionValues_18_9);
break;
default:
entries = buildEntries(R.array.resolutionsArray_16_9);
break;
}
String[] entriesArray = new String[entries.size()];
return entries.toArray(entriesArray);
}
/**
* Build resolutions from the arrays.
*
* #param resID resource ID for the resolution array
* #return ArrayList of available resolutions
*/
private ArrayList<String> buildEntries(int resID) {
DisplayMetrics metrics = getRealDisplayMetrics();
int width = getScreenWidth(metrics);
int height = getScreenHeight(metrics);
String nativeRes = width + "x" + height;
ArrayList<String> entries = new ArrayList<>(Arrays.asList(getResources().getStringArray(resID)));
Iterator<String> entriesIterator = entries.iterator();
while (entriesIterator.hasNext()) {
String entry = entriesIterator.next();
String[] widthHeight = entry.split("x");
if (width < Integer.parseInt(widthHeight[0]) || height < Integer.parseInt(widthHeight[1])) {
entriesIterator.remove();
}
}
if (!entries.contains(nativeRes))
entries.add(nativeRes);
return entries;
}
/**
* Returns object of DisplayMetrics
*
* #return DisplayMetrics
*/
private DisplayMetrics getRealDisplayMetrics(){
DisplayMetrics metrics = new DisplayMetrics();
WindowManager window = (WindowManager) getActivity().getSystemService(Context.WINDOW_SERVICE);
window.getDefaultDisplay().getRealMetrics(metrics);
return metrics;
}
/**
* Get width of screen in pixels
*
* #return screen width
*/
private int getScreenWidth(DisplayMetrics metrics) {
return metrics.widthPixels;
}
/**
* Get height of screen in pixels
*
* #return Screen height
*/
private int getScreenHeight(DisplayMetrics metrics) {
return metrics.heightPixels;
}
/**
* Get aspect ratio of the screen
*/
private Const.ASPECT_RATIO getAspectRatio() {
float screen_width = getScreenWidth(getRealDisplayMetrics());
float screen_height = getScreenHeight(getRealDisplayMetrics());
float aspectRatio;
if (screen_width > screen_height) {
aspectRatio = screen_width / screen_height;
} else {
aspectRatio = screen_height / screen_width;
}
return Const.ASPECT_RATIO.valueOf(aspectRatio);
}
/**
* Set permission listener in the {#link MainActivity} to handle permission results
*/
private void setPermissionListener() {
if (getActivity() != null && getActivity() instanceof MainActivity) {
activity = (MainActivity) getActivity();
activity.setPermissionResultListener(this);
}
}
/**
* Get the persisted value for the preference from default sharedPreference
*
* #param key String represnting the sharedpreference key to fetch
* #param defVal String Default value if the preference does not exist
* #return String the persisted preference value or default if not found
*/
private String getValue(String key, String defVal) {
return prefs.getString(key, defVal);
}
/**
* Method to convert bits per second to MB/s
*
* #param bps float bitsPerSecond
* #return float
*/
private float bitsToMb(float bps) {
return bps / (1024 * 1024);
}
//Register for OnSharedPreferenceChangeListener when the fragment resumes
#Override
public void onResume() {
super.onResume();
getPreferenceScreen().getSharedPreferences()
.registerOnSharedPreferenceChangeListener(this);
}
//Unregister for OnSharedPreferenceChangeListener when the fragment pauses
#Override
public void onPause() {
super.onPause();
getPreferenceScreen().getSharedPreferences()
.unregisterOnSharedPreferenceChangeListener(this);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
}
//When user changes preferences, update the summary accordingly
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
Preference pref = findPreference(s);
if (pref == null) return;
switch (pref.getTitleRes()) {
case R.string.preference_resolution_title:
updateResolution((ListPreference) pref);
break;
case R.string.preference_fps_title:
String fps = String.valueOf(getValue(getString(R.string.fps_key), "30"));
pref.setSummary(fps);
break;
case R.string.preference_bit_title:
float bps = bitsToMb(Integer.parseInt(getValue(getString(R.string.bitrate_key), "7130317")));
pref.setSummary(bps + " Mbps");
break;
case R.string.preference_filename_format_title:
pref.setSummary(getFileSaveFormat());
break;
case R.string.preference_audio_record_title:
requestAudioPermission();
break;
case R.string.preference_filename_prefix_title:
EditTextPreference etp = (EditTextPreference) pref;
etp.setSummary(etp.getText());
ListPreference filename = (ListPreference) findPreference(getString(R.string.filename_key));
filename.setSummary(getFileSaveFormat());
break;
case R.string.preference_floating_control_title:
requestSystemWindowsPermission();
break;
case R.string.preference_show_touch_title:
CheckBoxPreference showTouchCB = (CheckBoxPreference)pref;
if (showTouchCB.isChecked() && !hasPluginInstalled()){
showTouchCB.setChecked(false);
showDownloadAlert();
}
break;
case R.string.preference_crash_reporting_title:
CheckBoxPreference crashReporting = (CheckBoxPreference)pref;
CheckBoxPreference anonymousStats = (CheckBoxPreference) findPreference(getString(R.string.preference_anonymous_statistics_key));
if(!crashReporting.isChecked())
anonymousStats.setChecked(false);
break;
case R.string.preference_anonymous_statistics_title:
break;
case R.string.preference_theme_title:
activity.recreate();
break;
}
}
/**
* show an alert to download the plugin when the plugin is not found
*/
private void showDownloadAlert() {
new AlertDialog.Builder(getActivity())
.setTitle(R.string.alert_plugin_not_found_title)
.setMessage(R.string.alert_plugin_not_found_message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
try {
getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("market://details?id=com.orpheusdroid.screencamplugin")));
} catch (android.content.ActivityNotFoundException e) { // if there is no Google Play on device
getActivity().startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=com.orpheusdroid.screencamplugin")));
}
}
})
.setNeutralButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
}
})
.create().show();
}
/**
* Check if "show touches" plugin is installed.
*
* #return boolean
*/
private boolean hasPluginInstalled(){
PackageManager pm = getActivity().getPackageManager();
try {
pm.getPackageInfo("com.orpheusdroid.screencamplugin",PackageManager.GET_META_DATA);
} catch (PackageManager.NameNotFoundException e) {
Log.d(Const.TAG, "Plugin not installed");
return false;
}
return true;
}
/**
* Method to concat file prefix with dateTime format
*/
public String getFileSaveFormat() {
String filename = prefs.getString(getString(R.string.filename_key), "yyyyMMdd_hhmmss");
String prefix = prefs.getString(getString(R.string.fileprefix_key), "recording");
return prefix + "_" + filename;
}
/**
* Method to request android permission to record audio
*/
public void requestAudioPermission() {
if (activity != null) {
activity.requestPermissionAudio();
}
}
/**
* Method to request android system windows permission to show floating controls
* <p>
* Shown only on devices above api 23 (Marshmallow)
* </p>
*/
private void requestSystemWindowsPermission() {
if (activity != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
activity.requestSystemWindowsPermission();
} else {
Log.d(Const.TAG, "API is < 23");
}
}
/**
* Show snackbar with permission Intent when the user rejects write storage permission
*/
private void showSnackbar() {
Snackbar.make(getActivity().findViewById(R.id.fab), R.string.snackbar_storage_permission_message,
Snackbar.LENGTH_INDEFINITE).setAction(R.string.snackbar_storage_permission_action_enable,
new View.OnClickListener() {
#Override
public void onClick(View v) {
if (activity != null){
activity.requestPermissionStorage();
}
}
}).show();
}
/**
* Show a dialog when the permission to storage is denied by the user during startup
*/
private void showPermissionDeniedDialog(){
new AlertDialog.Builder(activity)
.setTitle(R.string.alert_permission_denied_title)
.setMessage(R.string.alert_permission_denied_message)
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (activity != null){
activity.requestPermissionStorage();
}
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
showSnackbar();
}
})
.setIconAttribute(android.R.attr.alertDialogIcon)
.setCancelable(false)
.create().show();
}
//Permission result callback to process the result of Marshmallow style permission request
#Override
public void onPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case Const.EXTDIR_REQUEST_CODE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_DENIED)) {
Log.d(Const.TAG, "Storage permission denied. Requesting again");
dirChooser.setEnabled(false);
showPermissionDeniedDialog();
} else if((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)){
dirChooser.setEnabled(true);
}
return;
case Const.AUDIO_REQUEST_CODE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
Log.d(Const.TAG, "Record audio permission granted.");
recaudio.setChecked(true);
} else {
Log.d(Const.TAG, "Record audio permission denied");
recaudio.setChecked(false);
}
return;
case Const.SYSTEM_WINDOWS_CODE:
if ((grantResults.length > 0) && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
Log.d(Const.TAG, "System Windows permission granted");
floatingControl.setChecked(true);
} else {
Log.d(Const.TAG, "System Windows permission denied");
floatingControl.setChecked(false);
}
default:
Log.d(Const.TAG, "Unknown permission request with request code: " + requestCode);
}
}
#Override
public void onDirectorySelected() {
Log.d(Const.TAG, "In settings fragment");
if (getActivity() != null && getActivity() instanceof MainActivity) {
((MainActivity) getActivity()).onDirectoryChanged();
}
}
}
I am trying to ask runtime permission from fragment using the methods mention in MainActivity. But activity = getActivity() is showing null.
I have tried using onAttach method in fragment, it is also not working showing class cast exception.
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
activity = (MainActivity) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " Not MainActivity class instance");
}
}

as settingActivity is the container of Fragment, you cant get the context from mainactivity unless mainactivity is container of fragment.
Solution - you can make function static or write them in extends Application Class or settingactivity

Related

Get Distance & UUID of Google Beacon

I have registered my beacon on the Google Beacon Platform and download the "Beacon Tools" android app to scan the beacon. Below I have attached its screenshot.
Now I'm developing an android app for that beacon and using this app I can get attachments that I set for the beacon. I 'am using Nearby Messages API for this. Now I want to get UUID and distance between user & beacon. I 'm new to these things and read many stackoverflow questions and answers. but those didn't solve my problem
Below I have mentioned my classes.
MainActivity.java
public class MainActivity extends AppCompatActivity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener,
SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = MainActivity.class.getSimpleName();
private static final int PERMISSIONS_REQUEST_CODE = 1111;
private static final String KEY_SUBSCRIBED = "subscribed";
/**
* The entry point to Google Play Services.
*/
private GoogleApiClient mGoogleApiClient;
/**
* The container {#link android.view.ViewGroup} for the minimal UI associated with this sample.
*/
private RelativeLayout mContainer;
/**
* Tracks subscription state. Set to true when a call to
* {#link Messages#subscribe(GoogleApiClient, MessageListener)} succeeds.
*/
private boolean mSubscribed = false;
/**
* Adapter for working with messages from nearby beacons.
*/
private ArrayAdapter<String> mNearbyMessagesArrayAdapter;
/**
* Backing data structure for {#code mNearbyMessagesArrayAdapter}.
*/
private List<String> mNearbyMessagesList = new ArrayList<>();
FirebaseDatabase db = FirebaseDatabase.getInstance();
DatabaseReference databaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
//setSupportActionBar(toolbar);
if (savedInstanceState != null) {
mSubscribed = savedInstanceState.getBoolean(KEY_SUBSCRIBED, false);
}
mContainer = (RelativeLayout) findViewById(R.id.main_activity_container);
if (!havePermissions()) {
Log.i(TAG, "Requesting permissions needed for this app.");
requestPermissions();
}
final List<String> cachedMessages = Utils.getCachedMessages(this);
if (cachedMessages != null) {
mNearbyMessagesList.addAll(cachedMessages);
}
final ListView nearbyMessagesListView = (ListView) findViewById(
R.id.nearby_messages_list_view);
mNearbyMessagesArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1,
mNearbyMessagesList);
if (nearbyMessagesListView != null) {
nearbyMessagesListView.setAdapter(mNearbyMessagesArrayAdapter);
}
}
#Override
protected void onResume() {
super.onResume();
getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE)
.registerOnSharedPreferenceChangeListener(this);
if (havePermissions()) {
buildGoogleApiClient();
}
}
#TargetApi(Build.VERSION_CODES.M)
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != PERMISSIONS_REQUEST_CODE) {
return;
}
for (int i = 0; i < permissions.length; i++) {
String permission = permissions[i];
if (grantResults[i] == PackageManager.PERMISSION_DENIED) {
if (shouldShowRequestPermissionRationale(permission)) {
Log.i(TAG, "Permission denied without 'NEVER ASK AGAIN': " + permission);
showRequestPermissionsSnackbar();
} else {
Log.i(TAG, "Permission denied with 'NEVER ASK AGAIN': " + permission);
showLinkToSettingsSnackbar();
}
} else {
Log.i(TAG, "Permission granted, building GoogleApiClient");
buildGoogleApiClient();
}
}
}
private synchronized void buildGoogleApiClient() {
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Nearby.MESSAGES_API, new MessagesOptions.Builder()
.setPermissions(NearbyPermissions.BLE).build())
.addConnectionCallbacks(this)
.enableAutoManage(this, this)
.build();
}
}
#Override
protected void onPause() {
getSharedPreferences(getApplicationContext().getPackageName(), Context.MODE_PRIVATE)
.unregisterOnSharedPreferenceChangeListener(this);
super.onPause();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
if (mContainer != null) {
Snackbar.make(mContainer, "Exception while connecting to Google Play services: " +
connectionResult.getErrorMessage(),
Snackbar.LENGTH_INDEFINITE).show();
}
}
#Override
public void onConnectionSuspended(int i) {
Log.w(TAG, "Connection suspended. Error code: " + i);
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Log.i(TAG, "GoogleApiClient connected");
subscribe();
}
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if (TextUtils.equals(key, Utils.KEY_CACHED_MESSAGES)) {
mNearbyMessagesList.clear();
mNearbyMessagesList.addAll(Utils.getCachedMessages(this));
mNearbyMessagesArrayAdapter.notifyDataSetChanged();
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(KEY_SUBSCRIBED, mSubscribed);
}
private boolean havePermissions() {
return ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED;
}
private void requestPermissions() {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, PERMISSIONS_REQUEST_CODE);
}
/**
* Calls {#link Messages#subscribe(GoogleApiClient, MessageListener, SubscribeOptions)},
* using a {#link Strategy} for BLE scanning. Attaches a {#link ResultCallback} to monitor
* whether the call to {#code subscribe()} succeeded or failed.
*/
private void subscribe() {
// In this sample, we subscribe when the activity is launched, but not on device orientation
// change.
if (mSubscribed) {
Log.i(TAG, "Already subscribed.");
return;
}
SubscribeOptions options = new SubscribeOptions.Builder()
.setStrategy(Strategy.BLE_ONLY)
.build();
Nearby.Messages.subscribe(mGoogleApiClient, getPendingIntent(), options)
.setResultCallback(new ResultCallback<Status>() {
#Override
public void onResult(#NonNull Status status) {
if (status.isSuccess()) {
Log.i(TAG, "Subscribed successfully.");
startService(getBackgroundSubscribeServiceIntent());
} else {
Log.e(TAG, "Operation failed. Error: " +
NearbyMessagesStatusCodes.getStatusCodeString(
status.getStatusCode()));
}
}
});
}
private PendingIntent getPendingIntent() {
return PendingIntent.getService(this, 0,
getBackgroundSubscribeServiceIntent(), PendingIntent.FLAG_UPDATE_CURRENT);
}
private Intent getBackgroundSubscribeServiceIntent() {
return new Intent(this, BackgroundSubscribeIntentService.class);
}
/**
* Displays {#link Snackbar} instructing user to visit Settings to grant permissions required by
* this application.
*/
private void showLinkToSettingsSnackbar() {
if (mContainer == null) {
return;
}
Snackbar.make(mContainer,
R.string.permission_denied_explanation,
Snackbar.LENGTH_INDEFINITE)
.setAction(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);
}
}).show();
}
/**
* Displays {#link Snackbar} with button for the user to re-initiate the permission workflow.
*/
private void showRequestPermissionsSnackbar() {
if (mContainer == null) {
return;
}
Snackbar.make(mContainer, R.string.permission_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
// Request permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
PERMISSIONS_REQUEST_CODE);
}
}).show();
}
}
BackgroundSubscribeIntentService.java
public class BackgroundSubscribeIntentService extends IntentService {
private static final String TAG = "BackSubIntentService";
private static final int MESSAGES_NOTIFICATION_ID = 1;
private static final int NUM_MESSAGES_IN_NOTIFICATION = 5;
public BackgroundSubscribeIntentService() {
super("BackgroundSubscribeIntentService");
}
#Override
public void onCreate() {
super.onCreate();
updateNotification();
}
#Override
protected void onHandleIntent(Intent intent) {
if (intent != null) {
Nearby.Messages.handleIntent(intent, new MessageListener() {
#Override
public void onFound(Message message) {
Utils.saveFoundMessage(getApplicationContext(), message);
updateNotification();
}
#Override
public void onLost(Message message) {
Utils.removeLostMessage(getApplicationContext(), message);
updateNotification();
}
});
}
}
private void updateNotification() {
List<String> messages = Utils.getCachedMessages(getApplicationContext());
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
launchIntent.setAction(Intent.ACTION_MAIN);
launchIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent pi = PendingIntent.getActivity(getApplicationContext(), 0,
launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
String contentTitle = getContentTitle(messages);
String contentText = getContentText(messages);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.star_on)
.setContentTitle(contentTitle)
.setContentText(contentText)
.setStyle(new NotificationCompat.BigTextStyle().bigText(contentText))
.setOngoing(true)
.setContentIntent(pi);
notificationManager.notify(MESSAGES_NOTIFICATION_ID, notificationBuilder.build());
}
private String getContentTitle(List<String> messages) {
switch (messages.size()) {
case 0:
return getResources().getString(R.string.scanning);
case 1:
return getResources().getString(R.string.one_message);
default:
return getResources().getString(R.string.many_messages, messages.size());
}
}
private String getContentText(List<String> messages) {
String newline = System.getProperty("line.separator");
if (messages.size() < NUM_MESSAGES_IN_NOTIFICATION) {
return TextUtils.join(newline, messages);
}
return TextUtils.join(newline, messages.subList(0, NUM_MESSAGES_IN_NOTIFICATION)) +
newline + "…";
}
}
Utils.java
public final class Utils {
static final String KEY_CACHED_MESSAGES = "cached-messages";
/**
* Fetches message strings stored in {#link SharedPreferences}.
*
* #param context The context.
* #return A list (possibly empty) containing message strings.
*/
static List<String> getCachedMessages(Context context) {
SharedPreferences sharedPrefs = getSharedPreferences(context);
String cachedMessagesJson = sharedPrefs.getString(KEY_CACHED_MESSAGES, "");
if (TextUtils.isEmpty(cachedMessagesJson)) {
return Collections.emptyList();
} else {
Type type = new TypeToken<List<String>>() {}.getType();
return new Gson().fromJson(cachedMessagesJson, type);
}
}
/**
* Saves a message string to {#link SharedPreferences}.
*
* #param context The context.
* #param message The Message whose payload (as string) is saved to SharedPreferences.
*/
static void saveFoundMessage(Context context, Message message) {
ArrayList<String> cachedMessages = new ArrayList<>(getCachedMessages(context));
Set<String> cachedMessagesSet = new HashSet<>(cachedMessages);
String messageString = new String(message.getContent());
if (!cachedMessagesSet.contains(messageString)) {
cachedMessages.add(0, new String(message.getContent()));
getSharedPreferences(context)
.edit()
.putString(KEY_CACHED_MESSAGES, new Gson().toJson(cachedMessages))
.apply();
}
}
/**
* Removes a message string from {#link SharedPreferences}.
* #param context The context.
* #param message The Message whose payload (as string) is removed from SharedPreferences.
*/
static void removeLostMessage(Context context, Message message) {
ArrayList<String> cachedMessages = new ArrayList<>(getCachedMessages(context));
cachedMessages.remove(new String(message.getContent()));
getSharedPreferences(context)
.edit()
.putString(KEY_CACHED_MESSAGES, new Gson().toJson(cachedMessages))
.apply();
}
/**
* Gets the SharedPReferences object that is used for persisting data in this application.
*
* #param context The context.
* #return The single {#link SharedPreferences} instance that can be used to retrieve and
modify values.
*/
static SharedPreferences getSharedPreferences(Context context) {
return context.getSharedPreferences(
context.getApplicationContext().getPackageName(),
Context.MODE_PRIVATE);
}
}
How can I get UUID and distance of the beacon and where I can apply the code. I have no prior experience of beacons.
The code shown in the question sets up a background subscription to BLE beacon Nearby messages that are delivered to a service by a PendingIntent: Nearby.Messages.subscribe(mGoogleApiClient, getPendingIntent(), options).setResultCallback(...);
Unfortunately, Google Nearby does not support delivering signal strength or distance estimates to background subscriptions. You can only do this with foreground subscriptions:
RSSI and Distance Callbacks
In addition to found and lost callbacks, a foreground subscription can update your MessageListener when Nearby has new information about the BLE signal associated with a message.
Note:
These extra callbacks are currently only delivered for BLE beacon messages (both attachments and beacon IDs).
These extra callbacks are not delivered to background (PendingIntent) subscriptions.
See https://developers.google.com/nearby/messages/android/advanced
If you want to get signal strength and distance estimates, with Google Nearby you must rewrite your code to use a foreground only subscription. The results will only be delivered if your app is in the foreground.
MessageListener messageListener = new MessageListener() {
#Override
public void onFound(final Message message) {
Log.i(TAG, "Found message: " + message);
}
#Override
public void onBleSignalChanged(final Message message, final BleSignal bleSignal) {
Log.i(TAG, "Message: " + message + " has new BLE signal information: " + bleSignal);
}
#Override
public void onDistanceChanged(final Message message, final Distance distance) {
Log.i(TAG, "Distance changed, message: " + message + ", new distance: " + distance);
}
#Override
public void onLost(final Message message) {
Log.i(TAG, "Lost message: " + message);
}
};
Nearby.getMessagesClient(this).subscribe(messageListener, options);
The link above shows a full example of how to do that.

HERE Map Turn By Turn Activate

i'm developing turn by turn based navigation application on android. I'm using HERE maps sdk for android. I can't switch to navigation driver mode for turn by turn navigation. How can i switch normal map to turn by turn mode.
Note: I changed to map scheme mode
map.setMapScheme(Map.Scheme.CARNAV_TRAFFIC_DAY);
public class BasicMapActivity extends Activity {
// permissions request code
private final static int REQUEST_CODE_ASK_PERMISSIONS = 1;
private PositioningManager posManager;
private MapRoute mapRoute;
private Route route;
private GeoPosition myPosition;
/**
* Permissions that need to be explicitly requested from end user.
*/
private static final String[] REQUIRED_SDK_PERMISSIONS = new String[] {
Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.WRITE_EXTERNAL_STORAGE };
// map embedded in the map fragment
private Map map = null;
// map fragment embedded in this activity
private MapFragment mapFragment = null;
private PositioningManager.OnPositionChangedListener positionListener = new PositioningManager.OnPositionChangedListener() {
#Override
public void onPositionUpdated(PositioningManager.LocationMethod locationMethod, GeoPosition geoPosition, boolean b) {
Log.v("HERE MAP",geoPosition.getCoordinate().toString());
myPosition = geoPosition;
map.setCenter(geoPosition.getCoordinate(),
Map.Animation.BOW);
// Set the zoom level to the average between min and max
}
#Override
public void onPositionFixChanged(PositioningManager.LocationMethod locationMethod, PositioningManager.LocationStatus locationStatus) {
}
};
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
checkPermissions();
}
#Override
protected void onResume() {
super.onResume();
if (posManager != null) {
posManager.start(
PositioningManager.LocationMethod.GPS_NETWORK);
}
}
#Override
protected void onPause() {
super.onPause();
if (posManager != null) {
posManager.stop();
}
}
public void onDestroy() {
if (posManager != null) {
// Cleanup
posManager.removeListener(
positionListener);
}
map = null;
super.onDestroy();
}
private void initialize() {
setContentView(R.layout.activity_main);
findViewById(R.id.btnDrawRoute).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
drawRoute();
}
});
findViewById(R.id.btnChangeMap).setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
setNavigationManager();
NavigationManager.Error error = NavigationManager.getInstance().startNavigation(route);
if(error.equals(NavigationManager.Error.NONE)){
map.setExtrudedBuildingsVisible(false);
}
}
});
// Search for the map fragment to finish setup by calling init().
mapFragment = (MapFragment) getFragmentManager().findFragmentById(R.id.mapfragment);
mapFragment.init(new OnEngineInitListener() {
#Override
public void onEngineInitializationCompleted(OnEngineInitListener.Error error) {
if (error == OnEngineInitListener.Error.NONE) {
// retrieve a reference of the map from the map fragment
map = mapFragment.getMap();
// Set the map center to the Vancouver region (no animation)
map.setZoomLevel((map.getMaxZoomLevel() + map.getMinZoomLevel()) / 2);
map.setCartoMarkersVisible(true);
map.setLandmarksVisible(true);
map.setMapScheme(Map.Scheme.CARNAV_DAY);
map.setTrafficInfoVisible(true);
map.setExtrudedBuildingsVisible(true);
map.setStreetLevelCoverageVisible(true);
mapFragment.getPositionIndicator().setVisible(true);
try {
posManager = PositioningManager.getInstance();
posManager.addListener(new WeakReference<>(positionListener));
posManager.start(
PositioningManager.LocationMethod.GPS_NETWORK);
}catch (Exception ex){
Log.v("Error",ex.getMessage());
}
} else {
System.out.println("ERROR: Cannot initialize Map Fragment");
}
}
});
}
private void setNavigationManager() {
NavigationManager.getInstance().setMap(map);
NavigationManager.getInstance().setMapUpdateMode(NavigationManager.MapUpdateMode.ROADVIEW);
NavigationManager.getInstance().setTrafficAvoidanceMode(NavigationManager.TrafficAvoidanceMode.DYNAMIC);
NavigationManager.getInstance().setRealisticViewMode(NavigationManager.RealisticViewMode.DAY);
NavigationManager.getInstance().setDistanceUnit(NavigationManager.UnitSystem.METRIC);
ArrayList<NavigationManager.NaturalGuidanceMode> arrayList = new ArrayList<NavigationManager.NaturalGuidanceMode>();
arrayList.add(NavigationManager.NaturalGuidanceMode.JUNCTION);
arrayList.add(NavigationManager.NaturalGuidanceMode.STOP_SIGN);
arrayList.add(NavigationManager.NaturalGuidanceMode.TRAFFIC_LIGHT);
EnumSet<NavigationManager.NaturalGuidanceMode> enumSet = EnumSet.copyOf(arrayList);
NavigationManager.getInstance().setNaturalGuidanceMode(enumSet);
setVoice();
ArrayList<NavigationManager.AudioEvent> audioEvents = new ArrayList<>();
audioEvents.add(NavigationManager.AudioEvent.ROUTE);
audioEvents.add(NavigationManager.AudioEvent.GPS);
NavigationManager.getInstance().setEnabledAudioEvents(EnumSet.copyOf(audioEvents));
NavigationManager.getInstance().addNewInstructionEventListener(new WeakReference<NavigationManager.NewInstructionEventListener>(new NavigationManager.NewInstructionEventListener() {
#Override
public void onNewInstructionEvent() {
super.onNewInstructionEvent();
Maneuver maneuver = NavigationManager.getInstance().getNextManeuver();
Log.v("Manevra",maneuver.getNextRoadName() + " "+maneuver.getRoadName());
maneuver.getRoadName();
}
}));
NavigationManager.getInstance().addManeuverEventListener(new WeakReference<NavigationManager.ManeuverEventListener>(new NavigationManager.ManeuverEventListener() {
#Override
public void onManeuverEvent() {
super.onManeuverEvent();
}
}));
NavigationManager.getInstance().addPositionListener(new WeakReference<NavigationManager.PositionListener>(new NavigationManager.PositionListener() {
#Override
public void onPositionUpdated(GeoPosition geoPosition) {
super.onPositionUpdated(geoPosition);
geoPosition.getCoordinate();
geoPosition.getHeading();
geoPosition.getSpeed();
// also remaining time and distance can be
// fetched from navigation manager
NavigationManager.getInstance().getTta(Route.TrafficPenaltyMode.DISABLED, true);
NavigationManager.getInstance().getDestinationDistance();
}
}));
}
private void setVoice() {
// Get the list of voice packages from the voice catalog list
List<VoicePackage> voicePackages = VoiceCatalog.getInstance().getCatalogList();
long id = -1;
// select
for (VoicePackage vPackage : voicePackages) {
if (vPackage.getMarcCode().compareToIgnoreCase("eng") == 0) {
if (vPackage.isTts()) {
id = vPackage.getId();
break;
}
}
}
if(id>-1)
NavigationManager.getInstance().setVoiceSkin(VoiceCatalog.getInstance().getLocalVoiceSkin(id));
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
/**
* Checks the dynamically controlled permissions and requests missing permissions from end user.
*/
protected void checkPermissions() {
final List<String> missingPermissions = new ArrayList<String>();
// check all required dynamic permissions
for (final String permission : REQUIRED_SDK_PERMISSIONS) {
final int result = ContextCompat.checkSelfPermission(this, permission);
if (result != PackageManager.PERMISSION_GRANTED) {
missingPermissions.add(permission);
}
}
if (!missingPermissions.isEmpty()) {
// request all missing permissions
final String[] permissions = missingPermissions
.toArray(new String[missingPermissions.size()]);
ActivityCompat.requestPermissions(this, permissions, REQUEST_CODE_ASK_PERMISSIONS);
} else {
final int[] grantResults = new int[REQUIRED_SDK_PERMISSIONS.length];
Arrays.fill(grantResults, PackageManager.PERMISSION_GRANTED);
onRequestPermissionsResult(REQUEST_CODE_ASK_PERMISSIONS, REQUIRED_SDK_PERMISSIONS,
grantResults);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_CODE_ASK_PERMISSIONS:
for (int index = permissions.length - 1; index >= 0; --index) {
if (grantResults[index] != PackageManager.PERMISSION_GRANTED) {
// exit the app if one permission is not granted
Toast.makeText(this, "Required permission '" + permissions[index]
+ "' not granted, exiting", Toast.LENGTH_LONG).show();
finish();
return;
}
}
// all permissions were granted
initialize();
break;
}
}
private void drawRoute(){
CoreRouter router = new CoreRouter();
GeoCoordinate gebzeCoord = new GeoCoordinate(40.9047617,29.4065243);
GeoCoordinate maslakCoord = new GeoCoordinate(41.1066509,29.0204711);
// Create the RoutePlan and add two waypoints
RoutePlan routePlan = new RoutePlan();
routePlan.addWaypoint(new RouteWaypoint(myPosition.getCoordinate()));
routePlan.addWaypoint(new RouteWaypoint(maslakCoord));
// Create the RouteOptions and set its transport mode & routing type
RouteOptions routeOptions = new RouteOptions();
routeOptions.setTransportMode(RouteOptions.TransportMode.CAR);
routeOptions.setRouteType(RouteOptions.Type.FASTEST);
routePlan.setRouteOptions(routeOptions);
// Calculate the route
router.calculateRoute(routePlan, new RouteListener());
TrafficUpdater trafficUpdater = TrafficUpdater.getInstance();
trafficUpdater.request(route, new TrafficUpdater.Listener() {
#Override
public void onStatusChanged(TrafficUpdater.RequestState requestState) {
}
});
}
private class RouteListener implements CoreRouter.Listener {
// Method defined in Listener
public void onProgress(int percentage) {
// Display a message indicating calculation progress
}
// Method defined in Listener
public void onCalculateRouteFinished(List<RouteResult> routeResult, RoutingError error) {
// If the route was calculated successfully
if (error == RoutingError.NONE) {
// Render the route on the map
mapRoute = new MapRoute(routeResult.get(0).getRoute());
route = routeResult.get(0).getRoute();
map.addMapObject(mapRoute);
}
else {
// Display a message indicating route calculation failure
}
}
}
}
Declare NavigationManager's object as a global object.
private NavigationManager m_navigationManager;
after that initialize it in your setNavigationManager() method.
m_navigationManager = NavigationManager.getInstance();
m_navigationManager.setMap(map);
// try to change current MapUpdateMode to POSITION_ANIMATION
m_navigationManager.setMapUpdateMode(NavigationManager.MapUpdateMode.POSITION_ANIMATION);
m_navigationManager.setTrafficAvoidanceMode(NavigationManager.TrafficAvoidanceMode.DYNAMIC);
m_navigationManager.setRealisticViewMode(NavigationManager.RealisticViewMode.DAY);
// set all other method on this object.
m_navigationManager.......
After you have to start navigation like this
NavigationManager.Error error = m_navigationManager.startNavigation(route);
if (error != NavigationManager.Error.NONE) {
m_navigationManager.setMap(null);
}
//set Tilt to at some angle that you can look in 3d mode
map.setTilt(70f, com.here.android.mpa.mapping.Map.Animation.NONE);
map.setZoomLevel(18);

Pictures taken after first shot have low lighting

I am taking pics on android 4.4 using code from here [1]: http://www.vogella.com/tutorials/AndroidCamera/article.html "4. Tutorial: Using the camera API" and using Eclipse "Full Screen activity" as template.
The first picture is normal, but after that the subsequent pictures are too dark to be useful.
I searched SO but couldn't fix it. What am I doing wrong here ?
My MainActivity Class
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*
* #see SystemUiHider
*/
public class DashboardActivity extends Activity {
static final String DEBUG_TAG = "fsym";
static String fileName = "";
private Camera camera;
private int cameraId = 0;
static long numPics = 1;
private TextView results;
private ImageView displayArea;
float dpHeight, dpWidth;
/**
* Whether or not the system UI should be auto-hidden after
* {#link #AUTO_HIDE_DELAY_MILLIS} milliseconds.
*/
private static final boolean AUTO_HIDE = true;
/**
* If {#link #AUTO_HIDE} is set, the number of milliseconds to wait after
* user interaction before hiding the system UI.
*/
private static final int AUTO_HIDE_DELAY_MILLIS = 3000;
/**
* If set, will toggle the system UI visibility upon interaction. Otherwise,
* will show the system UI visibility upon interaction.
*/
private static final boolean TOGGLE_ON_CLICK = true;
/**
* The flags to pass to {#link SystemUiHider#getInstance}.
*/
private static final int HIDER_FLAGS = SystemUiHider.FLAG_HIDE_NAVIGATION;
/**
* The instance of the {#link SystemUiHider} for this activity.
*/
private SystemUiHider mSystemUiHider;
#Override
protected void onCreate(Bundle savedInstanceState) {
Log.d(DashboardActivity.DEBUG_TAG, "onCreate called");
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dashboard);
DisplayMetrics displayMetrics = getResources().getDisplayMetrics();
dpHeight = displayMetrics.heightPixels / displayMetrics.density;
dpWidth = displayMetrics.widthPixels / displayMetrics.density;
final View controlsView = findViewById(R.id.fullscreen_content_controls);
final View contentView = findViewById(R.id.fullscreen_content);
results = (TextView) findViewById(R.id.resultTxtBox);
displayArea = (ImageView) findViewById(R.id.imagePanel);
// Set up an instance of SystemUiHider to control the system UI for
// this activity.
mSystemUiHider = SystemUiHider.getInstance(this, contentView, HIDER_FLAGS);
mSystemUiHider.setup();
mSystemUiHider.setOnVisibilityChangeListener(new SystemUiHider.OnVisibilityChangeListener() {
// Cached values.
int mControlsHeight;
int mShortAnimTime;
#Override
#TargetApi(Build.VERSION_CODES.HONEYCOMB_MR2)
public void onVisibilityChange(boolean visible) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
// If the ViewPropertyAnimator API is available
// (Honeycomb MR2 and later), use it to animate the
// in-layout UI controls at the bottom of the
// screen.
if (mControlsHeight == 0) {
mControlsHeight = controlsView.getHeight();
}
if (mShortAnimTime == 0) {
mShortAnimTime = getResources().getInteger(android.R.integer.config_shortAnimTime);
}
controlsView.animate().translationY(visible ? 0 : mControlsHeight).setDuration(mShortAnimTime);
} else {
// If the ViewPropertyAnimator APIs aren't
// available, simply show or hide the in-layout UI
// controls.
controlsView.setVisibility(visible ? View.VISIBLE : View.GONE);
}
if (visible && AUTO_HIDE) {
// Schedule a hide().
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
}
});
// Set up the user interaction to manually show or hide the system UI.
contentView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (TOGGLE_ON_CLICK) {
mSystemUiHider.toggle();
} else {
mSystemUiHider.show();
}
}
});
// Upon interacting with UI controls, delay any scheduled hide()
// operations to prevent the jarring behavior of controls going away
// while interacting with the UI.
findViewById(R.id.takePicBtn).setOnTouchListener(mDelayHideTouchListener);
results.setOnTouchListener(mDelayHideTouchListener);
// do we have a camera?
if (!getPackageManager()
.hasSystemFeature(PackageManager.FEATURE_CAMERA)) {
Toast.makeText(this, "No camera on this device", Toast.LENGTH_LONG)
.show();
} else {
cameraId = findFrontFacingCamera();
if (cameraId < 0) {
Toast.makeText(this, "No front facing camera found.",
Toast.LENGTH_LONG).show();
} else {
camera = Camera.open(cameraId);
}
}
}
#Override
protected void onPostCreate(Bundle savedInstanceState) {
Log.d(DashboardActivity.DEBUG_TAG, "onPostCreate called");
super.onPostCreate(savedInstanceState);
uiUpdateRunnable.run();
// Trigger the initial hide() shortly after the activity has been
// created, to briefly hint to the user that UI controls
// are available.
delayedHide(100);
}
/**
* Touch listener to use for in-layout UI controls to delay hiding the
* system UI. This is to prevent the jarring behavior of controls going away
* while interacting with activity UI.
*/
View.OnTouchListener mDelayHideTouchListener = new View.OnTouchListener() {
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
if (AUTO_HIDE) {
delayedHide(AUTO_HIDE_DELAY_MILLIS);
}
return false;
}
};
Handler mHideHandler = new Handler();
Runnable mHideRunnable = new Runnable() {
#Override
public void run() {
mSystemUiHider.hide();
}
};
/**
* Schedules a call to hide() in [delay] milliseconds, canceling any
* previously scheduled calls.
*/
private void delayedHide(int delayMillis) {
Log.d(DashboardActivity.DEBUG_TAG, "delayedHide called");
mHideHandler.removeCallbacks(mHideRunnable);
mHideHandler.postDelayed(mHideRunnable, delayMillis);
}
Handler uiUpdatehandler = new Handler();
Runnable uiUpdateRunnable = new Runnable() {
#Override
public void run() {
if (fileName!=null && fileName.trim().length()>0){
displayArea.setImageBitmap(BitmapFactory.decodeFile(fileName));
displayArea.setRotation(-90);
displayArea.setScaleType(ScaleType.CENTER_INSIDE);
}
results.setText("Ratio:"+FaceAnalyzer.measureFace(fileName));
//results.invalidate();
//displayArea.invalidate();
uiUpdatehandler.postDelayed(uiUpdateRunnable,1000);
}
};
public void takePicture(View view){
Log.d(DashboardActivity.DEBUG_TAG, "takePicture called");
camera.takePicture(null, null, new PhotoHandler(getApplicationContext()));
}
public void quitApp(View view){
uiUpdatehandler.removeCallbacks(uiUpdateRunnable);
finish();
System.exit(0);
}
private int findFrontFacingCamera() {
Log.d(DashboardActivity.DEBUG_TAG, "findFrontfacingCamera called");
int cameraId = -1;
// Search for the front facing camera
int numberOfCameras = Camera.getNumberOfCameras();
for (int i = 0; i < numberOfCameras; i++) {
CameraInfo info = new CameraInfo();
Camera.getCameraInfo(i, info);
if (info.facing == CameraInfo.CAMERA_FACING_FRONT) {
Log.d(DEBUG_TAG, "Camera found");
cameraId = i;
break;
}
}
return cameraId;
}
#Override
protected void onPause() {
Log.d(DashboardActivity.DEBUG_TAG, "onPause called");
if (camera != null) {
camera.release();
camera = null;
}
super.onPause();
}
}
My PhotoHandler:
public class PhotoHandler implements PictureCallback {
private final Context context;
public PhotoHandler(Context context) {
Log.d(DashboardActivity.DEBUG_TAG, "Photohandler contstructor called");
this.context = context;
}
#Override
public void onPictureTaken(byte[] data, Camera camera) {
Log.d(DashboardActivity.DEBUG_TAG, "onPicturetaken called");
File pictureFileDir = getDir();
if (!pictureFileDir.exists() && !pictureFileDir.mkdirs()) {
Log.d(DashboardActivity.DEBUG_TAG, "Can't create directory to save image.");
Toast.makeText(context, "Can't create directory to save image.",
Toast.LENGTH_LONG).show();
return;
}
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyymmddhhmmss");
String date = dateFormat.format(new Date());
String photoFile = "Picture_" + date +"_" +DashboardActivity.numPics+".jpg";
String filename = pictureFileDir.getPath() + File.separator + photoFile;
File pictureFile = new File(filename);
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
fos.write(data);
fos.close();
Toast.makeText(context, "New Image saved:" + photoFile,
Toast.LENGTH_LONG).show();
Log.d(DashboardActivity.DEBUG_TAG, "New Image saved:" + photoFile);
DashboardActivity.fileName = filename;
DashboardActivity.numPics++;
} catch (Exception error) {
Log.d(DashboardActivity.DEBUG_TAG, "File" + filename + "not saved: "
+ error.getMessage());
Toast.makeText(context, "Image could not be saved.",
Toast.LENGTH_LONG).show();
}
}
private File getDir() {
Log.d(DashboardActivity.DEBUG_TAG, "getDir called");
File sdDir = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
return new File(sdDir, "FacialSymmetryAnalyzer");
}
}
What am I doing wrong here ?

how to sign out from Google Account and show account chooser again using Google Drive Android Api

I have implemented a code to open the selected file from Google Drive on Google Drive Android Application through opener activity. In this application i need to place sign out option to choose different account. But this code will ask sign in only once after that i cant remove that signed-in user from my application.
Is it possible to sign out from Google account and show account chooser again using Google Drive Android Api ?
BaseDemoActivity.java
public abstract class BaseDemoActivity extends Activity implements
GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener {
private static final String TAG = "BaseDriveActivity";
/**
* DriveId of an existing folder to be used as a parent folder in
* folder operations samples.
*/
public static final String EXISTING_FOLDER_ID = "folderid";
/**
* DriveId of an existing file to be used in file operation samples..
*/
public static final String EXISTING_FILE_ID = "fileid";
/**
* Extra for account name.
*/
protected static final String EXTRA_ACCOUNT_NAME = "account_name";
/**
* Request code for auto Google Play Services error resolution.
*/
protected static final int REQUEST_CODE_RESOLUTION = 1;
/**
* Next available request code.
*/
protected static final int NEXT_AVAILABLE_REQUEST_CODE = 2;
/**
* Google API client.
*/
private GoogleApiClient mGoogleApiClient;
/**
* Called when activity gets visible. A connection to Drive services need to
* be initiated as soon as the activity is visible. Registers
* {#code ConnectionCallbacks} and {#code OnConnectionFailedListener} on the
* activities itself.
*/
#Override
protected void onResume() {
super.onResume();
if (mGoogleApiClient == null) {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addApi(Drive.API)
.addScope(Drive.SCOPE_FILE)
.addScope(Drive.SCOPE_APPFOLDER) // required for App Folder sample
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
}
mGoogleApiClient.connect();
}
/**
* Handles resolution callbacks.
*/
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == REQUEST_CODE_RESOLUTION && resultCode == RESULT_OK) {
mGoogleApiClient.connect();
}
}
/**
* Called when activity gets invisible. Connection to Drive service needs to
* be disconnected as soon as an activity is invisible.
*/
#Override
protected void onPause() {
if (mGoogleApiClient != null) {
mGoogleApiClient.disconnect();
}
super.onPause();
}
/**
* Called when {#code mGoogleApiClient} is connected.
*/
#Override
public void onConnected(Bundle connectionHint) {
Log.i(TAG, "GoogleApiClient connected");
}
/**
* Called when {#code mGoogleApiClient} is disconnected.
*/
#Override
public void onConnectionSuspended(int cause) {
Log.i(TAG, "GoogleApiClient connection suspended");
}
/**
* Called when {#code mGoogleApiClient} is trying to connect but failed.
* Handle {#code result.getResolution()} if there is a resolution is
* available.
*/
#Override
public void onConnectionFailed(ConnectionResult result) {
Log.i(TAG, "GoogleApiClient connection failed: " + result.toString());
if (!result.hasResolution()) {
// show the localized error dialog.
GooglePlayServicesUtil.getErrorDialog(result.getErrorCode(), this, 0).show();
return;
}
try {
result.startResolutionForResult(this, REQUEST_CODE_RESOLUTION);
} catch (SendIntentException e) {
Log.e(TAG, "Exception while starting resolution activity", e);
}
}
/**
* Shows a toast message.
*/
public void showMessage(String message) {
Toast.makeText(this, message, Toast.LENGTH_LONG).show();
}
/**
* Getter for the {#code GoogleApiClient}.
*/
public GoogleApiClient getGoogleApiClient() {
return mGoogleApiClient;
}
}
MainActivity.java
public class MainActivity extends BaseDemoActivity {
private static final String TAG = "MainActivity";
private static final int RC_SIGN_IN = 0;
private boolean mIntentInProgress;
private ConnectionResult mConnectionResult;
private static final int REQUEST_CODE_OPENER = 1;
private boolean browsefile = false;
private boolean mSignInClicked;
private String FILE_ID;
TextView filepath;
Button choosefilebutton;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
choosefilebutton = (Button) findViewById(R.id.choosefilebutton);
filepath = (TextView) findViewById(R.id.filepath);
choosefilebutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
open();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_logout:
signOutFromGplus();
choosefilebutton.setVisibility(View.GONE);
break;
default:
break;
}
return true;
}
#Override
public void onConnected(Bundle connectionHint) {
super.onConnected(connectionHint);
//mSignInClicked = false;
}
private void open(){
IntentSender intentSender = Drive.DriveApi
.newOpenFileActivityBuilder()
.build(getGoogleApiClient());
try {
browsefile = true;
startIntentSenderForResult(
intentSender, REQUEST_CODE_OPENER, null, 0, 0, 0);
} catch (SendIntentException e) {
Log.w(TAG, "Unable to send intent", e);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_CODE_OPENER:
if (resultCode == RESULT_OK && browsefile == true) {
showMessage("Result ok...");
if (!getGoogleApiClient().isConnecting()) {
getGoogleApiClient().connect();
}
DriveId driveId = (DriveId) data.getParcelableExtra(
OpenFileActivityBuilder.EXTRA_RESPONSE_DRIVE_ID);
showMessage("Selected file's ID: " + driveId.getResourceId());
FILE_ID = driveId.getResourceId();
if(FILE_ID != null){
String link = "https://docs.google.com/file/d/"+FILE_ID;
filepath.setText(link);
Uri path = Uri.parse(link);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(path);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
startActivity(intent);
} catch (Exception e) {
showMessage(e.getMessage());
}
}
}
//finish();
break;
default:
super.onActivityResult(requestCode, resultCode, data);
}
}
/**
* Sign-out from google
* */
private void signOutFromGplus() {
if (getGoogleApiClient().isConnected()) {
getGoogleApiClient().disconnect();
showMessage("Sign out Success...");
}
}
}
Take a look at my answer in SO 21610239, specifically the UPDATE 2014-11-04 section.

How to add pattern lock functionality code in android ??

i have gone through this link https://code.google.com/p/android-lockpattern/ to apply pattern functionality in my application. But i am facing some issues, I have created continue button to move to next screen for confirming the pattern but its not working at all. I want that when user starts to draw the pattern on the first screen continue button should start working but its not working so. Please tell me the solution.I am attaching my MainActivity.java code.
Thanks in advance
package com.example.lock_pattern;
import com.example.lock_pattern.prefs.DisplayPrefs;
public class MainActivity extends Activity {
private static final String CLASSNAME = MainActivity.class.getName();
public static final String ACTION_CREATE_PATTERN = CLASSNAME
+ ".create_pattern";
public static final String ACTION_COMPARE_PATTERN = CLASSNAME
+ ".compare_pattern";
public static final String ACTION_VERIFY_CAPTCHA = CLASSNAME
+ ".verify_captcha";
* If you use {#link #ACTION_COMPARE_PATTERN} and the user fails to "login"
public static final int RESULT_FAILED = RESULT_FIRST_USER + 1;
* If you use {#link #ACTION_COMPARE_PATTERN} and the user forgot his/ her
public static final int RESULT_FORGOT_PATTERN = RESULT_FIRST_USER + 2;
* If you use {#link #ACTION_COMPARE_PATTERN}, and the user fails to "login"
public static final String EXTRA_RETRY_COUNT = CLASSNAME + ".retry_count";
* Sets value of this key to a theme in {#code R.style.Alp_Theme_*}. Default
public static final String EXTRA_THEME = CLASSNAME + ".theme";
* Key to hold the pattern. It must be a {#code char[]} array.
public static final String EXTRA_PATTERN = CLASSNAME + ".pattern";
* You can provide an {#link ResultReceiver} with this key. The activity
public static final String EXTRA_RESULT_RECEIVER = CLASSNAME
+ ".result_receiver";
* Put a {#link PendingIntent} into this key. It will be sent before
public static final String EXTRA_PENDING_INTENT_OK = CLASSNAME
+ ".pending_intent_ok";
* Put a {#link PendingIntent} into this key. It will be sent before
public static final String EXTRA_PENDING_INTENT_CANCELLED = CLASSNAME
+ ".pending_intent_cancelled";
* You put a {#link Intent} of <i>{#link Activity}</i> into this extra. The
public static final String EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN = CLASSNAME
+ ".intent_activity_forgot_pattern";
* Helper enum for button OK commands. (Because we use only one "OK" button
private static enum ButtonOkCommand {
CONTINUE, FORGOT_PATTERN, DONE
}// ButtonOkCommand
* Delay time to reload the lock pattern view after a wrong pattern.
private static final long DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW = DateUtils.SECOND_IN_MILLIS;
/*
* FIELDS
*/
private int mMaxRetry;
private boolean mAutoSave;
private IEncrypter mEncrypter;
private int mMinWiredDots;
private ButtonOkCommand mBtnOkCmd;
private Intent mIntentResult;
private int mRetryCount = 0;
/*
* CONTROLS
*/
private TextView mTextInfo;
private LockPatternView mLockPatternView;
private View mFooter;
private Button mBtnCancel;
private Button mBtnConfirm;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG)
Log.d(CLASSNAME, "ClassName = " + CLASSNAME);
/*
* EXTRA_THEME
*/
if (getIntent().hasExtra(EXTRA_THEME))
setTheme(getIntent().getIntExtra(EXTRA_THEME,
R.style.Alp_Theme_Dark));
super.onCreate(savedInstanceState);
Toast.makeText(getApplicationContext(), "oncreate", 7000).show();
mMinWiredDots = DisplayPrefs.getMinWiredDots(this);
mMaxRetry = DisplayPrefs.getMaxRetry(this);
mAutoSave = SecurityPrefs.isAutoSavePattern(this);
/*
* Encrypter.
*/
char[] encrypterClass = SecurityPrefs.getEncrypterClass(this);
if (encrypterClass != null) {
try {
mEncrypter = (IEncrypter) Class.forName(
new String(encrypterClass), false, getClassLoader())
.newInstance();
} catch (Throwable t) {
throw new InvalidEncrypterException();
}
}
mIntentResult = new Intent();
setResult(RESULT_CANCELED, mIntentResult);
initContentView();
}// onCreate()
#Override
public void onConfigurationChanged(Configuration newConfig) {
Log.d(CLASSNAME, "onConfigurationChanged()");
super.onConfigurationChanged(newConfig);
initContentView();
}// onConfigurationChanged()
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
Toast.makeText(getApplicationContext(), "Inside onKeyDown", Toast.LENGTH_LONG).show();
if (keyCode == KeyEvent.KEYCODE_BACK
&& ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
/*
* Use this hook instead of onBackPressed(), because onBackPressed()
* is not available in API 4.
*/
finishWithNegativeResult(RESULT_CANCELED);
return true;
}
return super.onKeyDown(keyCode, event);
}// onKeyDown()
#Override
protected void onDestroy() {
super.onDestroy();
if (BuildConfig.DEBUG)
Log.d(CLASSNAME, "onDestroy()");
}// onDestroy()
/**
* Initializes UI...
*/
private void initContentView() {
/*
* Save all controls' state to restore later.
*/
CharSequence infoText = mTextInfo != null ? mTextInfo.getText() : null;
Boolean btnOkEnabled = mBtnConfirm != null ? mBtnConfirm.isEnabled()
: null;
LockPatternView.DisplayMode lastDisplayMode = mLockPatternView != null ? mLockPatternView
.getDisplayMode() : null;
List<Cell> lastPattern = mLockPatternView != null ? mLockPatternView
.getPattern() : null;
setContentView(R.layout.activity_main);
UI.adjustDialogSizeForLargeScreen(getWindow());
mTextInfo = (TextView) findViewById(R.id.alp_textview_info);
mLockPatternView = (LockPatternView) findViewById(R.id.alp_view_lock_pattern);
mFooter = findViewById(R.id.alp_viewgroup_footer);
mBtnCancel = (Button) findViewById(R.id.alp_button_cancel);
mBtnConfirm = (Button) findViewById(R.id.alp_button_confirm);
/*
* LOCK PATTERN VIEW
*/
if (getResources().getBoolean(R.bool.alp_is_large_screen)) {
int size = getResources().getDimensionPixelSize(
R.dimen.alp_lockpatternview_size);
LayoutParams lp = mLockPatternView.getLayoutParams();
lp.width = size;
lp.height = size;
mLockPatternView.setLayoutParams(lp);
}
/*
* Haptic feedback.
*/
boolean hapticFeedbackEnabled = false;
try {
hapticFeedbackEnabled = Settings.System.getInt(
getContentResolver(),
Settings.System.HAPTIC_FEEDBACK_ENABLED, 0) != 0;
} catch (Throwable t) {
/*
* Ignore it.
*/
}
mLockPatternView.setTactileFeedbackEnabled(hapticFeedbackEnabled);
mLockPatternView.setInStealthMode(DisplayPrefs.isStealthMode(this)
&& !ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction()));
mLockPatternView.setOnPatternListener(mLockPatternViewListener);
if (lastPattern != null && lastDisplayMode != null
&& !ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction()))
mLockPatternView.setPattern(lastDisplayMode, lastPattern);
/*
* COMMAND BUTTONS
*/
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
Toast.makeText(getApplicationContext(), "initContentView", 7000).show();
mBtnCancel.setOnClickListener(mBtnCancelOnClickListener);
mBtnConfirm.setOnClickListener(mBtnConfirmOnClickListener);
mBtnCancel.setVisibility(View.VISIBLE);
mBtnConfirm.setVisibility(View.VISIBLE);
mFooter.setVisibility(View.VISIBLE);
if (infoText != null)
mTextInfo.setText(infoText);
else
mTextInfo.setText(R.string.alp_msg_draw_an_unlock_pattern);
/*
* BUTTON OK
*/
if (mBtnOkCmd == null)
mBtnOkCmd = ButtonOkCommand.CONTINUE;
switch (mBtnOkCmd) {
case CONTINUE:
mBtnConfirm.setText(R.string.alp_cmd_continue);
break;
case DONE:
mBtnConfirm.setText(R.string.alp_cmd_confirm);
break;
default:
/*
* Do nothing.
*/
break;
}
if (btnOkEnabled != null)
mBtnConfirm.setEnabled(btnOkEnabled);
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
if (TextUtils.isEmpty(infoText))
mTextInfo.setText(R.string.alp_msg_draw_pattern_to_unlock);
else
mTextInfo.setText(infoText);
if (getIntent().hasExtra(EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN)) {
mBtnConfirm.setOnClickListener(mBtnConfirmOnClickListener);
mBtnConfirm.setText(R.string.alp_cmd_forgot_pattern);
mBtnConfirm.setEnabled(true);
mFooter.setVisibility(View.VISIBLE);
}
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_redraw_pattern_to_confirm);
final ArrayList<Cell> pattern;
if (getIntent().hasExtra(EXTRA_PATTERN))
pattern = getIntent()
.getParcelableArrayListExtra(EXTRA_PATTERN);
else
getIntent().putParcelableArrayListExtra(
EXTRA_PATTERN,
pattern = LockPatternUtils
.genCaptchaPattern(DisplayPrefs
.getCaptchaWiredDots(this)));
mLockPatternView.setPattern(DisplayMode.Animate, pattern);
}// ACTION_VERIFY_CAPTCHA
}// initContentView()
* Encodes {#code pattern} to a string.
private char[] encodePattern(List<Cell> pattern) {
* Compares {#code pattern} to the given pattern (
private void doComparePattern(List<Cell> pattern) {
Toast.makeText(getApplicationContext(), "Inside doComparePattern", Toast.LENGTH_LONG).show();
if (pattern == null)
return;
boolean okey = false;
if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
char[] currentPattern = getIntent()
.getCharArrayExtra(EXTRA_PATTERN);
if (currentPattern == null)
currentPattern = SecurityPrefs.getPattern(this);
okey = Arrays.equals(encodePattern(pattern), currentPattern);
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
final List<Cell> captchaPattern = getIntent()
.getParcelableArrayListExtra(EXTRA_PATTERN);
okey = captchaPattern.size() == pattern.size();
if (okey) {
for (int i = 0; i < captchaPattern.size(); i++) {
if (!captchaPattern.get(i).equals(pattern.get(i))) {
okey = false;
break;
}
}// for
}
}// ACTION_VERIFY_CAPTCHA
if (okey)
finishWithResultOk(null);
else {
mRetryCount++;
mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount);
if (mRetryCount >= mMaxRetry)
finishWithNegativeResult(RESULT_FAILED);
else {
mLockPatternView.setDisplayMode(DisplayMode.Wrong);
mTextInfo.setText(R.string.alp_msg_try_again);
mLockPatternView.postDelayed(mLockPatternViewReloader,
DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW);
}
}
}// doComparePattern()
/**
* Checks and creates the pattern.
*
* #param pattern
* the current pattern of lock pattern view.
*/
private void doCheckAndCreatePattern(List<Cell> pattern) {
Toast.makeText(getApplicationContext(), "Inside doCheckAndCreatePattern", Toast.LENGTH_LONG).show();
if (pattern.size() < mMinWiredDots) {
mLockPatternView.setDisplayMode(DisplayMode.Wrong);
mTextInfo.setText(getResources().getQuantityString(
R.plurals.alp_pmsg_connect_x_dots, mMinWiredDots,
mMinWiredDots));
mLockPatternView.postDelayed(mLockPatternViewReloader,
DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW);
return;
}
if (getIntent().hasExtra(EXTRA_PATTERN)) {
if (Arrays.equals(getIntent().getCharArrayExtra(EXTRA_PATTERN),
encodePattern(pattern))) {
mTextInfo.setText(R.string.alp_msg_your_new_unlock_pattern);
mBtnConfirm.setEnabled(true);
} else {
mTextInfo.setText(R.string.alp_msg_redraw_pattern_to_confirm);
mBtnConfirm.setEnabled(false);
mLockPatternView.setDisplayMode(DisplayMode.Wrong);
mLockPatternView.postDelayed(mLockPatternViewReloader,
DELAY_TIME_TO_RELOAD_LOCK_PATTERN_VIEW);
}
} else {
getIntent().putExtra(EXTRA_PATTERN, encodePattern(pattern));
mTextInfo.setText(R.string.alp_msg_pattern_recorded);
mBtnConfirm.setEnabled(true);
}
}// doCheckAndCreatePattern()
* Finishes activity with {#link Activity#RESULT_OK}.
private void finishWithResultOk(char[] pattern) {
Toast.makeText(getApplicationContext(), "Inside finishWithResultOk", Toast.LENGTH_LONG).show();
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction()))
mIntentResult.putExtra(EXTRA_PATTERN, pattern);
else {
/*
* If the user was "logging in", minimum try count can not be zero.
*/
mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount + 1);
}
setResult(RESULT_OK, mIntentResult);
/*
* ResultReceiver
*/
ResultReceiver receiver = getIntent().getParcelableExtra(
EXTRA_RESULT_RECEIVER);
if (receiver != null) {
Bundle bundle = new Bundle();
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction()))
bundle.putCharArray(EXTRA_PATTERN, pattern);
else {
/*
* If the user was "logging in", minimum try count can not be
* zero.
*/
bundle.putInt(EXTRA_RETRY_COUNT, mRetryCount + 1);
}
receiver.send(RESULT_OK, bundle);
}
/*
* PendingIntent
*/
PendingIntent pi = getIntent().getParcelableExtra(
EXTRA_PENDING_INTENT_OK);
if (pi != null) {
try {
pi.send(this, RESULT_OK, mIntentResult);
} catch (Throwable t) {
if (BuildConfig.DEBUG) {
Log.e(CLASSNAME, "Error sending PendingIntent: " + pi);
Log.e(CLASSNAME, ">>> " + t);
t.printStackTrace();
}
}
}
finish();
}// finishWithResultOk()
/**
* Finishes the activity with negative result (
* {#link Activity#RESULT_CANCELED}, {#link #RESULT_FAILED} or
* {#link #RESULT_FORGOT_PATTERN}).
*/
private void finishWithNegativeResult(int resultCode) {
if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction()))
mIntentResult.putExtra(EXTRA_RETRY_COUNT, mRetryCount);
setResult(resultCode, mIntentResult);
/*
* ResultReceiver
*/
ResultReceiver receiver = getIntent().getParcelableExtra(
EXTRA_RESULT_RECEIVER);
if (receiver != null) {
Bundle resultBundle = null;
if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
resultBundle = new Bundle();
resultBundle.putInt(EXTRA_RETRY_COUNT, mRetryCount);
}
receiver.send(resultCode, resultBundle);
}
/*
* PendingIntent
*/
PendingIntent pi = getIntent().getParcelableExtra(
EXTRA_PENDING_INTENT_CANCELLED);
if (pi != null) {
try {
pi.send(this, resultCode, mIntentResult);
} catch (Throwable t) {
if (BuildConfig.DEBUG) {
Log.e(CLASSNAME, "Error sending PendingIntent: " + pi);
Log.e(CLASSNAME, ">>> " + t);
t.printStackTrace();
}
}
}
finish();
}// finishWithNegativeResult()
/*
* LISTENERS
*/
private final LockPatternView.OnPatternListener mLockPatternViewListener = new LockPatternView.OnPatternListener() {
#Override
public void onPatternStart() {
Toast.makeText(getApplicationContext(), "Inside onPatternStart", Toast.LENGTH_LONG).show();
mLockPatternView.removeCallbacks(mLockPatternViewReloader);
mLockPatternView.setDisplayMode(DisplayMode.Correct);
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
Toast.makeText(getApplicationContext(), "Inside action create pattern", Toast.LENGTH_LONG).show();
mTextInfo.setText(R.string.alp_msg_release_finger_when_done);
mBtnConfirm.setEnabled(true);
if (mBtnOkCmd == ButtonOkCommand.CONTINUE)
getIntent().removeExtra(EXTRA_PATTERN);
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_draw_pattern_to_unlock);
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_redraw_pattern_to_confirm);
}// ACTION_VERIFY_CAPTCHA
}// onPatternStart()
#Override
public void onPatternDetected(List<Cell> pattern) {
Toast.makeText(getApplicationContext(), "Inside onPatternDetected", Toast.LENGTH_LONG).show();
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
doCheckAndCreatePattern(pattern);
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
doComparePattern(pattern);
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
if (!DisplayMode.Animate.equals(mLockPatternView
.getDisplayMode()))
doComparePattern(pattern);
}// ACTION_VERIFY_CAPTCHA
}// onPatternDetected()
#Override
public void onPatternCleared() {
Toast.makeText(getApplicationContext(), "Inside onPatternCleared", Toast.LENGTH_LONG).show();
mLockPatternView.removeCallbacks(mLockPatternViewReloader);
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
mLockPatternView.setDisplayMode(DisplayMode.Correct);
mBtnConfirm.setEnabled(true);
if (mBtnOkCmd == ButtonOkCommand.CONTINUE) {
getIntent().removeExtra(EXTRA_PATTERN);
mTextInfo.setText(R.string.alp_msg_draw_an_unlock_pattern);
} else
mTextInfo
.setText(R.string.alp_msg_redraw_pattern_to_confirm);
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
mLockPatternView.setDisplayMode(DisplayMode.Correct);
mTextInfo.setText(R.string.alp_msg_draw_pattern_to_unlock);
}// ACTION_COMPARE_PATTERN
else if (ACTION_VERIFY_CAPTCHA.equals(getIntent().getAction())) {
mTextInfo.setText(R.string.alp_msg_redraw_pattern_to_confirm);
List<Cell> pattern = getIntent().getParcelableArrayListExtra(
EXTRA_PATTERN);
mLockPatternView.setPattern(DisplayMode.Animate, pattern);
}// ACTION_VERIFY_CAPTCHA
}// onPatternCleared()
#Override
public void onPatternCellAdded(List<Cell> pattern) {
// TODO Auto-generated method stub
}// onPatternCellAdded()
};// mLockPatternViewListener
private final View.OnClickListener mBtnCancelOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
finishWithNegativeResult(RESULT_CANCELED);
}// onClick()
};// mBtnCancelOnClickListener
private final View.OnClickListener mBtnConfirmOnClickListener = new View.OnClickListener() {
#Override
public void onClick(View v) {
if (ACTION_CREATE_PATTERN.equals(getIntent().getAction())) {
if (mBtnOkCmd == ButtonOkCommand.CONTINUE) {
mBtnOkCmd = ButtonOkCommand.DONE;
mLockPatternView.clearPattern();
mTextInfo
.setText(R.string.alp_msg_redraw_pattern_to_confirm);
mBtnConfirm.setText(R.string.alp_cmd_confirm);
mBtnConfirm.setEnabled(false);
} else {
final char[] pattern = getIntent().getCharArrayExtra(
EXTRA_PATTERN);
if (mAutoSave)
SecurityPrefs.setPattern(MainActivity.this,
pattern);
finishWithResultOk(pattern);
}
}// ACTION_CREATE_PATTERN
else if (ACTION_COMPARE_PATTERN.equals(getIntent().getAction())) {
/*
* We don't need to verify the extra. First, this button is only
* visible if there is this extra in the intent. Second, it is
* the responsibility of the caller to make sure the extra is an
* Intent of Activity.
*/
startActivity((Intent) getIntent().getParcelableExtra(
EXTRA_INTENT_ACTIVITY_FORGOT_PATTERN));
finishWithNegativeResult(RESULT_FORGOT_PATTERN);
}// ACTION_COMPARE_PATTERN
}// onClick()
};// mBtnConfirmOnClickListener
/**
* This reloads the {#link #mLockPatternView} after a wrong pattern.
*/
private final Runnable mLockPatternViewReloader = new Runnable() {
#Override
public void run() {
mLockPatternView.clearPattern();
mLockPatternViewListener.onPatternCleared();
}// run()
};// mLockPatternViewReloader
}
Your bug is in your initialization in initContentView(). You are setting btnOkEnabled before you've loaded the button into mBtnConfirm.
Move your findViewById() calls to the top of that method and you should be all set.

Categories

Resources