Select default launcher for an app not appear in Android 7 - android

I have an app that run as a launcher, in Android 4 in work great but in Android 7 and 8 the select launcher dialog not appear
//
// Decompiled by Procyon v0.5.36
//
package com.r7developers.unityplugin;
import android.os.Build;
import android.annotation.TargetApi;
import android.os.Process;
import android.app.AppOpsManager;
import android.content.Intent;
import com.rvalerio.fgchecker.AppChecker;
import android.content.Context;
public class Plugin
{
static Context mContext;
static String mBundleIdentifier;
static AppChecker mAppChecker;
public static void init(final Context context, final String bundleIdentifier) {
Plugin.mContext = context;
Plugin.mBundleIdentifier = bundleIdentifier;
}
public static void start() {
Plugin.mAppChecker = new AppChecker();
Plugin.mAppChecker.other((AppChecker.Listener)new AppChecker.Listener() {
public void onForeground(final String packageName) {
if (packageName != null && !packageName.contains(Plugin.mBundleIdentifier)) {
final Intent startHomescreen = new Intent("android.intent.action.MAIN");
startHomescreen.addCategory("android.intent.category.HOME");
startHomescreen.setFlags(268435456);
Plugin.mContext.startActivity(startHomescreen);
}
}
}).timeout(1000).start(Plugin.mContext);
}
public static void stop() {
Plugin.mAppChecker.stop();
}
public static void requestUsageStatsPermission() {
if (needsUsageStatsPermission() && !hasUsageStatsPermission()) {
Plugin.mContext.startActivity(new Intent("android.settings.USAGE_ACCESS_SETTINGS"));
}
}
#TargetApi(19)
public static boolean hasUsageStatsPermission() {
final AppOpsManager appOps = (AppOpsManager)Plugin.mContext.getSystemService("appops");
final int mode = appOps.checkOpNoThrow("android:get_usage_stats", Process.myUid(), Plugin.mContext.getPackageName());
final boolean granted = mode == 0;
return granted;
}
public static boolean needsUsageStatsPermission() {
return Build.VERSION.SDK_INT >= 21;
}
public static void openSettings() {
final Intent intent = new Intent("android.settings.SETTINGS");
intent.addFlags(268435456);
Plugin.mContext.startActivity(intent);
}
}
This code is decompiled from a jar plugin from unity project
Is there anything I'm missing?

Your problem must be caused by some missing line in the manifest.
Android evolve really quickly and some application originally made for older version might not work anymore due to changing in the permission system.
That must apply to the Android Manifest as well. By luck you got it working on an older device, but it seems that handling newer ones is problematic.
Have you tried to recompile a way smaller version of the code and test it on multiple version ?
Just by looking at some exemple launcher (but made without the Unity Engine), can help you understand if you have miss something.
Here is a link to an Android Launcher I found (the first one) on GitHub: KISS/app/src/main/AndroidManifest.xml.
Try adding the line that you are missing from your, especially the intent-filter that help Android know what your apps should be aware of when showing it in menus, like the Launcher selector.
I am not an expert, but I know that working with Android can be a pain.

Related

Implementing platform functionality in a static class - Xamarin.Forms

