• 當前位置:首頁 > IT技術 > 移動平臺 > 正文

    安卓開發常用知識點& 安卓開發常見問題及解決方案
    2021-08-08 15:44:29

    常用知識點===

    一,Activity相關

    • 1,判斷activity是在前臺運行,還是在后臺運行
    //當前activity是否在前臺顯示
        private boolean isAPPforeground(final Context context) {
            ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
            if (!tasks.isEmpty()) {
                ComponentName topActivity = tasks.get(0).topActivity;
                if (topActivity.getClassName().equals(context.getClass().getName())) {
                    Log.i("qcl0403", "前臺");
                    return true;
                } else {
                    Log.i("qcl0403", "后臺");
                }
            }
            return false;
        }
    
    • 2,acitivity設置為singleTop或singleTask 模式時,相關文章跳本activity調整數據不改變問題
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        setIntent(intent);
        ARouter.getInstance().inject(this);
    }
    
    二,View相關
    • 1 判斷當前view是否在前臺展示,我們這里以recyclerView為例
    ViewTreeObserver treeObserver = recyclerView.getViewTreeObserver();
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR2) {
                treeObserver.addOnWindowFocusChangeListener(new ViewTreeObserver.OnWindowFocusChangeListener() {
                    @Override
                    public void onWindowFocusChanged(boolean hasFocus) {
                        /*
                        hasFocus是我們窗口狀態改變時回傳回來的值
                        true: 我們的view在前臺展示
                        fasle: 熄屏,onpause,后臺時展示 
                        我們如果在每次熄屏到亮屏也算一次曝光的話,那這里為true的時候可以做統計
                        */
    
                    }
                });
            }
    
    • 2,RecyclerView滾動到指定位置,并置頂
    LinearSmoothScroller smoothScroller = new LinearSmoothScroller
            (ArticleDetailActivity.this) {
        @Override
        protected int getVerticalSnapPreference() {
            return LinearSmoothScroller.SNAP_TO_START;
        }
    //設置滑動1px所需時間
    @Override
    protected float calculateSpeedPerPixel
    (DisplayMetrics displayMetrics) {
        //縮短每px的滑動時間
        float MILLISECONDS_PER_INCH = getResources().getDisplayMetrics()
                .density * 0.03f;
        return MILLISECONDS_PER_INCH / displayMetrics.density;
        //返回滑動一個pixel需要多少毫秒
    }
    };
    smoothScroller.setTargetPosition(position);
    virtualLayoutManager.startSmoothScroll(smoothScroller);
    
    三,適配相關

    -1,判斷手機是否有底部虛擬按鍵

       /*
        * 判斷手機是否有底部虛擬按鍵
        * */
        public boolean checkDeviceHasNavigationBar(Context context) {
            boolean hasNavigationBar = false;
            Resources rs = context.getResources();
            int id = rs.getIdentifier("config_showNavigationBar", "bool", "android");
            if (id > 0) {
                hasNavigationBar = rs.getBoolean(id);
            }
            try {
                Class systemPropertiesClass = Class.forName("android.os.SystemProperties");
                Method m = systemPropertiesClass.getMethod("get", String.class);
                String navBarOverride = (String) m.invoke(systemPropertiesClass, "qemu.hw.mainkeys");
                if ("1".equals(navBarOverride)) {
                    hasNavigationBar = false;
                } else if ("0".equals(navBarOverride)) {
                    hasNavigationBar = true;
                }
            } catch (Exception e) {
            }
            return hasNavigationBar;
        }
    
    • 2,解決popupwindow在7.0以上機型設置居于view下方卻蓋在了view上面的問題
      if (Build.VERSION.SDK_INT < 24) {
                    popupWindow.showAsDropDown(v);
                } else {
                    int[] location = new int[2];
                    v.getLocationOnScreen(location);
                    int x = location[0];
                    int y = location[1];
                    popupWindow.showAtLocation(v, Gravity.NO_GRAVITY, 0, y + v.getHeight());
                }
    
    常見問題============ 一,androidstudio編譯相關

    1, Error while Installing APK

    解決方案:重新sync按鈕編譯下gradle就可以了

    2,出現Execution failed for task類的錯誤

    Error:Execution failed for task ‘:app:compileDebugJavaWithJavac’.
    Compilation failed; see the compiler error output for details.

    TaskExecutionException: Execution failed for task ‘:app:transformClassesWithAspectTransformForDebug’
    安卓開發常用知識點& 安卓開發常見問題及解決方案_安卓
    解決方案
    首先找到Execution failed for task,然后取到后面的如上面紅框里的信息
    在命令行執行
    ./gradlew app:transformDexArchiveWithExternalLibsDexMergerForDebug --stacktrace --info
    或者
    ./gradlew compileDebugJavaWithJavac --stackstrace
    執行完成以后,搜索‘錯誤’就可以看到具體錯誤原因了

    或者運行下面然后查看 Caused by的地方
    ./gradlew compileDebugSources --stacktrace -info

    3 Could not find support-media-compat.aar

    升級android studio到3.3版本,今天checkout到歷史tag上運行android項目,死活報錯
    之前也有同事遇到過類似的問題: Could not find support-media-compat.aar
    安卓開發常用知識點& 安卓開發常見問題及解決方案_編譯問題_02
    最后意外發現是google()倉庫位置的問題
    報錯配置:

    allprojects {
        repositories {
            flatDir {
                dirs 'libs'
            }
            jcenter()
            maven { url "https://jitpack.io" }
            maven { url "https://dl.bintray.com/thelasterstar/maven/" }
            maven {
                url "http://maven.aliyun.com/nexus/content/repositories/releases"
            }
            mavenCentral()
            google()
        }
        configurations.all {
            resolutionStrategy {
                force "com.android.support:appcompat-v7:$supportLibVersion"
            }
        }
    }
    

    把google()放到第一位即可

    allprojects {
        repositories {
            google()
            flatDir {
                dirs 'libs'
            }
            jcenter()
            maven { url "https://jitpack.io" }
            maven { url "https://dl.bintray.com/thelasterstar/maven/" }
            maven {
                url "http://maven.aliyun.com/nexus/content/repositories/releases"
            }
            mavenCentral()
        }
        configurations.all {
            resolutionStrategy {
                force "com.android.support:appcompat-v7:$supportLibVersion"
            }
        }
    }
    

    4,could not find com.android.support:appconpat 如下圖:

    安卓開發常用知識點& 安卓開發常見問題及解決方案_androidstudio_03
    需要在project的build.gradle中allprojects 添加如下配置即可,添加下面代碼到第一行。
    maven { url “https://maven.google.com” }

    安卓開發常用知識點& 安卓開發常見問題及解決方案_安卓常見問題_04

    5,報錯:Annotation processors must be explicitly declared now.

    在app的gradle文件中加入下面這句話:

    android {
        .....
        defaultConfig {
            ......
    	//在下面添加這句話,然后重新編譯,就OK了。
            javaCompileOptions { annotationProcessorOptions { includeCompileClasspath = true } }
        }
    

    持續更新中。。。

    ?

    本文摘自 :https://blog.51cto.com/u

    開通會員,享受整站包年服務
    国产呦精品一区二区三区网站|久久www免费人咸|精品无码人妻一区二区|久99久热只有精品国产15|中文字幕亚洲无线码