Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
 Android教程網 >> Android技術 >> Android開發 >> 關於android開發 >> android開發中遇到的問題匯總【九】

android開發中遇到的問題匯總【九】

編輯:關於android開發

android開發中遇到的問題匯總【九】


244.http請求的url含有中字符時,需要Uri編碼。Uri.encoder()

245.使用androidstudio時,不知道什麼原因svn不見了

Android Studio missing Subversion plugin

Please make sure that the “SubversionIntegration” plugin is enabled in Preferences > Plugins

246.Error:Execution failed for task ‘:app:dexDebug’.> com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process ‘command ‘/home/xxx/tools/android/jdk1.7.0_71/bin/java” finished with non-zero exit value 2

檢查下是否多次引用同一個jar包
以下情況
1. module下jar包版本不同

同一個module 在libs中包含樂.jar,而在src下又把相應的source頁加入了

gradle中是否重復編譯,

比如
已經加了compile fileTree(include: [‘*.jar’], dir: ‘libs’)
然而在下面又加一句compile files(‘libs/xxx.jar’)

參考 Error:Execution failed for task ‘:app:dexDebug’. com.android.ide.common.process.ProcessException

246.android handler的警告Handler Class Should be Static or Leaks Occur

在使用Handler更新UI的時候public class SampleActivity extends Activity {

private final Handler mLeakyHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO
}
}
}會包上述warning 會導致內存洩露
原因在於匿名內部類handler持有activity的引用,當activity finish後 handler還沒有處理完,導致activity的view和resource資源不能得到釋放,導致內存洩露
針對這個問題google官方給出了正確的做法
通過靜態內部類 包含activity的弱引用來處理。
public class SampleActivity extends Activity {

/**
* Instances of static inner classes do not hold an implicit
* reference to their outer class.
*/
private static class MyHandler extends Handler {
private final WeakReference mActivity;

public MyHandler(SampleActivity activity) {
  mActivity = new WeakReference(activity);
}

@Override
public void handleMessage(Message msg) {
  SampleActivity activity = mActivity.get();
  if (activity != null) {
    // ...
  }
}

}

private final MyHandler mHandler = new MyHandler(this);

/**
* Instances of anonymous classes do not hold an implicit
* reference to their outer class when they are “static”.
*/
private static final Runnable sRunnable = new Runnable() {
@Override
public void run() { }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

// Post a message and delay its execution for 10 minutes.
mHandler.postDelayed(sRunnable, 60 * 10 * 1000);

// Go back to the previous Activity.
finish();

}
}

參考android handler的警告Handler Class Should be Static or Leaks Occur

247.androidstudio不同tab切換 ctrl+tab

248.androidstudio 如何自動import用到的類或接口?

For Windows/Linux, you can go to File -> Settings -> Editor -> General -> Auto Import -> Java and make the following changes:

change Insert imports on paste value to All

markAdd unambigious imports on the fly option as checked
On a Mac, do the same thing in Android Studio -> Preferences

參考What is the shortcut to Auto import all in Android Studio?

249.Android NDK: Could not find application project directory ! Android NDK: Please define the NDK_PROJECT_PATH variable to point to it.

/home/cenuser/android/android-ndk-r7b/build/core/build-local.mk:130: *** Android NDK: Aborting    .  Stop.

cd到jni目錄。或者 ndk-build -C your_project_path

250 .Why do I want to avoid non-default constructors in fragments? fragment設置參數正確的做法

Make a bundle object and insert your data (in this example your Category object). Be careful, you can't pass this object directly into the bundle, unless it's serializable. I think it's better to build your object in the fragment, and put only an id or something else into bundle. This is the code to create and attach a bundle:

Bundle args = new Bundle();
args.putLong("key", value);
yourFragment.setArguments(args);
After that, in your fragment access data:

Type value = getArguments().getType("key");
That's all.

251. ubuntu下刪除.svn的方法

find -type d -name '.svn' -exec rm -rfv {} \;

參考 http://blog.csdn.net/zhaoyu7777777/article/details/9445717

252. Fatal : Could not read from remote repository.

