android开发中遇到的问题汇总

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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包版本号不同

  1. 同一个module 在libs中包括乐.jar,而在src下又把相应的source页加入了

  2. 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<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开发遇到问题点滴





































































以上是关于android开发中遇到的问题汇总的主要内容,如果未能解决你的问题,请参考以下文章

android开发中遇到的问题汇总

Android开发错误——Android Studio中遇到过的错误问题与解决方案汇总

Android开发错误——Android Studio中遇到过的错误问题与解决方案汇总

Android开发细节——上班实战项目中遇到的棘手问题与解决方案汇总

Android开发细节——上班实战项目中遇到的棘手问题与解决方案汇总

Android开发细节——上班实战项目中遇到的棘手问题与解决方案汇总