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

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

245.使用androidstudio時,不知道什麼緣由svn不見了

Android Studio missing Subversion pluginhtml

Please make sure that the 「SubversionIntegration」 plugin is enabled in Preferences > Pluginsjava

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包版本號不一樣node

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

  2. gradle中是否反覆編譯,android

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

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

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

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

private final Handler mLeakyHandler = new Handler() {
@Override
public void handleMessage(Message msg) {
// TODO
}
}
}會包上述warning 會致使內存泄露
緣由在於匿名內部類handler持有activity的引用。當activity finish後 handler尚未處理完。致使activity的view和resource資源不能獲得釋放。致使內存泄露
針對這個問題google官方給出了正確的作法
經過靜態內部類 包括activity的弱引用來處理。ubuntu


public class SampleActivity extends Activity {segmentfault

/**
* 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<SampleActivity>(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幾個很是不錯的快捷鍵

  1. Ctrl+Shift+Alt+T 重構代碼 change name
  2. Ctrl+I 水平分屏顯示【需要在keymap中搜索split 設置move right的快捷鍵】
  3. shift+alt+L 變量生成
  4. 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<String, String> obHashMap = new HashMap<String, String>();
                // 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

  1. 改動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'
}
  1. 改動Application.兩種方法:

    1) 直接把Application替換成MultiDexApplication

<?

xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.android.multidex.myapplication"> <application ... android:name="android.support.multidex.MultiDexApplication"> ... </application> </manifest>

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:

<android.support.design.widget.TabLayout
    android:id="@+id/sliding_tabs"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_horizontal"
    app:tabMode="scrollable" />
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文件裏配置

<meta-data
            android:name="UMENG_CHANNEL"
            android:value="${UMENG_CHANNEL_VALUE}" />

在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上查看代碼片派生到個人代碼片 <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="your.package.name"> <application> <meta-data android:name="UMENG_CHANNEL" android:value="UMENG"/> </application> </manifest> 注意。上面的value的值要和你的渠道名所相應。比方wandoujia裏面要相應爲你豌豆莢上的渠道名(如WANDOUJAI)。

而後在你的build.gradle的android{}節點裏面,加入productFlavors節點,代碼例如如下: [plain] view plain copy 在CODE上查看代碼片派生到個人代碼片 android { // 這裏是你的其它配置 productFlavors{ umeng{ } wandoujai { } yingyongbao{ } } // 你的其它配置 } 注意這裏的flavors的名字要和你的目錄的名字相應。這樣配置以後。構建的就是多渠道的APK了。

參考
Gradle實現的兩種簡單的多渠道打包方法

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來協助

比方:

<?xml version="1.0" encoding="utf-8"?>
<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"/>
</RelativeLayout>

加填充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"
        }
    }
}

參考undefined reference to `__android_log_print’

不少其它問題請關注 android開發遇到問題點滴

相關文章
相關標籤/搜索