git配置使用,已經把公鑰發給發給服務端,在終端命令行也是可以正常的pull push,但是在androidstudio push或者pull的時候確出現上述錯誤
解決方式
setting –> Version Control –>Git ,In the SSH executable dropdown, choose Native

253. ubuntu獲取證書指紋的命令

keytool -list -keystore xxx.keystore
eg:查看debug.keystore
keytool -list -keystore ~/.android/debug.keystore

254. mac 命令行安裝軟件

通過brew安裝,相當於ubuntu中得apt-get
首先安裝brew
curl -LsSf http://github.com/mxcl/homebrew/tarball/master | sudo tar xvz -C/usr/local –strip 1
然後就可以使用brew安裝軟件了
比如 使用brew安裝軟件 brew install wget

255.代碼混淆時 報如下錯誤 Error:Execution failed for task ‘:app:proguarxxxRelease’.

java.io.IOException: Can’t read [/libs/xxx.jar] (No such file or directory)
http://stackoverflow.com/questions/26028171/android-studio-proguard-java-io-ioexception-bin-classes-no-such-file-or-d

解答 proguard-android.txt文件中不用在指定 -injars, -outjars, or -libraryjars or libs.

The Android Gradle plugin already specifies all input and output for you, so you must not specify -injars, -outjars, or -libraryjars.

Moreover, the file proguard-android.txt in the Android SDK specifies all generic Android settings for you, so you shouldn’t specify them again.

Essentially, your file proguard-rules.txt can be empty, except for any application-specific settings to make sure any reflection continues to work

256.Android中如何設置RadioButton在文字的右邊,圖標在左邊

解決方法 :
第一步:
android:button=”@null”這條語句將原來系統的RadioButton圖標給隱藏起來。
第二步:
android:drawableRight=”@android:drawable/btn_radio”這條語句
參考 http://blog.csdn.net/sunnyfans/article/details/7901592

257.java報“非法字符: \65279 ”錯誤的解決方法

眾所周知,在跨程序的工程中,統一編碼是至關重要的,而目前最普遍的則是統一采用“utf8”編碼方案。
但是在采用utf8方案的時候,請注意編輯器的自作聰明。
比如editplus。
原因就在於某些編輯器會往utf8文件中添加utf8標記(editplus稱其為簽名),它會在文件開始的地方插入三個不可見的字符(0xEF 0xBB 0xBF,即BOM),它的表示的是 Unicode 標記(BOM)。
參考 http://hyl198611.iteye.com/blog/1336981

258.手機root後 還會出現下述情況Android: adb: copy file to /system (Permission denied)

解決方式,需要remount /system
mount -o remount,rw /system

259.androidstudio 手動添加assets文件 路徑在哪

XXX\src\main\assets  

260.android雙擊back退出

public class MainActivity extends Activity {


    private Toast toast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toast = Toast.makeText(getApplicationContext(), "確定退出?", 0);

    }
    public void onBackPressed() {
        quitToast();
    }

    private void quitToast() {
        if(null == toast.getView().getParent()){
            toast.show();
        }else{
            System.exit(0);
        }
    }
}

或者

private Toast toast;
 protected void onCreate(Bundle savedInstanceState) {
    ...
         toast = Toast.makeText(this, "再按一次退出應用", Toast.LENGTH_SHORT);
        toast.setGravity(Gravity.BOTTOM, 0, ConversionUtil.dip2px(this, 150));
 }
@Override 
public void onBackPressed() { 
    if (doubleBackToExitPressedOnce) { 
        if(toast!=null){
            toast.cancel();
        }
        super.onBackPressed(); 
        return; 
    } 

    this.doubleBackToExitPressedOnce = true;
    toast.show();

    new Handler().postDelayed(new Runnable() {

        @Override 
        public void run() { 
            doubleBackToExitPressedOnce=false;                        
        } 
    }, 2000); 
}  

參考 Android關於雙擊退出應用的問題

261.anroid幾個很不錯的快捷鍵

Ctrl+Shift+Alt+T 重構代碼 change name Ctrl+I 水平分屏顯示【需要在keymap中搜索split 設置move right的快捷鍵】 shift+alt+L 變量生成 ctrl+shift+v