I am not sure of the terminology for what I'm looking to do, so sorry in advance!
I've found a FilePicker plugin for Xamarin.Forms (https://github.com/Studyxnet/FilePicker-Plugin-for-Xamarin-and-Windows) that implements device-specific functionality for selecting files via the CrossFilePicker class.
The way to use leverage this functionality would be something like
CrossFilePicker.Current.OpenFile("Filename.txt");
The most important part of this for me is that CrossFilePicker.Current is static and can be accessible from anywhere in the shared layer of my Xamarin.Forms app.
I need to implement a class with the same characteristics. I want to leverage device Accessibility functionality (i.e. determining if a screen reader is enabled) and I need to be able to do so with a static class.
My eventual plan is to then wrap this static class so that I can use it for unit tests too.
I don't want to import device libraries into my shared project.
TLDR: I need a static class that implements device-specific functionality.
Any help would be greatly appreciated! Thank you :)
EDIT:
Here are the files I have currently implemented in my project
IAccessibilityService Located in the shared .NET project
namespace Bitspace.Services
{
public interface IAccessibilityService
{
public bool IsScreenReaderEnabled();
public void Announcement(string message);
public void NavigationAnnouncement(string message);
}
}
DeviceAccessibility.cs Located in the shared .NET project
using System;
namespace Bitspace.Services
{
public class DeviceAccessibility
{
private static Lazy<IAccessibilityService> Implementation = new Lazy<IAccessibilityService>(() => CreateAccessibilityService(), System.Threading.LazyThreadSafetyMode.PublicationOnly);
public static IAccessibilityService Current
{
get
{
var curr = Implementation.Value;
if (curr == null)
{
throw new Exception();
}
return curr;
}
}
private static IAccessibilityService CreateAccessibilityService()
{
return new DeviceAccessibilityImplementation();
}
}
}
DeviceAccessibilityImplementation.cs Located in the Android project
using Android.Runtime;
namespace Bitspace.Services
{
[Preserve (AllMembers = true)]
public class DeviceAccessibilityImplementation : IAccessibilityService
{
public bool IsScreenReaderEnabled()
{
return true;
}
public void Announcement(string message)
{
}
public void NavigationAnnouncement(string message)
{
}
}
}
If I try to build the project, I get an error on the return new DeviceAccessibilityImplementation(); line in DeviceAccessibility.cs that says DeviceAccessibility.cs(25, 24): [CS0246] The type or namespace name 'DeviceAccessibilityImplementation' could not be found (are you missing a using directive or an assembly reference?)
However, CTRL Clicking on that line takes me to the DeviceAccessibilityImplementation.cs

How to correctly implement and test Custom Lint Rules in Android Studio?

