I've been working on trying to create a maze solver method using an enum, but it has not been going so well.
This is the enum class:
Code:
public enum Direction {
N, NE, E, SE, S, SW, W, NW, HERE;
/**
* Returns the X/column change on the screen that is associated with
* this direction: -1 for W, 0 for N/S, and +1 for E.
*/
public int getColModifier() {
int mod;
switch (this) {
case NW:
case W:
case SW:
mod = -1;
break;
case NE:
case E:
case SE:
mod = +1;
break;
default:
mod = 0;
break;
}
return mod;
}
/**
* Returns the Y/row change on the screen that is associated with
* this direction: -1 for N, 0 for E/W, and +1 for south.
*/
public int getRowModifier() {
int mod;
switch (this) {
case N:
case NE:
case NW:
mod = -1;
break;
case S:
case SE:
case SW:
mod = +1;
break;
default:
mod = 0;
break;
}
return mod;
}
/** As {@link #getColModifier()} */
public int getXModifier() {
return this.getColModifier();
}
/** As {@link #getRowModifier()} */
public int getYModifier() {
return this.getRowModifier();
}
/**
* Returns the direction that is the opposite of this one.
* For example, <code>Direction.NE.reverse() == Direction.SW</code>.
* (The opposite of HERE is still HERE though.)
*/
public Direction reverse() {
if (this == HERE) {
return this;
}else {
int reversed = (this.ordinal() + 4) % 8;
Direction[] dirs = Direction.values();
return dirs[reversed];
}
}
}
and this is the method that I have been trying to write:
Code:
public java.util.ArrayList<Direction> getPathToExit(){
for (int x=0; x<map.length; x++){
for (int y=0; y<map[x].length; y++){
if (map[x][y]=='S'){
this.startRow=x;
this.startCol=y;
}
}
}
System.out.println("start "+startRow+", "+startCol);
return getPathToExit(this.startRow, this.startCol);
}
private java.util.ArrayList<Direction> getPathToExit(int row, int col){
Direction [] dirs = Direction.values();
ArrayList<Direction> path = new ArrayList<Direction>();
getPathToExit(row, col);
if (row < 0 || col < 0 || row > map.length || col > map[row].length){
return path;
}
else if (map[row][col] != ' '){
return path;
}
else if (map[row][col] == 'E'){
path.add(Direction.HERE);
return path;
}
else {
for (int x=0; x<dirs.length-1; x++){
map[row][col]='x';
int nextRow = row + dirs[x].getRowModifier();
int nextCol = col + dirs[x].getColModifier();
path = getPathToExit(nextRow, nextCol);
}
}
return path;
}
The problem I am having is that I keep getting stackoverflowerrors or the piece does not move (tested this by printing what row/col it is on), it would stay on the same tile then crash.
Thanks in advance.
Related
With the enhancement of D. Yeager for CM9, we can enable the Host Card Emulation functionality without any Secure Element.
by now, it can only change the SAK, ATQA, APP_DATA,... by modifying the CM9 source code. but when changing the uid, we'll get the lower-layer error: by logcating, it shows 'ANY_E_REG_ACCESS_DENIED' according to ETSI TS 102 622.
so, this operation must be blocked by the CLF's software stack, i guess - for i have no PN544/PN65N's manual.
but, i want to ask, is there any possible to change the rid to uid of host card emulation for nuxus s?
Reference:
Modifyed Code:
loc: android_external_libnfc-nxp.rar\src\phHciNfc_CE_A.c
Code:
NFCSTATUS
phHciNfc_CE_A_Initialise(
phHciNfc_sContext_t *psHciContext,
void *pHwRef
)
{
/*
1. Open Pipe,
2. Set all parameters
*/
NFCSTATUS status = NFCSTATUS_SUCCESS;
static uint8_t sak = 0x38; // HOST_CE_A_SAK_DEFAULT;
static uint8_t uid_info[] = { 0xE0U, 0x15U, 0x07U, 0x06U };
static uint8_t atqa_info[] = { NXP_CE_A_ATQA_LOW,
NXP_CE_A_ATQA_HIGH
};
if ((NULL == psHciContext) || (NULL == pHwRef))
{
status = PHNFCSTVAL(CID_NFC_HCI, NFCSTATUS_INVALID_PARAMETER);
}
else if(NULL == psHciContext->p_ce_a_info)
{
status = PHNFCSTVAL(CID_NFC_HCI, NFCSTATUS_FEATURE_NOT_SUPPORTED);
}
else
{
phHciNfc_CE_A_Info_t *ps_ce_a_info = ((phHciNfc_CE_A_Info_t *)
psHciContext->p_ce_a_info );
phHciNfc_Pipe_Info_t *ps_pipe_info = NULL;
ps_pipe_info = ps_ce_a_info->p_pipe_info;
if(NULL == ps_pipe_info )
{
status = PHNFCSTVAL(CID_NFC_HCI,
NFCSTATUS_INVALID_HCI_INFORMATION);
}
else
{
switch(ps_ce_a_info->current_seq)
{
case HOST_CE_A_PIPE_OPEN:
{
status = phHciNfc_Open_Pipe( psHciContext,
pHwRef, ps_pipe_info );
if(status == NFCSTATUS_SUCCESS)
{
//{----------------------------------- new for uid
ps_ce_a_info->next_seq = HOST_CE_A_UID_SEQ; // HOST_CE_A_SAK_SEQ;
//}----------------------------------- new for uid
status = NFCSTATUS_PENDING;
}
break;
}
//{----------------------------------- new for uid
case HOST_CE_A_UID_SEQ:
{
/* HOST Card Emulation A UID Configuration */
ps_pipe_info->reg_index = HOST_CE_A_UID_REG_INDEX;
/* Configure the UID of Host Card Emulation A */
ps_pipe_info->param_info = (void*)uid_info ;
ps_pipe_info->param_length = sizeof(uid_info) ;
status = phHciNfc_Send_Generic_Cmd(psHciContext,pHwRef,
ps_pipe_info->pipe.pipe_id,
(uint8_t)ANY_SET_PARAMETER);
if(status == NFCSTATUS_PENDING)
{
ps_ce_a_info->next_seq = HOST_CE_A_SAK_SEQ;
}
break;
}
//}----------------------------------- new for uid
case HOST_CE_A_SAK_SEQ:
{
/* HOST Card Emulation A SAK Configuration */
ps_pipe_info->reg_index = HOST_CE_A_SAK_INDEX;
/* Configure the SAK of Host Card Emulation A */
sak = (uint8_t)HOST_CE_A_SAK_DEFAULT;
ps_pipe_info->param_info =(void*)&sak ;
ps_pipe_info->param_length = sizeof(sak) ;
status = phHciNfc_Send_Generic_Cmd(psHciContext,pHwRef,
ps_pipe_info->pipe.pipe_id,
(uint8_t)ANY_SET_PARAMETER);
if(status == NFCSTATUS_PENDING)
{
ps_ce_a_info->next_seq = HOST_CE_A_ATQA_SEQ;
}
break;
}
case HOST_CE_A_ATQA_SEQ:
{
/* HOST Card Emulation A ATQA Configuration */
ps_pipe_info->reg_index = HOST_CE_A_ATQA_INDEX;
/* Configure the ATQA of Host Card Emulation A */
ps_pipe_info->param_info = (void*)atqa_info ;
ps_pipe_info->param_length = sizeof(atqa_info) ;
status = phHciNfc_Send_Generic_Cmd(psHciContext,pHwRef,
ps_pipe_info->pipe.pipe_id,
(uint8_t)ANY_SET_PARAMETER);
if(status == NFCSTATUS_PENDING)
{
ps_ce_a_info->next_seq = HOST_CE_A_ENABLE_SEQ;
}
break;
}
case HOST_CE_A_ENABLE_SEQ:
{
status = phHciNfc_CE_A_Mode( psHciContext,
pHwRef, HOST_CE_MODE_ENABLE );
if(status == NFCSTATUS_PENDING)
{
ps_ce_a_info->next_seq = HOST_CE_A_DISABLE_SEQ;
status = NFCSTATUS_SUCCESS;
}
break;
}
default :
{
break;
}
}
}
}
return status;
}
> sorry, i'm new to the xda, and cannot post externanl links with this thread.
if the reason is coming from the clf's software stack - the fireware, so, can we change it by disassamble it to unlock this block?
maybe there is an answer to this, thank u ^)^
I'm trying to develop an app to scan for a BLE device. However, it only scans one time. I tried to use a while loop to loop it but it hangs there. The scanning part is at the proceed function:
Code:
package com.example.user.myfriend;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import org.w3c.dom.Text;
public class MainActivity extends ActionBarActivity {
BluetoothAdapter mBluetoothAdapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
BluetoothManager bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
hello();
}
public void hello() {
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBluetooth = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBluetooth, 1);
}
proceed();
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 1) {
if (resultCode == RESULT_OK) {
proceed();
}
}
super.onActivityResult(requestCode, resultCode, data);
}
private BluetoothAdapter.LeScanCallback mLeScanCallback = new BluetoothAdapter.LeScanCallback() {
public void onLeScan(final BluetoothDevice device, final int rssi, final byte[] scanRecord) {
int startByte = 2;
boolean patternFound = false;
while (startByte <= 5) {
if (((int) scanRecord[startByte + 2] & 0xff) == 0x02 && //Identifies an iBeacon
((int) scanRecord[startByte + 3] & 0xff) == 0x15) { //Identifies correct data length
patternFound = true;
break;
}
startByte++;
}
if (patternFound) {
//Convert to hex String
byte[] uuidBytes = new byte[16];
System.arraycopy(scanRecord, startByte + 4, uuidBytes, 0, 16);
String hexString = bytesToHex(uuidBytes);
//Here is your UUID
String uuid = hexString.substring(0, 8) + "-" +
hexString.substring(8, 12) + "-" +
hexString.substring(12, 16) + "-" +
hexString.substring(16, 20) + "-" +
hexString.substring(20, 32);
//Here is your Major value
int major = (scanRecord[startByte + 20] & 0xff) * 0x100 + (scanRecord[startByte + 21] & 0xff);
//Here is your Minor value
int minor = (scanRecord[startByte + 22] & 0xff) * 0x100 + (scanRecord[startByte + 23] & 0xff);
if (major == 1) {
RelativeLayout hai = (RelativeLayout) findViewById(R.id.hai);
hai.setBackgroundColor(Color.YELLOW);
}
if (major == 2) {
RelativeLayout hai = (RelativeLayout) findViewById(R.id.hai);
hai.setBackgroundColor(Color.RED);
}
}
}
};
private static String bytesToHex(byte[] bytes) {
final char[] hexArray = "0123456789ABCDEF".toCharArray();
char[] hexChars = new char[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}
public void proceed() {
boolean scanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallback);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
// @Override
public void run() {
mBluetoothAdapter.stopLeScan(mLeScanCallback);
}
}, 50000000);
}
Code:
Hi,
I have a listview adapter which looks at radiogroups. I'm running into issues on how to exactly take the selected radiogroup value and save it to a sqlite table. Part of my adapter code is below.
holder.radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
List<Integer> x = new ArrayList<Integer>();
public void onCheckedChanged(RadioGroup group, int checkedId) {
for (int i = 0; i < x.size(); i++) {
if (i==position){
x.add(position, checkedId);
//x.add(position) ;
break;
}
}
}
});
Try this code :
Code:
rdgrp=(RadioGroup)findViewById(R.id.RadioGroup01);
String radiovalue= ((RadioButton)this.findViewById(rdgrp.getCheckedRadioButtonId())).getText().toString();
Bye
i work with this guild: Android Uploading Camera Image, Video to Server with Progress Bar
and when i take image i got this error:
Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/profile_imagephoto.jpg: open failed: ENOENT (No such file or directory
What can i do to fix this?
Code:
//Upload Profile Image
profileImage.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v) {
pictureCheck = "to_profile";
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setIcon(R.drawable.ic_action_search);
builder.setMessage("Select What To Do:")
// Positive button functionality
.setPositiveButton("Camera",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg0) {
Toast.makeText(MainActivity.this, "Open Camera...", Toast.LENGTH_SHORT).show();
Intent cameraintent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraintent, IMAGE_CAPTURE);
}
})
// Negative button functionality
.setNegativeButton("Gallery",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int arg0) {
Toast.makeText(
MainActivity.this, "Open Gallery...", Toast.LENGTH_SHORT).show();
// Do more stuffs
Intent galleryIntent = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
//dialog.cancel();
fileUri = getOutputMediaFileUri(MEDIA_TYPE_IMAGE);
galleryIntent.putExtra(MediaStore.EXTRA_OUTPUT, fileUri);
startActivityForResult(galleryIntent, RESULT_LOAD_INAGE);
}
});
// Create the Alert Dialog
AlertDialog alertdialog = builder.create();
// Show Alert Dialog
alertdialog.show();
}
});
/**
* Here we store the file url as it will be null after returning from camera
* app
*/
@Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// save file url in bundle as it will be null on screen orientation
// changes
outState.putParcelable("file_uri", fileUri);
}
@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
super.onRestoreInstanceState(savedInstanceState);
// get the file url
fileUri = savedInstanceState.getParcelable("file_uri");
}
@Override
public void onActivityResult(int requestCodeToProfile, int resultCodeToProfile, Intent dataToProfile) {
super.onActivityResult(requestCodeToProfile, resultCodeToProfile, dataToProfile);
launchUploadActivity(true);
}
private void launchUploadActivity(boolean isImage){
Intent i = new Intent(MainActivity.this, UploadActivity.class);
i.putExtra("filePath", fileUri.getPath());
i.putExtra("isImage", isImage);
startActivity(i);
}
/**
* Creating file uri to store image/video
*/
public Uri getOutputMediaFileUri(int type) {
return Uri.fromFile(getOutputMediaFile(type));
}
/**
* returning image / video
*/
private static File getOutputMediaFile(int type) {
// External sdcard location
File mediaStorageDir =
new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"profile_image");
// Create the storage directory if it does not exist
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d(TAG, "Oops! Failed create "
+ "profile_image" + " directory");
return null;
}
}
// Create a media file name
java.util.Date date= new java.util.Date();
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss",
Locale.getDefault()).format(date.getTime());
File mediaFile;
if (type == MEDIA_TYPE_IMAGE) {
mediaFile = new File(mediaStorageDir.getPath() + "photo.jpg");
} else if (type == MEDIA_TYPE_VIDEO) {
mediaFile = new File(mediaStorageDir.getPath() + File.separator
+ "VID_" + timeStamp + ".mp4");
} else {
return null;
}
return mediaFile;
}
This is a long shot, but the path of your image looks wrong. Are you missing a slash between the last dir and 'photo.jpg'. Should be this line:
mediaFile = new File(mediaStorageDir.getPath() + "photo.jpg");
Have you ever tried to extend your favorite app with new features using Xposed, but were shocked halfway that your hooked app doesn't declare a permission in AndroidManifest ? And then you spent infinite hours on the internet trying to solve this frustrating problem, you decided to use services and an external intent, but you found out that it was not convenient, and finally you gave up...
So you are like me, who wasted hours looking for a solution, until I figured out how to do it myself. Here's a snippet to save time for future Xposed enthusiasts. Put this code snippet in handleLoadPackage
Java:
// Hook will only patch System Framework
if (!lpparam.packageName.equals("android")) return;
String targetPkgName = "com.example.app"; // Replace this with the target app package name
String[] newPermissions = new String[] { // Put the new permissions here
"android.permission.INTERNET",
"android.permission.ACCESS_NETWORK_STATE"
};
String grantPermissionsMethod = null;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
grantPermissionsMethod = "restorePermissionState";
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.S_V2) {
XposedBridge.log("[WARNING] THIS HOOK IS NOT GUARANTEED TO WORK ON ANDROID VERSIONS NEWER THAN ANDROID 12");
}
} else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.P) {
grantPermissionsMethod = "grantPermissions";
}
else {
grantPermissionsMethod = "grantPermissionsLPw";
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
XposedBridge.log("[WARNING] THIS HOOK IS NOT GUARANTEED TO WORK ON ANDROID VERSIONS PRIOR TO JELLYBEAN");
}
}
XposedBridge.hookAllMethods(XposedHelpers.findClass("com.android.server.pm.permission.PermissionManagerService", lpparam.classLoader),
grantPermissionsMethod, new XC_MethodHook() {
@Override
protected void beforeHookedMethod(MethodHookParam param) throws Throwable {
// on Android R and above, param.args[0] is an instance of android.content.pm.parsing.ParsingPackageImpl
// on Android Q and older, param.args[0] is an instance of android.content.pm.PackageParser$Package
// However, they both declare the same fields we need, so no need to check for class type
String pkgName = (String) XposedHelpers.getObjectField(param.args[0], "packageName");
XposedBridge.log("Package " + pkgName + " is requesting permissions");
if (pkgName.equals(targetPkgName)) {
List<String> permissions = (List<String>) XposedHelpers.getObjectField(param.args[0], "requestedPermissions");
for (String newPermission: newPermissions) {
if (!permissions.contains(newPermission)) {
permissions.add(newPermission);
XposedBridge.log("Added " + newPermission + " permission to " + pkgName);
}
}
}
}
});
Notes:
You must check System Framework in LSposed Manager
A reboot is required after adding the target permissions
You still need to prompt the user to accept sensitive permissions (ie android.permission.READ_CONTACTS), even if you have added them using this method
Wow, thx. Great for the install permissions!
I wrote a class to grant install and runtime/sensitive permissions (without prompting users).
Android 12 and 13 implementation:
Java:
public class Grant_Package_Permissions {
private static final int sdk = android.os.Build.VERSION.SDK_INT;
public static void hook(LoadPackageParam lpparam) {
try {
Class<?> PermissionManagerService = XposedHelpers.findClass(
sdk >= 33 /* android 13+ */ ?
"com.android.server.pm.permission.PermissionManagerServiceImpl" :
"com.android.server.pm.permission.PermissionManagerService", lpparam.classLoader);
Class<?> AndroidPackage = XposedHelpers.findClass(
"com.android.server.pm.parsing.pkg.AndroidPackage", lpparam.classLoader);
Class<?> PermissionCallback = XposedHelpers.findClass(
sdk >= 33 /* android 13+ */ ?
"com.android.server.pm.permission.PermissionManagerServiceImpl$PermissionCallback" :
"com.android.server.pm.permission.PermissionManagerService$PermissionCallback", lpparam.classLoader);
// PermissionManagerService(Impl) - restorePermissionState
XposedHelpers.findAndHookMethod(PermissionManagerService, "restorePermissionState",
AndroidPackage, boolean.class, String.class, PermissionCallback, int.class, new XC_MethodHook() {
@SuppressWarnings("unchecked")
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// params
Object pkg = param.args[0];
int filterUserId = (int) param.args[4];
// obtém os campos
Object mState = XposedHelpers.getObjectField(param.thisObject, "mState");
Object mRegistry = XposedHelpers.getObjectField(param.thisObject, "mRegistry");
Object mPackageManagerInt = XposedHelpers.getObjectField(param.thisObject, "mPackageManagerInt");
// Continua ?
String packageName = (String) XposedHelpers.callMethod(pkg, "getPackageName");
Object ps = XposedHelpers.callMethod(mPackageManagerInt,
sdk >= 33 /* android 13+ */ ?
"getPackageStateInternal" :
"getPackageSetting", packageName);
if (ps == null)
return;
int[] getAllUserIds = (int[]) XposedHelpers.callMethod(param.thisObject, "getAllUserIds");
int userHandle_USER_ALL = XposedHelpers.getStaticIntField(Class.forName("android.os.UserHandle"), "USER_ALL");
final int[] userIds = filterUserId == userHandle_USER_ALL ? getAllUserIds : new int[]{filterUserId};
for (int userId : userIds) {
List<String> requestedPermissions;
Object userState = XposedHelpers.callMethod(mState, "getOrCreateUserState", userId);
int appId = (int) XposedHelpers.callMethod(ps, "getAppId");
Object uidState = XposedHelpers.callMethod(userState, "getOrCreateUidState", appId);
// package 1
if (packageName.equals("PACKAGE_1")) {
requestedPermissions = (List<String>) XposedHelpers.callMethod(pkg, "getRequestedPermissions");
grantInstallOrRuntimePermission(requestedPermissions, uidState, mRegistry,
Manifest.permission.RECORD_AUDIO);
grantInstallOrRuntimePermission(requestedPermissions, uidState, mRegistry,
Manifest.permission.MODIFY_AUDIO_SETTINGS);
}
// package 2
if (packageName.equals("PACKAGE_2")) {
requestedPermissions = (List<String>) XposedHelpers.callMethod(pkg, "getRequestedPermissions");
grantInstallOrRuntimePermission(requestedPermissions, uidState, mRegistry,
Manifest.permission.READ_CONTACTS);
}
}
}
});
} catch (Exception e) {
XposedBridge.log(e);
}
}
private static void grantInstallOrRuntimePermission(List<String> requestedPermissions, Object uidState,
Object registry, String permission) {
if (!requestedPermissions.contains(permission))
XposedHelpers.callMethod(uidState, "grantPermission",
XposedHelpers.callMethod(registry, "getPermission", permission));
}
}
Edit: Android 12 and 13 implementation!
this looks promising. how to use this in xposed ? is there a module available?