262.在舊項目中引入android materialdesign 時 出現如下問題

android.view.InflateException: Binary XML file line #17: Error inflating class android.support.design.internal.NavigationMenuView
Caused by: java.lang.reflect.InvocationTargetException
Caused by: android.content.res.Resources$NotFoundException: Resource is not a Drawable (color or path): TypedValue{t=0x2/d=0x7f0100c5 a=-1}
You need to use a Theme.AppCompat theme (or descendant) with this activity.

解決方法 :使用NavigationMenuView的Activity【一般都是mainActivity】繼承自AppCompatActivity,並且修改AndroidManifest.xml中對應activity的theme,使用繼承自@style/Theme.AppCompat的主題。

262.How to get key and value of HashMap in java

public class AccessKeyValueOfHashMap {
        public static void main(String[] args) {
                // Create a Empty HashMap 
                HashMap obHashMap = new HashMap();
                // Put values in hash map
                obHashMap.put("AB", "1");
                obHashMap.put("EF", "2");
                obHashMap.put("Gh", "3");
                obHashMap.put("CD", "4");
                //Store entry (Key/Value)of HashMap in set
                Set mapSet = (Set) obHashMap.entrySet();
                //Create iterator on Set 
                Iterator mapIterator = mapSet.iterator();
                System.out.println("Display the key/value of HashMap.");
                while (mapIterator.hasNext()) {
                        Map.Entry mapEntry = (Map.Entry) mapIterator.next();
                        // getKey Method of HashMap access a key of map
                        String keyValue = (String) mapEntry.getKey();
                        //getValue method returns corresponding key's value
                        String value = (String) mapEntry.getValue();
                        System.out.println("Key : " + keyValue + "= Value : " + value);
                }
        }
}

263. 設置鍵盤回車為發送建

        android:imeOptions="actionSend"
        android:inputType="text"

264. editText 取消背景格式 取消下劃線等自帶樣式

去掉下劃線只需把背景設置成為“@null”,
如果想設為其他樣式也是設置背景

265. How to build an .so binary for a device with a 64-bit CPU?

latest version of the NDK (right now it's r10e)
Application.mk
APP_ABI := armeabi arm64-v8a armeabi-v7a x86 mips

266. Android NDK for x86_64 has no reference for bcopy and index

You can fix this cleanly with a single line in Application.mk (docs):

APP_CFLAGS += -DSTDC_HEADERS

267.Error:Execution failed for task ‘:xxx:processDebugManifest’. > Manifest merger failed : uses-sdk element cannot have a “tools:node” attribute

This has been updated to reflect the release of API 21, Lollipop. Be sure to download the latest SDK.

In one of my modules I had the following in build.gradle:

dependencies {
    compile 'com.android.support:support-v4:+'
}
Changing this to

dependencies {
    // do not use dynamic updating.
    compile 'com.android.support:support-v4:21.0.0' 
}
fixed the issue.

參考Manifest merger failed : uses-sdk:minSdkVersion 14

268.Error:(1, 1) A problem occurred evaluating project ‘xxx’. > Could not create plugin of type ‘LibraryPlugin’.

修改了build.gradle中的gradle
也要修改gradle-wrapper.properties
例如:

build.gradle
  dependencies {
        classpath 'com.android.tools.build:gradle:1.2.3'
    }
    gradle-wrapper.properties
  distributionUrl=https\://services.gradle.org/distributions/gradle-2.4-all.zip

269.androidstudio Building Apps with Over 65K Methods

android {
    compileSdkVersion 21
    buildToolsVersion "21.1.0"

    defaultConfig {
        ...
        minSdkVersion 14
        targetSdkVersion 21
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.0'
}

270.Caused by: java.lang.NoClassDefFoundError: android.support.v4.util.Pools$SimplePool

http://stackoverflow.com/questions/25477860/error-inflating-class-android-support-v7-widget-recyclerview

271.Caused by: java.lang.NoSuchMethodException: [class android.content.Context, interface android.util.AttributeSet]

http://stackoverflow.com/questions/11753719/how-do-i-properly-extend-a-layout-class

272.java.lang.IndexOutOfBoundsException: Inconsistency detected. Invalid view holder adapter positionViewHolder{423a4c60 position=4 id=-1, oldPos=1, pLpos:1 scrap tmpDetached not recyclable(1) no parent}

273.Failure [INSTALL_PARSE_FAILED_MANIFEST_MALFORMED]

http://stackoverflow.com/questions/6056564/installation-error-install-parse-failed-manifest-malformed
I was having this error because i had capital letters in my package name like this

Com.Example.packagename
after i had changed it to something like

com.example.packagename
it was solved

273.解決異常Circular dependencies cannot exist in RelativeLayout

RelativeLayout中存在循環的相關

274.java.lang.ClassNotFoundException 使用MultiDex 後,運行時發現有些crash或者有些類無法調用 報NoClassDefFound error

首先正確使用 google的multipartdex

修改Gradle,導入’com.android.support:multidex:1.0.0’,打開multiDexEnabled;
android {
    compileSdkVersion 21
    buildToolsVersion "21.1.0"

    defaultConfig {
        ...
        minSdkVersion 14
        targetSdkVersion 21
        ...

        // Enabling multidex support.
        multiDexEnabled true
    }
    ...
}

dependencies {
  compile 'com.android.support:multidex:1.0.0'
}

修改Application.兩種方法:

1) 直接把Application替換成MultiDexApplication



    
        ...
    

2) 在原來的Application中修改調用MultiDex.install(this);