I'm following this tutorial and this Custom Detector Example in order to implement Custom Lint Rules. Basically what I've done is:
Create a new Android Project in Android Studio;
Create a java module for project created in step 1;
On module's build.gradle, import Lint API dependencies;
Create an Issue & IssueRegistry & CustomDetector;
Reference the IssueRegistry on module's build.gradle;
Create Unit tests;
My problem is, during the execution of my JUnits, I always receive "No Warning". When I debug the test, I can see that my Custom Detector isn't called, what am I doing wrong?
Strings.java
public class Strings {
public static final String STR_ISSUE_001_ID = "VarsMustHaveMoreThanOneCharacter";
public static final String STR_ISSUE_001_DESCRIPTION = "Avoid naming variables with only one character";
public static final String STR_ISSUE_001_EXPLANATION = "Variables named with only one character do not pass any meaning to the reader. " +
"Variables name should clear indicate the meaning of the value it is holding";
}
Issues.java
public class Issues {
public static final
Issue ISSUE_001 = Issue.create(
STR_ISSUE_001_ID,
STR_ISSUE_001_DESCRIPTION,
STR_ISSUE_001_EXPLANATION,
SECURITY,
// Priority ranging from 0 to 10 in severeness
6,
WARNING,
new Implementation(VariableNameDetector.class, ALL_RESOURCES_SCOPE)
);
}
IssuesRegistry.java
public class IssueRegistry extends com.android.tools.lint.client.api.IssueRegistry {
#Override
public List<Issue> getIssues() {
List<Issue> issues = new ArrayList<>();
issues.add(ISSUE_001);
return issues;
}
}
VariableNameDetector.java
public class VariableNameDetector extends Detector implements Detector.JavaScanner {
public VariableNameDetector() {
}
#Override
public boolean appliesToResourceRefs() {
return false;
}
#Override
public boolean appliesTo(Context context, File file) {
return true;
}
#Override
#Nullable
public AstVisitor createJavaVisitor(JavaContext context) {
return new NamingConventionVisitor(context);
}
#Override
public List<String> getApplicableMethodNames() {
return null;
}
#Override
public List<Class<? extends Node>> getApplicableNodeTypes() {
List<Class<? extends Node>> types = new ArrayList<>(1);
types.add(lombok.ast.VariableDeclaration.class);
return types;
}
#Override
public void visitMethod(
JavaContext context,
AstVisitor visitor,
MethodInvocation methodInvocation
) {
}
#Override
public void visitResourceReference(
JavaContext context,
AstVisitor visitor,
Node node,
String type,
String name,
boolean isFramework
) {
}
private class NamingConventionVisitor extends ForwardingAstVisitor {
private final JavaContext context;
NamingConventionVisitor(JavaContext context) {
this.context = context;
}
#Override
public boolean visitVariableDeclaration(VariableDeclaration node) {
StrictListAccessor<VariableDefinitionEntry, VariableDeclaration> varDefinitions =
node.getVariableDefinitionEntries();
for (VariableDefinitionEntry varDefinition : varDefinitions) {
String name = varDefinition.astName().astValue();
if (name.length() == 1) {
context.report(
ISSUE_001,
context.getLocation(node),
STR_ISSUE_001_DESCRIPTION
);
return true;
}
}
return false;
}
}
}
build.gradle
apply plugin: 'java'
configurations {
lintChecks
}
ext {
VERSION_LINT_API = '24.3.1'
VERSION_LINT_API_TESTS = '24.3.1'
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "com.android.tools.lint:lint-api:$VERSION_LINT_API"
implementation "com.android.tools.lint:lint-checks:$VERSION_LINT_API"
testImplementation "com.android.tools.lint:lint-tests:$VERSION_LINT_API_TESTS"
}
jar {
manifest {
attributes('Lint-Registry': 'br.com.edsilfer.lint_rules.resources.IssueRegistry')
}
}
sourceCompatibility = "1.7"
targetCompatibility = "1.7"
TestVariableNameDetector.java
private static final String ARG_DEFAULT_LINT_SUCCESS_LOG = "No warnings.";
#Override
protected Detector getDetector() {
return new VariableNameDetector();
}
#Override
protected List<Issue> getIssues() {
return Collections.singletonList(Issues.ISSUE_001);
}
public void test_file_with_no_variables_with_length_equals_01() throws Exception {
assertEquals(
ARG_DEFAULT_LINT_SUCCESS_LOG,
lintProject(java("assets/Test.java", "public class Test {public String sampleVariable;}"))
);
}
public void test_file_with_variables_with_length_equals_01() throws Exception {
assertEquals(
ARG_DEFAULT_LINT_SUCCESS_LOG,
lintProject(java("assets/Test3.java", "public class Test {public String a;bnvhgvhj}"))
);
}
}
P.S.: on Java's module I do not have access to assetsor res folder, that is the reason why I've created a String.java and I'm using java(to, source) in my Unit test - I assumed that this java method does the same as the xml from the tutorial link I referenced at the top of this question.
It turned out that in my case the problem was with the JUnit itself. I think that the way I was attempting to simulate the file was wrong. The text below is part of the README.md of a sample project that I've created in order to document what I've learned from this API and answers the question in the title:
Create
Create a new Android Project;
Create a new Java Library Module - Custom Lint Rules are packaged into .jar libraries once they are ready, therefore the easiest way to implement them using them is inside a Java Module Library;
On module's build.gradle:
add target and source compatibility to Java 1.7;
add dependencies for lint-api, lint-checks and test dependencies;
add jar packing task containing two attributes: Manifest-Version and Lint-Registry, set the first to 1.0 and the second as the full path to a class that will later on contain the issue's catalog;
add a default tasl assemble;
[OPTIONAL]: add a task that will copy the generated .jar into ~/.android/lint;
Check REF001 and choose a Detector that best suits your needs, based on it create and implement a class to fulfill the Detector's role;
Still based on REF0001 chosen file, create and implement a Checker class, later referring to it inside Detector's createJavaVisitor() method;
for the sake of SRP, do not place Checker in the same file of Detector's class;
Copy the generated .jar file from build/lib to ~/.android/lint - if you added a task on build.gradle that does this you can skip this step;
Restart the computer - once created and moved into ~/.android/lint, the Custom Rules should be read by Lint next time the program starts. In order to have the alert boxes inside Android Studio, it is enough to invalidate caches and restart the IDE, however, to have your custom rules caught on Lint Report when ./gradlew check, it might be necessary to restart your computer;
Testing Detectors and Checkers
Testing Custom Rules is not an easy task to do - mainly due the lack of documentation for official APIs. This section will present two approaches for dealing with this. The main goal of this project is to create custom rules that will be run against real files, therefore, test files will be necessary for testing them. They can be places in src/test/resources folder from your Lint Java Library Module;
Approach 01: LintDetectorTest
Make sure you've added all test dependencies - checkout sample project's build.gradle;
Copy EnhancedLintDetectorTest.java and FileUtils.java into your project's test directory;
There is a known bug with Android Studio that prevents it from seeing files from src/test/resources folder, these files are a workaround for that;
EnhancedLintDetectorTest.java should return all issues that will be subject of tests. A nice way to do so is getting them from Issue Registry;
Create a test class that extends from EnhancedLintDetectorTest.java;
Implement getDetector() method returning an instance of the Detector to be tested;
Use lintFiles("test file path taking resources dir as root") to perform the check of the Custom Rules and use its result object to assert the tests;
Note that LintDetectorTest.java derives from TestCase.java, therefore, you're limited to JUnit 3.
Approach 02: Lint JUnit Rule
You might have noticed that Approach 01 might be a little overcomplicated, despite the fact that you're limited to JUnit 3 features. Because of that GitHub user a11n created a Lint JUnit Rule that allows the test of Custom Lint Rules in a easier way that counts with JUnit 4 and up features. Please, refer to his project README.md for details about how to create tests using this apprach.
Currently, Lint JUnit Rule do not correct the root dir for test files and you might no be able to see the tests passing from the IDE - however it works when test are run from command line. An issue and PR were created in order to fix this bug.
I'm not sure how to use the AST Api, however I'm personally using Psi and this is one of my lint checks that are working for me.
public final class RxJava2MethodCheckReturnValueDetector extends Detector implements Detector.JavaPsiScanner {
static final Issue ISSUE_METHOD_MISSING_CHECK_RETURN_VALUE =
Issue.create("MethodMissingCheckReturnValue", "Method is missing the #CheckReturnValue annotation",
"Methods returning RxJava Reactive Types should be annotated with the #CheckReturnValue annotation.",
MESSAGES, 8, WARNING,
new Implementation(RxJava2MethodCheckReturnValueDetector.class, EnumSet.of(JAVA_FILE, TEST_SOURCES)));
#Override public List<Class<? extends PsiElement>> getApplicablePsiTypes() {
return Collections.<Class<? extends PsiElement>>singletonList(PsiMethod.class);
}
#Override public JavaElementVisitor createPsiVisitor(#NonNull final JavaContext context) {
return new CheckReturnValueVisitor(context);
}
static class CheckReturnValueVisitor extends JavaElementVisitor {
private final JavaContext context;
CheckReturnValueVisitor(final JavaContext context) {
this.context = context;
}
#Override public void visitMethod(final PsiMethod method) {
final PsiType returnType = method.getReturnType();
if (returnType != null && Utils.isRxJava2TypeThatRequiresCheckReturnValueAnnotation(returnType)) {
final PsiAnnotation[] annotations = method.getModifierList().getAnnotations();
for (final PsiAnnotation annotation : annotations) {
if ("io.reactivex.annotations.CheckReturnValue".equals(annotation.getQualifiedName())) {
return;
}
}
final boolean isMethodMissingCheckReturnValueSuppressed = context.getDriver().isSuppressed(context, ISSUE_METHOD_MISSING_CHECK_RETURN_VALUE, method);
if (!isMethodMissingCheckReturnValueSuppressed) {
context.report(ISSUE_METHOD_MISSING_CHECK_RETURN_VALUE, context.getLocation(method.getNameIdentifier()), "Method should have #CheckReturnValue annotation");
}
}
}
}
}
Checkout the many more I wrote here.

