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 ?
Related
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
My app consist Image Capture Face Recognition what i need to implement is converting the byte Array image into bitmap , and pass the bitmap to next Activity, The next Activity will receive the bitmap and show it in an image-view , than convert the bitmap into base 64.
I Don't know how to implement above task into my existing codes.
So when image is captured it shows, once click to save button pass the image to next activity and again convert the bitmap into base64.
FaceTrackerAcivity.java
public final class FaceTrackerActivity extends AppCompatActivity implements View.OnClickListener {
private static final String TAG = "FaceTracker";
private CameraSource mCameraSource = null;
private CameraSourcePreview mPreview;
private GraphicOverlay mGraphicOverlay;
private ImageView btnCapture;
private ImageView btnChangeCamera;
private ImageView btnCancel;
private ImageView btnSave;
private FrameLayout frmResult;
private ImageView imgPicture;
Bitmap bmp;
private static final int RC_HANDLE_GMS = 9001;
// permission request codes need to be < 256
private static final int RC_HANDLE_CAMERA_PERM = 2;
private static final int RC_HANDLE_WRITE_EXTERNAL_STORAGE_PERM = 3;
private int cameraId = CameraSource.CAMERA_FACING_BACK;
Intent x;
//==============================================================================================
// Activity Methods
//==============================================================================================
/**
* Initializes the UI and initiates the creation of a face detector.
*/
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mPreview = (CameraSourcePreview) findViewById(R.id.preview);
mGraphicOverlay = (GraphicOverlay) findViewById(R.id.faceOverlay);
btnCapture = (ImageView) findViewById(R.id.btn_capture);
btnChangeCamera = (ImageView) findViewById(R.id.btn_change_camera);
btnCancel = (ImageView) findViewById(R.id.btn_cancel);
btnSave = (ImageView) findViewById(R.id.btn_save);
frmResult = (FrameLayout) findViewById(R.id.frm_capture_result);
imgPicture = (ImageView) findViewById(R.id.img_capture_result);
boolean hasPermissionCamera = (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED);
if (!hasPermissionCamera) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA}, RC_HANDLE_CAMERA_PERM);
} else {
boolean hasPermissionWriteStorage = (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED);
if (!hasPermissionWriteStorage) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, RC_HANDLE_WRITE_EXTERNAL_STORAGE_PERM);
} else {
createCameraSource(cameraId);
}
}
btnCapture.setOnClickListener(this);
btnChangeCamera.setOnClickListener(this);
}
private void createCameraSource(int cameraId) {
Context context = getApplicationContext();
FaceDetector detector = new FaceDetector.Builder(context)
.setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
.build();
detector.setProcessor(
new MultiProcessor.Builder<>(new GraphicFaceTrackerFactory())
.build());
if (!detector.isOperational()) {
Log.w(TAG, "Face detector dependencies are not yet available.");
}
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mCameraSource = new CameraSource.Builder(context, detector)
.setRequestedPreviewSize(metrics.heightPixels, metrics.widthPixels)
.setFacing(cameraId)
.setAutoFocusEnabled(true)
.setRequestedFps(30.0f)
.build();
}
#Override
protected void onResume() {
super.onResume();
startCameraSource();
}
#Override
protected void onPause() {
super.onPause();
mPreview.stop();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mCameraSource != null) {
mCameraSource.release();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case RC_HANDLE_CAMERA_PERM: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
finish();
startActivity(getIntent());
}
break;
}
case RC_HANDLE_WRITE_EXTERNAL_STORAGE_PERM: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
finish();
startActivity(getIntent());
}
break;
}
}
}
private void startCameraSource() {
// check that the device has play services available.
int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
getApplicationContext());
if (code != ConnectionResult.SUCCESS) {
Dialog dlg = GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
dlg.show();
}
if (mCameraSource != null) {
try {
mPreview.start(mCameraSource, mGraphicOverlay);
} catch (IOException e) {
Log.e(TAG, "Unable to start camera source.", e);
mCameraSource.release();
mCameraSource = null;
}
}
}
#Override
public void onClick(View v) {
int id = v.getId();
if (id == R.id.btn_capture) {
Toast.makeText(this, "capture", Toast.LENGTH_SHORT).show();
mCameraSource.takePicture(null, new CameraSource.PictureCallback() {
#Override
public void onPictureTaken(final byte[] bytes) {
int orientation = Exif.getOrientation(bytes);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bmp = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, options);
switch (orientation) {
case 90:
bmp = Utils.rotateImage(bmp, 90);
break;
case 180:
bmp = Utils.rotateImage(bmp, 180);
break;
case 270:
bmp = Utils.rotateImage(bmp, 270);
break;
}
if (cameraId == CameraSource.CAMERA_FACING_FRONT) {
bmp = Utils.flip(bmp, Constants.FLIP_HORIZONTAL);
}
if (bmp != null) {
frmResult.setVisibility(View.VISIBLE);
imgPicture.setImageBitmap(bmp);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
frmResult.setVisibility(View.GONE);
}
});
btnSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SavePhotoTask savePhotoTask = new SavePhotoTask();
savePhotoTask.execute(bytes);
}
});
}
}
});
} else if (id == R.id.btn_change_camera) {
mCameraSource.release();
mCameraSource = null;
cameraId = cameraId == CameraSource.CAMERA_FACING_BACK ? CameraSource.CAMERA_FACING_FRONT : CameraSource.CAMERA_FACING_BACK;
createCameraSource(cameraId);
startCameraSource();
}
}
private class GraphicFaceTrackerFactory implements MultiProcessor.Factory<Face> {
#Override
public Tracker<Face> create(Face face) {
return new GraphicFaceTracker(mGraphicOverlay);
}
}
private class GraphicFaceTracker extends Tracker<Face> {
private GraphicOverlay mOverlay;
private FaceGraphic mFaceGraphic;
GraphicFaceTracker(GraphicOverlay overlay) {
mOverlay = overlay;
mFaceGraphic = new FaceGraphic(overlay);
}
#Override
public void onNewItem(int faceId, Face item) {
mFaceGraphic.setId(faceId);
}
#Override
public void onUpdate(FaceDetector.Detections<Face> detectionResults, Face face) {
mOverlay.add(mFaceGraphic);
mFaceGraphic.updateFace(face);
}
#Override
public void onMissing(FaceDetector.Detections<Face> detectionResults) {
mOverlay.remove(mFaceGraphic);
}
#Override
public void onDone() {
mOverlay.remove(mFaceGraphic);
}
}
class SavePhotoTask extends AsyncTask<byte[], String, String> {
#Override
protected String doInBackground(byte[]... data) {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "TRACKER_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
try {
File photo = File.createTempFile(imageFileName, ".jpg", storageDir);
FileOutputStream fos = new FileOutputStream(photo.getPath());
fos.write(data[0]);
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}}
NEXT.java
public class NEXT extends AppCompatActivity {
ImageView y;
Intent intent;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.next);
y = (ImageView) findViewById(R.id.myimage);
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("key");
y.setImageBitmap(bitmap);
}}
Putin large data (>1Mo) can produce android.os.TransactionTooLargeException, ref :
The Binder transaction buffer has a limited fixed size, currently
1Mb, which is shared by all transactions in progress for the
process. Consequently this exception can be thrown when there are many
transactions in progress even when most of the individual transactions
are of moderate size.
The best way is to create a class and put your image into it, you can then access to it from any activity
public class Demo extends LayoutGameActivity implements SampleApplicationControl,SampleAppMenuInterface {
private static final int CAMERA_WIDTH = 720;
private static final int CAMERA_HEIGHT = 480;
private static final float AUTOWRAP_WIDTH = 720 - 50 - 50;
private EditText mEditText;
private Font mFont;
private Text mText;
private Line mRight;
private Line mLeft;
private static final String LOGTAG = "ImageTargets";
SampleApplicationSession vuforiaAppSession;
private DataSet mCurrentDataset;
private int mCurrentDatasetSelectionIndex = 0;
private int mStartDatasetsIndex = 0;
private int mDatasetsNumber = 0;
private ArrayList<String> mDatasetStrings = new ArrayList<String>();
// Our OpenGL view:
private SampleApplicationGLView mGlView;
// Our renderer:
private ImageTargetRenderer mRenderer;
private GestureDetector mGestureDetector;
// The textures we will use for rendering:
private Vector<Texture> mTextures;
private boolean mSwitchDatasetAsap = false;
private boolean mFlash = false;
private boolean mContAutofocus = false;
private boolean mExtendedTracking = false;
private View mFlashOptionView;
private RelativeLayout mUILayout;
private SampleAppMenu mSampleAppMenu;
LoadingDialogHandler loadingDialogHandler = new LoadingDialogHandler(this);
// Alert Dialog used to display SDK errors
private AlertDialog mErrorDialog;
boolean mIsDroidDevice = false;
// Called when the activity first starts or the user navigates back to an
// activity.
// Process Single Tap event to trigger autofocus
private class GestureListener extends
GestureDetector.SimpleOnGestureListener
{
// Used to set autofocus one second after a manual focus is triggered
private final Handler autofocusHandler = new Handler();
#Override
public boolean onDown(MotionEvent e)
{
return true;
}
#Override
public boolean onSingleTapUp(MotionEvent e)
{
// Generates a Handler to trigger autofocus
// after 1 second
autofocusHandler.postDelayed(new Runnable()
{
public void run()
{
boolean result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_TRIGGERAUTO);
if (!result)
Log.e("SingleTapUp", "Unable to trigger focus");
}
}, 1000L);
return true;
}
}
// We want to load specific textures from the APK, which we will later use
// for rendering.
private void loadTextures()
{
mTextures.add(Texture.loadTextureFromApk("TextureTeapotBrass.png",
getAssets()));
mTextures.add(Texture.loadTextureFromApk("TextureTeapotBlue.png",
getAssets()));
mTextures.add(Texture.loadTextureFromApk("TextureTeapotRed.png",
getAssets()));
mTextures.add(Texture.loadTextureFromApk("ImageTargets/Buildings.jpeg",
getAssets()));
}
// Called when the activity will start interacting with the user.
#Override
protected void onResume()
{
Log.d(LOGTAG, "onResume");
super.onResume();
vuforiaAppSession = new SampleApplicationSession(this);
startLoadingAnimation();
mDatasetStrings.add("StonesAndChips.xml");
mDatasetStrings.add("Tarmac.xml");
// mDatasetStrings.add("my_first.xml");
vuforiaAppSession
.initAR(this, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
mGestureDetector = new GestureDetector(this, new GestureListener());
// Load any sample specific textures:
mTextures = new Vector<Texture>();
loadTextures();
mIsDroidDevice = android.os.Build.MODEL.toLowerCase().startsWith(
"droid");
// This is needed for some Droid devices to force portrait
if (mIsDroidDevice)
{
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
try
{
vuforiaAppSession.resumeAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
// Resume the GL view:
if (mGlView != null)
{
mGlView.setVisibility(View.VISIBLE);
mGlView.onResume();
}
}
// Callback for configuration changes the activity handles itself
#Override
public void onConfigurationChanged(Configuration config)
{
Log.d(LOGTAG, "onConfigurationChanged");
super.onConfigurationChanged(config);
vuforiaAppSession.onConfigurationChanged();
}
// Called when the system is about to start resuming a previous activity.
#Override
protected void onPause()
{
Log.d(LOGTAG, "onPause");
super.onPause();
if (mGlView != null)
{
mGlView.setVisibility(View.INVISIBLE);
mGlView.onPause();
}
// Turn off the flash
if (mFlashOptionView != null && mFlash)
{
// OnCheckedChangeListener is called upon changing the checked state
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
((Switch) mFlashOptionView).setChecked(false);
} else
{
((CheckBox) mFlashOptionView).setChecked(false);
}
}
try
{
vuforiaAppSession.pauseAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
}
// The final call you receive before your activity is destroyed.
#Override
protected void onDestroy()
{
Log.d(LOGTAG, "onDestroy");
super.onDestroy();
try
{
vuforiaAppSession.stopAR();
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
// Unload texture:
mTextures.clear();
mTextures = null;
System.gc();
}
// Initializes AR application components.
private void initApplicationAR()
{
// Create OpenGL ES view:
int depthSize = 16;
int stencilSize = 0;
boolean translucent = Vuforia.requiresAlpha();
mGlView = new SampleApplicationGLView(this);
mGlView.init(translucent, depthSize, stencilSize);
mRenderer = new ImageTargetRenderer(this, vuforiaAppSession);
mRenderer.setTextures(mTextures);
mGlView.setRenderer(mRenderer);
}
private void startLoadingAnimation()
{
LayoutInflater inflater = LayoutInflater.from(this);
mUILayout = (RelativeLayout) inflater.inflate(R.layout.camera_overlay,
null, false);
mUILayout.setVisibility(View.VISIBLE);
mUILayout.setBackgroundColor(Color.BLACK);
// Gets a reference to the loading dialog
loadingDialogHandler.mLoadingDialogContainer = mUILayout
.findViewById(R.id.loading_indicator);
// Shows the loading indicator at start
loadingDialogHandler
.sendEmptyMessage(LoadingDialogHandler.SHOW_LOADING_DIALOG);
// Adds the inflated layout to the view
addContentView(mUILayout, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
}
// Methods to load and destroy tracking data.
#Override
public boolean doLoadTrackersData()
{
TrackerManager tManager = TrackerManager.getInstance();
ObjectTracker objectTracker = (ObjectTracker) tManager
.getTracker(ObjectTracker.getClassType());
if (objectTracker == null)
return false;
if (mCurrentDataset == null)
mCurrentDataset = objectTracker.createDataSet();
if (mCurrentDataset == null)
return false;
if (!mCurrentDataset.load(
mDatasetStrings.get(mCurrentDatasetSelectionIndex),
STORAGE_TYPE.STORAGE_APPRESOURCE))
return false;
if (!objectTracker.activateDataSet(mCurrentDataset))
return false;
int numTrackables = mCurrentDataset.getNumTrackables();
for (int count = 0; count < numTrackables; count++)
{
Trackable trackable = mCurrentDataset.getTrackable(count);
if(isExtendedTrackingActive())
{
trackable.startExtendedTracking();
}
String name = "Current Dataset : " + trackable.getName();
trackable.setUserData(name);
Log.d(LOGTAG, "UserData:Set the following user data "
+ (String) trackable.getUserData());
}
return true;
}
#Override
public boolean doUnloadTrackersData()
{
// Indicate if the trackers were unloaded correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
ObjectTracker objectTracker = (ObjectTracker) tManager
.getTracker(ObjectTracker.getClassType());
if (objectTracker == null)
return false;
if (mCurrentDataset != null && mCurrentDataset.isActive())
{
if (objectTracker.getActiveDataSet().equals(mCurrentDataset)
&& !objectTracker.deactivateDataSet(mCurrentDataset))
{
result = false;
} else if (!objectTracker.destroyDataSet(mCurrentDataset))
{
result = false;
}
mCurrentDataset = null;
}
return result;
}
#Override
public void onInitARDone(SampleApplicationException exception)
{
if (exception == null)
{
initApplicationAR();
mRenderer.mIsActive = true;
// Now add the GL surface view. It is important
// that the OpenGL ES surface view gets added
// BEFORE the camera is started and video
// background is configured.
addContentView(mGlView, new LayoutParams(LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT));
// Sets the UILayout to be drawn in front of the camera
mUILayout.bringToFront();
// Sets the layout background to transparent
mUILayout.setBackgroundColor(Color.TRANSPARENT);
try
{
vuforiaAppSession.startAR(CameraDevice.CAMERA.CAMERA_DEFAULT);
} catch (SampleApplicationException e)
{
Log.e(LOGTAG, e.getString());
}
boolean result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_CONTINUOUSAUTO);
if (result)
mContAutofocus = true;
else
Log.e(LOGTAG, "Unable to enable continuous autofocus");
mSampleAppMenu = new SampleAppMenu(this, this, "Image Targets",
mGlView, mUILayout, null);
setSampleAppMenuSettings();
} else
{
Log.e(LOGTAG, exception.getString());
showInitializationErrorMessage(exception.getString());
}
}
// Shows initialization error messages as System dialogs
public void showInitializationErrorMessage(String message)
{
final String errorMessage = message;
runOnUiThread(new Runnable()
{
public void run()
{
if (mErrorDialog != null)
{
mErrorDialog.dismiss();
}
// Generates an Alert Dialog to show the error message
AlertDialog.Builder builder = new AlertDialog.Builder(
Demo.this);
builder
.setMessage(errorMessage)
.setTitle(getString(R.string.INIT_ERROR))
.setCancelable(false)
.setIcon(0)
.setPositiveButton(getString(R.string.button_OK),
new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int id)
{
finish();
}
});
mErrorDialog = builder.create();
mErrorDialog.show();
}
});
}
#Override
public void onQCARUpdate(State state)
{
if (mSwitchDatasetAsap)
{
mSwitchDatasetAsap = false;
TrackerManager tm = TrackerManager.getInstance();
ObjectTracker ot = (ObjectTracker) tm.getTracker(ObjectTracker
.getClassType());
if (ot == null || mCurrentDataset == null
|| ot.getActiveDataSet() == null)
{
Log.d(LOGTAG, "Failed to swap datasets");
return;
}
doUnloadTrackersData();
doLoadTrackersData();
}
}
#Override
public boolean doInitTrackers()
{
// Indicate if the trackers were initialized correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
Tracker tracker;
// Trying to initialize the image tracker
tracker = tManager.initTracker(ObjectTracker.getClassType());
if (tracker == null)
{
Log.e(
LOGTAG,
"Tracker not initialized. Tracker already initialized or the camera is already started");
result = false;
} else
{
Log.i(LOGTAG, "Tracker successfully initialized");
}
return result;
}
#Override
public boolean doStartTrackers()
{
// Indicate if the trackers were started correctly
boolean result = true;
Tracker objectTracker = TrackerManager.getInstance().getTracker(
ObjectTracker.getClassType());
if (objectTracker != null)
objectTracker.start();
return result;
}
#Override
public boolean doStopTrackers()
{
// Indicate if the trackers were stopped correctly
boolean result = true;
Tracker objectTracker = TrackerManager.getInstance().getTracker(
ObjectTracker.getClassType());
if (objectTracker != null)
objectTracker.stop();
return result;
}
#Override
public boolean doDeinitTrackers()
{
// Indicate if the trackers were deinitialized correctly
boolean result = true;
TrackerManager tManager = TrackerManager.getInstance();
tManager.deinitTracker(ObjectTracker.getClassType());
return result;
}
#Override
public boolean onTouchEvent(MotionEvent event)
{
// Process the Gestures
if (mSampleAppMenu != null && mSampleAppMenu.processEvent(event))
return true;
return mGestureDetector.onTouchEvent(event);
}
boolean isExtendedTrackingActive()
{
return mExtendedTracking;
}
final public static int CMD_BACK = -1;
final public static int CMD_EXTENDED_TRACKING = 1;
final public static int CMD_AUTOFOCUS = 2;
final public static int CMD_FLASH = 3;
final public static int CMD_CAMERA_FRONT = 4;
final public static int CMD_CAMERA_REAR = 5;
final public static int CMD_DATASET_START_INDEX = 6;
// This method sets the menu's settings
private void setSampleAppMenuSettings()
{
SampleAppMenuGroup group;
group = mSampleAppMenu.addGroup("", false);
group.addTextItem(getString(R.string.menu_back), -1);
group = mSampleAppMenu.addGroup("", true);
group.addSelectionItem(getString(R.string.menu_extended_tracking),
CMD_EXTENDED_TRACKING, false);
group.addSelectionItem(getString(R.string.menu_contAutofocus),
CMD_AUTOFOCUS, mContAutofocus);
mFlashOptionView = group.addSelectionItem(
getString(R.string.menu_flash), CMD_FLASH, false);
CameraInfo ci = new CameraInfo();
boolean deviceHasFrontCamera = false;
boolean deviceHasBackCamera = false;
for (int i = 0; i < Camera.getNumberOfCameras(); i++)
{
Camera.getCameraInfo(i, ci);
if (ci.facing == CameraInfo.CAMERA_FACING_FRONT)
deviceHasFrontCamera = true;
else if (ci.facing == CameraInfo.CAMERA_FACING_BACK)
deviceHasBackCamera = true;
}
if (deviceHasBackCamera && deviceHasFrontCamera)
{
group = mSampleAppMenu.addGroup(getString(R.string.menu_camera),
true);
group.addRadioItem(getString(R.string.menu_camera_front),
CMD_CAMERA_FRONT, false);
group.addRadioItem(getString(R.string.menu_camera_back),
CMD_CAMERA_REAR, true);
}
group = mSampleAppMenu
.addGroup(getString(R.string.menu_datasets), true);
mStartDatasetsIndex = CMD_DATASET_START_INDEX;
mDatasetsNumber = mDatasetStrings.size();
group.addRadioItem("Stones & Chips", mStartDatasetsIndex, true);
group.addRadioItem("Tarmac", mStartDatasetsIndex + 1, false);
// group.addRadioItem("my_first", mStartDatasetsIndex + 2, false);
mSampleAppMenu.attachMenu();
}
#SuppressLint("NewApi") #Override
public boolean menuProcess(int command)
{
boolean result = true;
switch (command)
{
case CMD_BACK:
finish();
break;
case CMD_FLASH:
result = CameraDevice.getInstance().setFlashTorchMode(!mFlash);
if (result)
{
mFlash = !mFlash;
} else
{
showToast(getString(mFlash ? R.string.menu_flash_error_off
: R.string.menu_flash_error_on));
Log.e(LOGTAG,
getString(mFlash ? R.string.menu_flash_error_off
: R.string.menu_flash_error_on));
}
break;
case CMD_AUTOFOCUS:
if (mContAutofocus)
{
result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_NORMAL);
if (result)
{
mContAutofocus = false;
} else
{
showToast(getString(R.string.menu_contAutofocus_error_off));
Log.e(LOGTAG,
getString(R.string.menu_contAutofocus_error_off));
}
} else
{
result = CameraDevice.getInstance().setFocusMode(
CameraDevice.FOCUS_MODE.FOCUS_MODE_CONTINUOUSAUTO);
if (result)
{
mContAutofocus = true;
} else
{
showToast(getString(R.string.menu_contAutofocus_error_on));
Log.e(LOGTAG,
getString(R.string.menu_contAutofocus_error_on));
}
}
break;
case CMD_CAMERA_FRONT:
case CMD_CAMERA_REAR:
// Turn off the flash
if (mFlashOptionView != null && mFlash)
{
// OnCheckedChangeListener is called upon changing the checked state
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
{
((Switch) mFlashOptionView).setChecked(false);
} else
{
((CheckBox) mFlashOptionView).setChecked(false);
}
}
vuforiaAppSession.stopCamera();
try
{
vuforiaAppSession
.startAR(command == CMD_CAMERA_FRONT ? CameraDevice.CAMERA.CAMERA_FRONT
: CameraDevice.CAMERA.CAMERA_BACK);
} catch (SampleApplicationException e)
{
showToast(e.getString());
Log.e(LOGTAG, e.getString());
result = false;
}
doStartTrackers();
break;
case CMD_EXTENDED_TRACKING:
for (int tIdx = 0; tIdx < mCurrentDataset.getNumTrackables(); tIdx++)
{
Trackable trackable = mCurrentDataset.getTrackable(tIdx);
if (!mExtendedTracking)
{
if (!trackable.startExtendedTracking())
{
Log.e(LOGTAG,
"Failed to start extended tracking target");
result = false;
} else
{
Log.d(LOGTAG,
"Successfully started extended tracking target");
}
} else
{
if (!trackable.stopExtendedTracking())
{
Log.e(LOGTAG,
"Failed to stop extended tracking target");
result = false;
} else
{
Log.d(LOGTAG,
"Successfully started extended tracking target");
}
}
}
if (result)
mExtendedTracking = !mExtendedTracking;
break;
default:
if (command >= mStartDatasetsIndex
&& command < mStartDatasetsIndex + mDatasetsNumber)
{
mSwitchDatasetAsap = true;
mCurrentDatasetSelectionIndex = command
- mStartDatasetsIndex;
}
break;
}
return result;
}
private void showToast(String text)
{
Toast.makeText(this, text, Toast.LENGTH_SHORT).show();
}
#Override
protected void onCreate(Bundle pSavedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(pSavedInstanceState);
}
#Override
public EngineOptions onCreateEngineOptions() {
final org.andengine.engine.camera.Camera camera = new org.andengine.engine.camera.Camera(0, 0, Demo.CAMERA_WIDTH, Demo.CAMERA_HEIGHT);
return new EngineOptions(true, ScreenOrientation.PORTRAIT_FIXED, new RatioResolutionPolicy(Demo.CAMERA_WIDTH, Demo.CAMERA_HEIGHT), camera);
}
private void updateText() {
final String string = this.mEditText.getText().toString();
this.mText.setText(string);
final float left = (this.mText.getWidth() * 0.5f) - (this.mText.getLineWidthMaximum() * 0.5f);
this.mLeft.setPosition(left, 0, left, Demo.CAMERA_HEIGHT);
final float right = (this.mText.getWidth() * 0.5f) + (this.mText.getLineWidthMaximum() * 0.5f);
this.mRight.setPosition(right, 0, right, Demo.CAMERA_HEIGHT);
}
#Override
protected int getLayoutID() {
// TODO Auto-generated method stub
return R.layout.camera_overlay;
}
#Override
protected int getRenderSurfaceViewID() {
// TODO Auto-generated method stub
return R.id.textbreakexample_rendersurfaceview;
}
#Override
protected void onSetContentView() {
// TODO Auto-generated method stub
super.onSetContentView();
}
#Override
public void onCreateResources(
OnCreateResourcesCallback pOnCreateResourcesCallback)
throws IOException {
// TODO Auto-generated method stub
}
#Override
public void onCreateScene(OnCreateSceneCallback pOnCreateSceneCallback)
throws IOException {
// TODO Auto-generated method stub
}
#Override
public void onPopulateScene(Scene pScene,
OnPopulateSceneCallback pOnPopulateSceneCallback)
throws IOException {
// TODO Auto-generated method stub
}
}
I am using andEngine for Developing game and I also use vuforia for AR (Augmented Reality).But if i combine both the codes then i getting error as surfaceview null.
**and if it's not supported then what is the use for augmented reality object tracking in andenginre **
I need to get the orientation of a device. The screen orientation of the device is fixed as portrait.I have used the following code but it doesn't seem to work.I have made changes in the manifest file
due to which
getResources().getConfiguration().orientation;
always gives the same value
public final class CaptureActivity extends Activity implements SurfaceHolder.Callback,SensorEventListener{
private static final String TAG = CaptureActivity.class.getSimpleName();
private static final long DEFAULT_INTENT_RESULT_DURATION_MS = 1500L;
private static final long BULK_MODE_SCAN_DELAY_MS = 1000L;
private static final String PACKAGE_NAME = "com.google.zxing.client.android";
private static final String PRODUCT_SEARCH_URL_PREFIX = "http://www.google";
private static final String PRODUCT_SEARCH_URL_SUFFIX = "/m/products/scan";
private static final String[] ZXING_URLS = { "http://zxing.appspot.com/scan", "zxing://scan/" };
public static final int HISTORY_REQUEST_CODE = 0x0000bacc;
private static final Set<ResultMetadataType> DISPLAYABLE_METADATA_TYPES =
EnumSet.of(ResultMetadataType.ISSUE_NUMBER,
ResultMetadataType.SUGGESTED_PRICE,
ResultMetadataType.ERROR_CORRECTION_LEVEL,
ResultMetadataType.POSSIBLE_COUNTRY);
private CameraManager cameraManager;
private CaptureActivityHandler handler;
private Result savedResultToShow;
private ViewfinderView viewfinderView;
//private TextView statusView;
//private View resultView;
private Result lastResult;
private boolean hasSurface;
private boolean copyToClipboard;
private IntentSource source;
private String sourceUrl;
private ScanFromWebPageManager scanFromWebPageManager;
private Collection<BarcodeFormat> decodeFormats;
private Map<DecodeHintType,?> decodeHints;
private String characterSet;
private HistoryManager historyManager;
private InactivityTimer inactivityTimer;
private BeepManager beepManager;
private AmbientLightManager ambientLightManager;
private int orientation;
private SensorManager mSensorManager;
private Sensor mAccelerometer;
ViewfinderView getViewfinderView() {
return viewfinderView;
}
public Handler getHandler() {
return handler;
}
CameraManager getCameraManager() {
return cameraManager;
}
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
Window window = getWindow();
window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.capture);
hasSurface = false;
historyManager = new HistoryManager(this);
historyManager.trimHistory();
inactivityTimer = new InactivityTimer(this);
beepManager = new BeepManager(this);
ambientLightManager = new AmbientLightManager(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
//showHelpOnFirstLaunch();
}
#Override
protected void onResume() {
super.onResume();
// CameraManager must be initialized here, not in onCreate(). This is necessary because we don't
// want to open the camera driver and measure the screen size if we're going to show the help on
// first launch. That led to bugs where the scanning rectangle was the wrong size and partially
// off screen.
cameraManager = new CameraManager(getApplication());
viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_view);
viewfinderView.setCameraManager(cameraManager);
WindowManager manager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
int orientaionWidth = display.getWidth();
int orientaionHeight = display.getHeight();
int rotation=display.getRotation();
int orien=getResources().getConfiguration().orientation;
boolean orientation = false;
if(orientaionWidth>orientaionHeight){
orientation=true;
}
if(orien==1){
setLandscape(true);
}else{
setLandscape(false);
}
handler = null;
lastResult = null;
resetStatusView();
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
if (hasSurface) {
// The activity was paused but not stopped, so the surface still exists. Therefore
// surfaceCreated() won't be called, so init the camera here.
initCamera(surfaceHolder);
} else {
// Install the callback and wait for surfaceCreated() to init the camera.
surfaceHolder.addCallback(this);
surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
beepManager.updatePrefs();
ambientLightManager.start(cameraManager);
inactivityTimer.onResume();
Intent intent = getIntent();
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
copyToClipboard = prefs.getBoolean(PreferencesActivity.KEY_COPY_TO_CLIPBOARD, true)
&& (intent == null || intent.getBooleanExtra(Intents.Scan.SAVE_HISTORY, true));
source = IntentSource.NONE;
decodeFormats = null;
characterSet = null;
if (intent != null) {
String action = intent.getAction();
String dataString = intent.getDataString();
if (Intents.Scan.ACTION.equals(action)) {
// Scan the formats the intent requested, and return the result to the calling activity.
source = IntentSource.NATIVE_APP_INTENT;
decodeFormats = DecodeFormatManager.parseDecodeFormats(intent);
decodeHints = DecodeHintManager.parseDecodeHints(intent);
if (intent.hasExtra(Intents.Scan.WIDTH) && intent.hasExtra(Intents.Scan.HEIGHT)) {
int width = intent.getIntExtra(Intents.Scan.WIDTH, 0);
int height = intent.getIntExtra(Intents.Scan.HEIGHT, 0);
if (width > 0 && height > 0) {
cameraManager.setManualFramingRect(width, height);
}
}
String customPromptMessage = intent.getStringExtra(Intents.Scan.PROMPT_MESSAGE);
} else if (dataString != null &&
dataString.contains(PRODUCT_SEARCH_URL_PREFIX) &&
dataString.contains(PRODUCT_SEARCH_URL_SUFFIX)) {
// Scan only products and send the result to mobile Product Search.
source = IntentSource.PRODUCT_SEARCH_LINK;
sourceUrl = dataString;
decodeFormats = DecodeFormatManager.PRODUCT_FORMATS;
} else if (isZXingURL(dataString)) {
// Scan formats requested in query string (all formats if none specified).
// If a return URL is specified, send the results there. Otherwise, handle it ourselves.
source = IntentSource.ZXING_LINK;
sourceUrl = dataString;
Uri inputUri = Uri.parse(dataString);
scanFromWebPageManager = new ScanFromWebPageManager(inputUri);
decodeFormats = DecodeFormatManager.parseDecodeFormats(inputUri);
// Allow a sub-set of the hints to be specified by the caller.
decodeHints = DecodeHintManager.parseDecodeHints(inputUri);
}
characterSet = intent.getStringExtra(Intents.Scan.CHARACTER_SET);
}
}
#Override
protected void onPause() {
if (handler != null) {
handler.quitSynchronously();
handler = null;
}
inactivityTimer.onPause();
ambientLightManager.stop();
cameraManager.closeDriver();
if (!hasSurface) {
SurfaceView surfaceView = (SurfaceView) findViewById(R.id.preview_view);
SurfaceHolder surfaceHolder = surfaceView.getHolder();
surfaceHolder.removeCallback(this);
}
super.onPause();
}
#Override
protected void onDestroy() {
inactivityTimer.shutdown();
super.onDestroy();
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (resultCode == RESULT_OK) {
if (requestCode == HISTORY_REQUEST_CODE) {
int itemNumber = intent.getIntExtra(Intents.History.ITEM_NUMBER, -1);
if (itemNumber >= 0) {
HistoryItem historyItem = historyManager.buildHistoryItem(itemNumber);
decodeOrStoreSavedBitmap(null, historyItem.getResult());
}
}
}
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
if (holder == null) {
Log.e(TAG, "*** WARNING *** surfaceCreated() gave us a null surface!");
}
if (!hasSurface) {
hasSurface = true;
initCamera(holder);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
hasSurface = false;
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
private static void drawLine(Canvas canvas, Paint paint, ResultPoint a, ResultPoint b, float scaleFactor) {
if (a != null && b != null) {
canvas.drawLine(scaleFactor * a.getX(),
scaleFactor * a.getY(),
scaleFactor * b.getX(),
scaleFactor * b.getY(),
paint);
}
}
private void sendReplyMessage(int id, Object arg, long delayMS) {
Message message = Message.obtain(handler, id, arg);
if (delayMS > 0L) {
handler.sendMessageDelayed(message, delayMS);
} else {
handler.sendMessage(message);
}
}
/**
* We want the help screen to be shown automatically the first time a new version of the app is
* run. The easiest way to do this is to check android:versionCode from the manifest, and compare
* it to a value stored as a preference.
*/
private boolean showHelpOnFirstLaunch() {
/* try {
PackageInfo info = getPackageManager().getPackageInfo(PACKAGE_NAME, 0);
int currentVersion = info.versionCode;
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
int lastVersion = prefs.getInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, 0);
if (currentVersion > lastVersion) {
prefs.edit().putInt(PreferencesActivity.KEY_HELP_VERSION_SHOWN, currentVersion).commit();
Intent intent = new Intent(this, HelpActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
// Show the default page on a clean install, and the what's new page on an upgrade.
String page = lastVersion == 0 ? HelpActivity.DEFAULT_PAGE : HelpActivity.WHATS_NEW_PAGE;
intent.putExtra(HelpActivity.REQUESTED_PAGE_KEY, page);
startActivity(intent);
return true;
}
} catch (PackageManager.NameNotFoundException e) {
Log.w(TAG, e);
}*/
return false;
}
private void initCamera(SurfaceHolder surfaceHolder) {
if (surfaceHolder == null) {
throw new IllegalStateException("No SurfaceHolder provided");
}
if (cameraManager.isOpen()) {
Log.w(TAG, "initCamera() while already open -- late SurfaceView callback?");
return;
}
try {
cameraManager.openDriver(surfaceHolder);
// Creating the handler starts the preview, which can also throw a RuntimeException.
if (handler == null) {
handler = new CaptureActivityHandler(this, decodeFormats, decodeHints, characterSet, cameraManager);
}
decodeOrStoreSavedBitmap(null, null);
} catch (IOException ioe) {
Log.w(TAG, ioe);
displayFrameworkBugMessageAndExit();
} catch (RuntimeException e) {
// Barcode Scanner has seen crashes in the wild of this variety:
// java.?lang.?RuntimeException: Fail to connect to camera service
Log.w(TAG, "Unexpected error initializing camera", e);
displayFrameworkBugMessageAndExit();
}
}
private void displayFrameworkBugMessageAndExit() {
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle(getString(R.string.app_name));
builder.setMessage(getString(R.string.msg_camera_framework_bug));
builder.setPositiveButton(R.string.button_ok, new FinishListener(this));
builder.setOnCancelListener(new FinishListener(this));
builder.show();
}
public void restartPreviewAfterDelay(long delayMS) {
if (handler != null) {
handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
}
resetStatusView();
}
private void resetStatusView() {
viewfinderView.setVisibility(View.VISIBLE);
lastResult = null;
}
public void drawViewfinder() {
viewfinderView.drawViewfinder();
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
}
public void setLandscape(boolean orientation) {
viewfinderView.setLandscape(orientation);
}
#Override
public void onAccuracyChanged(Sensor arg0, int arg1) {
// TODO Auto-generated method stub
}
#Override
public void onSensorChanged(SensorEvent arg0) {
if (arg0.values[1]<6.5 && arg0.values[1]>-6.5) {
if (orientation!=1) {
Log.d("Sensor", "Landscape");
}
orientation=1;
} else {
if (orientation!=0) {
Log.d("Sensor", "Portrait");
}
orientation=0;
}
}
}
You can get the current orientation through
Activity.getResources().getConfiguration().orientation
or
getActivity().getResources().getConfiguration().orientation
this should work...
int orientation = getResources().getConfiguration().orientation;
if(orientation == Configuration.ORIENTATION_PORTRAIT) {
Log.i(TAG, "Portrait");
} else if(orientation == Configuration.ORIENTATION_LANDSCAPE) {
Log.i(TAG, "LandScape");
}
It should be
Display display = ((WindowManager) getSystemService(WINDOW_SERVICE)).getDefaultDisplay();
/* Now we can retrieve all display-related infos */
int width = display.getWidth();
int height = display.getHeight();
int rotation = display.getRotation();
Also, try with Activity().getResources().getConfiguration().orientation
By setting the orientation to be fixed to portrait in the manifest, you cant use getResources().getConfiguration().orientation as you already know.
Try using the accelerometer to determine the current rotation/tilt of the device as described here, How do I use the Android Accelerometer?
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.