public class HelloMultiDexApplication extends Application {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }
}

如果做了上面處理,依舊NoClassDefFound error 通過如下方式處理:
一些在二級Dex加載之前,可能會被調用到的類(比如靜態變量的類),需要放在主Dex中.否則會ClassNotFoundError.
通過修改Gradle,可以顯式的把一些類放在Main Dex中.

參考Android 分Dex (MultiDex)

275.Linux 32 Bit Libraries

sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1

276.Android Material Design TabLayout.when more than screen width scroll when less than screen width fill

Android TabLayout,當tab總寬度少於一屏時候,擴展為屏幕寬度展示.當tab總寬度大於一屏時,滾動顯示

Tab gravity only effects MODE_FIXED.

One possible solution is to set your layout_width to wrap_content and layout_gravity to center_horizontal:


If the tabs are smaller than the screen width, the TabLayout itself will also be smaller and it will be centered because of the gravity. If the tabs are bigger than the screen width, the TabLayout will match the screen width and scrolling will activate.

參考Android Support Design TabLayout: Gravity Center and Mode Scrollable

277. android多渠道打包

目前采用的方案是,在AndroidManifest.xml文件中配置

在app的build.gradle文件中配置

android{
 //用於生成不同渠道號
    productFlavors {
        wandoujia {}
        baidu {}
        yingyongbao{}
        ...

    }

    productFlavors.all {
        flavor -> flavor.manifestPlaceholders = [UMENG_CHANNEL_VALUE: name]
    }

}

這樣編譯時會生成對應的渠道包apk.現在問題來了,如果有幾十個渠道,會生成對應幾十個apk包.打包編譯一個apk一般需要1分鐘左右(和電腦配置有關).那麼打包幾十個要幾十分鐘的時間.確實挺費時間的.那麼有沒有好的方式吶?
當然是有的
我們可以采用如下方案處理.通過文件配置只需要生成一個apk包

此種方法是需要創建文件的。
我們在寫完我們的代碼之後,在app/src下面,分別創建和main同級目錄的文件夾umeng, wandoujia, yingyongbao,這三個文件夾裡面都各只有一個AndroidManifest.xml文件,文件只需要如下:
[plain] view plain copy 在CODE上查看代碼片派生到我的代碼片
  
      

            

      
  