React Native Android Native UI Components doesn't find #ReactProps

i'm trying to implement my first react native UI component, i followed the Facebook tutorial and it should be easy but i have some strange problem
public class CameraViewManager extends SimpleViewManager<CameraPreview> {
public static final String REACT_CLASS = "RCTCameraView";
#Override
public String getName() {
return REACT_CLASS;
}
#Override
public CameraPreview createViewInstance(ThemedReactContext context) {
return new CameraPreview(context);
}
#ReactProp(name = "test")
public void setTest(CameraPreview view, #Nullable String test){
Log.i("TESTWD", test);
}
}
This is the ViewManager i'm using and to me it seems correct. The first problem is that android studio doesn't find #ReactProp and it doesn't compile. The second problem is that if i remove that method everything compile but when i use this component nothing appears
Just ran into this myself. The solution is as if-else-switch pointed out in a comment above:
// Import this
import com.facebook.react.uimanager.annotations.ReactProp;
// Not this!
import com.facebook.react.uimanager.ReactProp;
There seem to be two #ReactProp definitions in different packages and Android Studio chooses the wrong one by default.
I solved this problem using react-native 0.13.+ instead of 0.11.+

OpenCV + Android - face recognition not working

I have been implemented this project: https://github.com/yaylas/AndroidFaceRecognizer into Android Studio. I included OpenCV using tutorial: https://www.youtube.com/watch?v=OTw_GIQNbD8 (this is static initialization). Moreover, I set in Android Studio settings proper NDK location.
Problem is that, if I add this Class:
package com.yaylas.sytech.facerecognizer;
import java.util.Vector;
import org.opencv.core.Mat;
import org.opencv.core.MatOfRect;
import android.widget.Toast;
public class DetectionBasedTracker
{
public DetectionBasedTracker(String cascadeName, int minFaceSize, boolean isFaceDetector) {
mNativeObj = nativeCreateObject(cascadeName, minFaceSize, isFaceDetector);
}
public long getNativeObj(){
return mNativeObj;
}
public void setMinFaceSize(int size) {
nativeSetFaceSize(mNativeObj, size);
}
public void detect(Mat imageGray, MatOfRect faces) {
nativeDetect(mNativeObj, imageGray.getNativeObjAddr(), faces.getNativeObjAddr());
}
public void release() {
nativeDestroyObject(mNativeObj);
mNativeObj = 0;
}
public static Vector<Mat> imageVector = new Vector<Mat>();
public static void addElement(Mat m){
imageVector.add(m);
System.out.println("--------------------------------- elementAdded: "+imageVector.size());
}
public static long getElementAt(int index){
if(index >= imageVector.size() || index < 0){
return 0;
}
System.out.println("-------------------------***** get element: "+imageVector.size()+" index: "+index);
return imageVector.elementAt(index).getNativeObjAddr();
}
public static int getImageCount(){
return imageVector.size();
}
private long mNativeObj = 0;
private static native long nativeCreateObject(String cascadeName, int minFaceSize, boolean faceDetection);
private static native void nativeDestroyObject(long thiz);
private static native void nativeStart(long thiz);
private static native void nativeStop(long thiz);
private static native void nativeSetFaceSize(long thiz, int size);
private static native void nativeDetect(long thiz, long inputImage, long faces);
}
An error is returned:
Cannot resolve corresponding JNI function
I tried everything, but the error still is there. I would like to ask, where can be a problem?
There are several reasons why the runtime might not be able to resolve the JNI function. Test these hypotheses:
The native code library didn't get bundled into your APK. Look inside the APK for it.
The native code library is in the wrong directory of the APK. Again, look and see.
The Java class got mangled by ProGuard so the names no longer match with the native library. Try turning off ProGuard. It should be off for debug builds.
If your native code library is compiled for ARM but you're running in an x86 based Android emulator (or vice versa), it won't be able to load that library.
Think of more hypotheses, then test them.
The page http://opencv.org/platforms/android.html has lots of info about OpenCV on Android, including links to tutorials.

