How to pass android permission name as variable? - android

Which type of variable can pass REQUESTED_PERMISSION to the following function (sample code from Here) and how it shoud be concatenated to android.Manifest.permission.+ ?
Edit:
It seems that the variable should also pass through the ContextCompat.checkSelfPermission (It is marked as unused). How should I pass it?
Public boolean checkPermission( ????? REQUESTED_PERMISSION){
if (ContextCompat.checkSelfPermission(
CONTEXT, android.Manifest.permission.REQUESTED_PERMISSION) ==
PackageManager.PERMISSION_GRANTED) {
performAction(...);
} else if (shouldShowRequestPermissionRationale(...)) {
showInContextUI(...);
} else {
requestPermissions(...);
}
}

https://developer.android.com/reference/android/Manifest.permission
Here you have list with the permissions. They are all strings.
public boolean checkPermission( String permission ) { ... }
usage (for example, you need vibration) :
checkPermission(Manifest.permission.VIBRATE);

Related

Android AspectJ #Around with method args not working

In my current Android application I am investigating the use of #AspectJ
I am attempting to "capture" all executions to methods whose signature resembles:-
public void onMethodClicked(com.example.CustomType customType) {}
I have the following POINTCUTS
1) Ignore my Aspect class:
#Pointcut("!within(com.example.aspect)")
public void notAspect() { }
2) Select all "Clicked" methods with customType argument
#Pointcut("execution(* com.example..*.*Clicked(com.example.CustomType)) && args(custom)";)
public void customClicked(CustomType custom) { }
3) My #Around:-
#Around("notAspect() && customClicked()")
public Object selectedClicked(final ProceedingJoinPoint joinPoint, CustomType custom) throws Throwable {
Log.d(TAG, "Found a clicked method " + custom);
Object result = joinPoint.proceed();
return result;
}
When I build my Android Application I get these messages
no match for this type name: CustomType [Xlint:invalidAbsoluteTypeName]
bad parameter to pointcut reference
formal unbound in pointcut
no match for this type name: com.example.aspect [Xlint:invalidAbsoluteTypeName]
the parameter custom is not bound in [all branches of] pointcut
use of ProceedingJoinPoint is allowed only on around advice (arg 1 in (before(extraFlags: 2): (((!within(com.example.aspect+) && execution(* com.example..*.*Clicked(com.example.CustomType)) && args(custom)) && persingleton(com.example.aspect.TraceAspect))->void com.example.aspect.TraceAspect.selectedClicked(org.aspectj.lang.JoinPoint, com.example.CustomType)))
What have I done wrong?
UPDATE
I have fixed one of the error/warning messages by correcting the !within() as follows:-
1) Ignore my Aspect class:
#Pointcut("!within(com.example.aspect.TraceAspect)")
public void notAspect() { }
I'm not sure about your problem but you may try changing the POINTCUT like this.
#Pointcut("!within(com.example.aspect.TraceAspect)")
public void notAspect() { }
#Pointcut("execution(* com.example..*.*Clicked(com.example.CustomType)))
public void customClicked() { }
Look I've removed the args(custom) part here which go inside the #Around annotation. And yes, of course I've removed the function parameter argument of customClicked function and the semi-colon by the end of the statement.
Now write your selectedClicked function like this by passing the arguments from here.
#Around("notAspect() && customClicked() && args(custom)")
public Object selectedClicked(final ProceedingJoinPoint joinPoint, CustomType custom) throws Throwable {
Log.d(TAG, "Found a clicked method " + custom);
Object result = joinPoint.proceed();
return result;
}
It should work with no failure.

Create boolean listener