注意,上面的value的值要和你的渠道名所對應。比如wandoujia裡面要對應為你豌豆莢上的渠道名(如WANDOUJAI)。
然後在你的build.gradle的android{}節點裡面,添加productFlavors節點,代碼如下:
[plain] view plain copy 在CODE上查看代碼片派生到我的代碼片
android {  
    // 這裡是你的其他配置  

    productFlavors{  
        umeng{  }  
        wandoujai {  }  
        yingyongbao{  }  
    }  
    // 你的其他配置  
}  
注意這裡的flavors的名字要和你的文件夾的名字對應。這樣配置之後,構建的就是多渠道的APK了。

 

278 Tcpdump抓包

有些模擬器比如genymotion自帶了tcpdump,如果沒有的話,需要下載tcpdump:
http://www.strazzere.com/android/tcpdump

把tcpdump push到/data/local下,抓包命令:

Linux抓包工具tcpdump詳解

279 查看簽名

很多開發者服務都需要綁定簽名信息,用下面的命令可以查看簽名:

keytool -list -v -keystore release.jks

280 系統日志中幾個重要的TAG

\

281 一行居中,多行居左的TextView

這個一般用於提示信息對話框,如果文字是一行就居中,多行就居左。
在TextView外套一層wrap_content的ViewGroup即可簡單實現:

\

282 setCompoundDrawablesWithIntrinsicBounds()

網上一大堆setCompoundDrawables()方法無效不顯示的問題,然後解決方法是setBounds,需要計算大小…

不用這麼麻煩,用setCompoundDrawablesWithIntrinsicBounds()這個方法最簡單!

282 更新媒體庫文件

以前做ROM的時候經常碰到一些第三方軟件(某音樂APP)下載了新文件或刪除文件之後,但是媒體庫並沒有更新,因為這個是需要第三方軟件主動觸發。

\

283 Monkey參數

大家都知道,跑monkey的參數設置有一些要注意的地方,比如太快了不行不切實際,太慢了也不行等等,這裡給出一個參考:

一邊跑monkey,一遍抓log吧。

\

284 強大的dumpsys

dumpsys可以查看系統服務和狀態,非常強大,可通過如下查看所有支持的子命令:

\

這裡列舉幾個稍微常用的:

媒體庫會在手機啟動,SD卡插拔的情況下進行全盤掃描,不是實時的而且代價比較大,所以單個文件的刷新很有必要。

注[278-284來源於] 
你應該知道的那些Android小經驗

285. 在布局文件時,在xml可視化文件中看到效果,而又不影響最終展示.可以通過tools來協助

比如:

<code class="language-java hljs "><!--{cke_protected}{C}%3C!%2D%2D%3Fxml%20version%3D%221.0%22%20encoding%3D%22utf-8%22%3F%2D%2D%3E-->
<relativelayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/rootView" android:layout_width="match_parent" android:layout_height="match_parent" android:gravity="center">

    <progressbar android:id="@+id/progress_loading" android:layout_width="75dp" android:layout_height="60dp">

    <textview android:id="@+id/tv_reload" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/transparent" android:src="@drawable/refresh_big" android:scaletype="centerInside" android:visibility="gone" tools:text="點我,重新加載" tools:visibility="visible">
</textview></progressbar></relativelayout>
</code>

加填充xml文件時,TextView是隱藏的,但又想在xml中直觀的看到它顯示後的整體效果.借助xmlns:tools=”http://schemas.android.com/tools” 完美實現.

參考android中xml tools屬性詳解

286. android studio對於錯誤拼寫/不識別的英文單詞,給予波浪提示。

Spellchecker inspection helps locate typos and misspelling in your code, comments and literals, and fix them in one click
android studio對於錯誤拼寫/不識別的英文單詞,給予波浪提示
選中單詞,單擊鼠標右鍵 spelling
Save ‘xxx’ to dictionary..

287. Warning: Use ‘′insteadof′.′forinnerclasses(oruseonlylowercaselettersinpackagenames);replace.with

Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
包名小寫,避免和類名或接口名沖突

288. JNI undefined reference to `__android_log_print’

android {
    defaultConfig {
        ndk {
            moduleName "your_module_name"
            ldLibs "log"
        }
    }
}

  1. 上一頁:
  2. 下一頁:
熱門文章
閱讀排行版
Copyright © Android教程網 All Rights Reserved