CordovaWebView.Cordova_Version Error

I have just created a splash screen in my cordova project. I was able to build and run my project initially and my splash screen was displaying. However, when I added in the cordova.jar into the project library to serve as a file dependencies for my webservice function. I kept having this syntax error in my SplashScreen.java:
error: cannot find symbol variable CORDOVA_VERSION
Following is a snippet of my code:
import org.apache.cordova.*;
import org.apache.cordova.CallbackContext;
import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CordovaWebView;
public class SplashScreen extends CordovaPlugin {
private static final String LOG_TAG = "SplashScreen";
// Cordova 3.x.x has a copy of this plugin bundled with it (SplashScreenInternal.java).
// Enable functionality only if running on 4.x.x.
private static final boolean HAS_BUILT_IN_SPLASH_SCREEN = Integer.valueOf(CordovaWebView.
CORDOVA_VERSION.split("\\.")[0]) < 4;
private static Dialog splashDialog;
private static ProgressDialog spinnerDialog;
private static boolean firstShow = true;
....
Could I receive some help to solve this issue please?
I don't know what you are trying to do exaclty but you can't do that.
You just can't CordovaWebView.CORDOVA_VERSION.
If you really want to know what version you use programmatically, you can use this plugin
Otherwise you can just do that
PackageManager packageManager = this.cordova.getActivity().getPackageManager();
System.out.println(packageManager.versionName);
or
PackageManager packageManager = this.cordova.getActivity().getPackageManager();
packageManager.getPackageInfo(this.cordova.getActivity().getPackageName(), 0).versionName;
Dont forget to surround with try/catch.

Categories

Resources