In Android, how do I take an action whenever a variable changes?
So I want to implement a listener for an object I created. What I want it to do is execute a block of code when its value changes from false to true.
As I am following this thread, I can't understand where the person wants us to implement the last block of code containing the logic for the listener.
Could someone, hopefully, guide me in the right direction?
(This question is being asked here as I don't have enough rep. points)
That last bit of example code triggers the listener, so it basically needs to be run whenever the "event" occurs. In this case the "event" is whenever (wherever in the code) the value of the variable changes.
If you have a setter and that is the only place the value changes, that is where you'd put it. If you are changing the value in multiple places throughout your code, I would make a new private method (call it signalChanged), put your code there, and then call it immediately after the variable assignment in the cases you want the listener to fire.
Here's an example (some code borrowed from linked answer, haven't checked that it compiles).
public class MyObj
{
public MyObj(int value)
{
setValue(value);
}
private int myValue;
public int getValue() { return myValue; }
public void setValue( int value )
{
if (value != myValue)
{
myValue = value;
signalChanged();
}
}
public interface VariableChangeListener
{
public void onVariableChanged(Object... variableThatHasChanged);
}
private VariableChangeListener variableChangeListener;
public void setVariableChangeListener(VariableChangeListener variableChangeListener)
{
this.variableChangeListener = variableChangeListener;
}
private void signalChanged()
{
if (variableChangeListener != null)
variableChangeListener.onVariableChanged(myValue);
}
}
you have to create a callback interface
here is a good about custom listener tutorial
here is a sample
public class MyObj {
VariableChanger onVariableChanged ;
public void setOnVariableChanged(VariableChanger onVariableChanged) {
this.onVariableChanged = onVariableChanged;
}
void log(){
boolean changed = false;
onVariableChanged.onVariableChanged();
//this will call it
}
interface VariableChanger{
void onVariableChanged();
}
}
class logic {
MyObj mo = new MyObj();
void main(){
mo.setOnVariableChanged(new MyObj.VariableChanger() {
#Override
public void onVariableChanged() {
//do your action
}
});
}
}
In Android, like any language, most developper uses logic comparisons to check values (if, else, switch, =, !=, >, <, etc) or Event (signal)
What kind of listener do you want to implement?

How to mock permissions for testing in Android?

With Android 6.0 and new permission model, I am checking if the permission exists before performing certain task.
I want to assign these permissions to available and not available for testing purpose. I have a static class to check various permissions depending on the string.
boolean result = ContextCompat.checkSelfPermission(context, name) == PackageManager.PERMISSION_GRANTED;
Can it be achieved using Mockito or Roboelectric?
If you move your permission checker to a collaborator class, you can mock the collaborator. I am not familiar with the Android return types but the solution would look like this:
class PermissionsChecker {
public String checkSelfPermission(context, name) {
return ContextCompat.checkSelfPermission(context, name);
}
}
class YourApp {
private PermissionsChecker permissionsChecker; //need to inject this via setter or constructor
public doSomething() {
boolean result = permissionsChecker.checkSelfPermission(context, name).equals(PackageManager.PERMISSION_GRANTED);
}
}
class YourAppTest {
PermissionsChecker permissionsChecker = mock(PermissionsChecker.class);
#InjectMocks YourApp app = new YourApp();
#Test
public void hasPermissions() {
when(permissionsChecker.checkSelfPermission(...)).thenReturn("NOT GRANTED");
app.something();
//verify you get some error
}
}

How to parcel custom list on Android?

First of all, all the code i will refer to is at my repository
I have been having problems parcelizing a PlayList, the parcelizing works wonders but the deserializing ends up on either a NullPointerException or a BadParcelableException. I haven't been able to pinpoint the source of the exceptions, thus i ask you to check my code to see if i'm abusing any OOP principles or outright misusing the API.
You can't pass the all the class as a parameter to parcel.write(). You need to pass just the parameter copy received in the constructor. You also need to ensure that all objects manipulated are or implement ´Parcelable`.
I believe you need to change the follwing:
In constructor
ArrayList<Song> copy;
public PlayList(ArrayList<Song> copy){
super(copy);
this.copy = copy;
}
In write()
public void writeToParcel(Parcel parcel, int flags) {
parcel.writeTypedList(copy);
parcel.writeInt(actualSong);
parcel.writeInt(shuffling ? 1 : 0);
parcel.writeInt(repeating ? 1 : 0);
}
In read()
public PlayList(Parcel serialized) {
super(serialized.readTypedList(copy, Song.WptType.CREATOR));
actualSong = serialized.readInt();
shuffling = serialized.readInt() == 1 ? true : false;
repeating = serialized.readInt() == 1 ? true : false;
}
NOTE
You also need to implement Parcelable in the Song class for this to work, but it looks already done in the code repository.

How to judge whether two context are the same in Android?

such as you want to judge two strings, you can use string1.equals(string2)...then how to judge whether two context are the same in Android?
Why do you do this?
If they are all Activity instances you can treat them as such and use:
if ( activity instanceof MyClassActivityOne ) {
// do something
}
Check it like this
if(c1.getClass().equals(c2.getClass()))
{
//The context is the same
}
else
{
//Context is different
}
You can check the getApplicationContext() of each to see if they are the same.
Im not sure,but you can try this:
if(context1.getClass().getName().equals("com.xxx.sameclass"))&&context2.getClass().getName().equals("com.xxx.sameclass")))
{
if(context1 == context2)
//same condition
}

Categories

Resources