Android

Android SharedPreference

用来在应用中存储键值对配置

context.getSharedPreferences(“prefName”, Context.MODE_PRIVATE) get SharedPreferecnes instance
sharedPref.getXXX(“keyName”, defaultValue) get value from SharedPreferences
sharedPref.edit() get editor(SharedPreference.Editor)
editor.putXXX(“key-name”, value) put value
editor.commit() commit the changes

Android 连接 WiFi

https://stackoverflow.com/questions/4249911/android-how-to-create-eap-wifi-configuration-programmatically

redirects to

https://stackoverflow.com/questions/4374862/how-to-programmatically-create-and-read-wep-eap-wifi-configurations-in-android

https://stackoverflow.com/questions/19170260/how-to-connect-to-wpa-eap-wifi-on-android-with-4-3-api

Android 6.0 changes

https://developer.android.com/about/versions/marshmallow/android-6.0-changes.html#behavior-network

working methods

https://stackoverflow.com/questions/12486441/how-can-i-set-proxysettings-and-proxyproperties-on-android-wi-fi-connection-usin

get real ip https://stackoverflow.com/questions/39335525
connect to wifi https://stackoverflow.com/questions/8818290

android added support to eap wifi in API 18 (4.3), a lot of tutorials online are outdated.

use WifiEnterpiresConfiguration.

Android 开发的一些 tips

Prefer Maven dependency resolution instead of importing jar files. If you explicitly include jar files in your project, they will be of some specific frozen version, such as 2.1.1. Downloading jars and handling updates is cumbersome, this is a problem that Maven solves properly, and is also encouraged in Android Gradle builds. For example:

“`
dependencies {
compile ‘com.squareup.okhttp:okhttp:2.2.0’
compile ‘com.squareup.okhttp:okhttp-urlconnection:2.2.0’
}
“`

Use different package name for non-release builds Use applicationIdSuffix for debug build type to be able to install both debug and release apk on the same device (do this also for custom build types, if you need any). This will be especially valuable later on in the app’s lifecycle, after it has been published to the store.

“`
android {
buildTypes {
debug {
applicationIdSuffix ‘.debug’
versionNameSuffix ‘-DEBUG’
}
release {
// …
}
}
}
“`

Use different icons to distinguish the builds installed on a device—for example with different colors or an overlaid “debug” label. Gradle makes this very easy: with default project structure, simply put debug icon in app/src/debug/res and release icon in app/src/release/res. You could also change app name per build type, as well as versionName (as in the above example).

use stetho

不要在application中存储全局变量
尽量少使用globalobject,最好使用intent

Maven Basics

From: http://tutorials.jenkov.com/maven/maven-tutorial.html

# Introduction
Maven is built around the pom.xml file. In Maven, how to build your project is predefined in the Maven Build Life Cycles, Phases and Goals. The POM file describes *what to build*, but most often *not how to build it*. How to build it is up to the Maven build phases and goals.

# Minimal POM file
Here is a minimal POM file:


4.0.0
com.jenkov
java-web-crawler
1.0.0

this outputs MAVEN_REPO/com/jenkov/java-web-crawler/1.0.0/java-web-crawler-1.0.0.jar

# Super POM
You can make a POM file explicitly inherit from another POM file. That way you can change the settings across all inheriting POM’s via their common super POM. You specify the super POM at the top of a POM file like this:


4.0.0

org.codehaus.mojo
my-parent
2.0
../my-parent

my-project

mvn help:effective-pom shows the combined pom of parent and current

# Running Maven

When executing the mvn command you pass the name of a build life cycle, phase or goal to it, which Maven then executes.

syntax: mvn phase:goal

# Directory Structure
You must follow the maven directory structure

“`
– src
– main
– java
– resources
– webapp
– test
– java
– resources
– target
“`

more here: Introduction to the Maven Standard Directory Layout

# Dependencies

“`
4.0.0
com.jenkov.crawler
java-web-crawler
1.0.0



org.jsoup
jsoup
1.7.1


junit
junit
4.8.1
test


“`

## external dependencies

“`

mydependency
mydependency
system
1.0
${basedir}\war\WEB-INF\lib\mydependency.jar

“`

## snapshot dependencies

Snapshot dependencies are dependencies (JAR files) which are under development.

`1.0-SNAPSHOT`

# Repositories

maven tries to pull dependencies from local, central, and remote repo

## Local Repositores

it’s defined in ~/.m2/settings.xml



d:\data\java\products\maven\repository

## Central Repositories

Maintained by the maven community

## Remote Repositories

A remote repository is often used for hosting projects internal to your organization, which are shared by multiple projects.



jenkov.code
http://maven.jenkov.com/maven2/lib

# Maven Build Cycles

When Maven builds a software project it follows a build life cycle. The build life cycle is divided into build phases, and the build phases are divided into build goals.
Since you cannot execute the default life cycle directly, you need to execute a build phase or goal from the default life cycle.

1. default
validate Validates that the project is correct and all necessary information is available. This also makes sure the dependencies are downloaded.
compile Compiles the source code of the project.
test Runs the tests against the compiled source code using a suitable unit testing framework. These tests should not require the code be packaged or deployed.
package Packs the compiled code in its distributable format, such as a JAR.
install Install the package into the local repository, for use as a dependency in other projects locally.
deploy Copies the final package to the remote repository for sharing with other developers and projects.
2. clean
3. site

# Profiles

Profiles let you use differvent build settings

使用 Gson 解析 json 文档

解析 json 有两种流派:

1. event-driven json parse: iterate the document, not loading all into memory
2. document-based json parse: load the full document into memory once for all.

在 Python 中可以很容易的解析json文件,Python 中的 json.loads 是 document-based。而在 java 中可以使用 event-driven的。个人感觉这种 event-driven 的解析方式是多此一举,json本来定位就是小型的数据传输和配置存储,如果生成了一个很大的 json,应该考虑换用xml了。

在 Java 中需要生成和 JSON 文档意义对应的 JavaBean 文件,这样才能解析到 Java Class。

把你的 json 文件的例子首先编写好,然后可以通过这个网站生成 JavaBean:http://www.jsonschema2pojo.org/

![](https://ws2.sinaimg.cn/large/0069RVTdly1fu2lsahbklj31880ni77y.jpg)

在 Android Studio build.gradle 文件中添加依赖:

“`
dependencies {
compile ‘com.google.code.gson:gson:2.3.1’
}
“`

解析

“`
package com.example;

import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Example {

@SerializedName(“foo”)
@Expose
private String foo;

public String getFoo() {
return foo;
}

public void setFoo(String foo) {
this.foo = foo;
}

}
“`

“`
Gson gson = new Gson();

String json = “{\”foo\”: \”bar\”}”;
Example example = gson.fromJson(json, Example.class);
// 解析:JavaBean对象 = gson.fromJson(json, JavaBean.class);
“`

参考资料:

1. http://www.jianshu.com/p/b87fee2f7a23

安卓证书与代理自动配置

Go to Settings > Security > Install from storage.

install programatically can be achived by from command line, by moving certs to

replacing bks file solely is useless, it has to be combined with the password

https://github.com/danzeeeman/meerkat-decompiled/blob/master/io/fabric/sdk/android/services/network/PinningInfoProvider.java

set proxy programatically

1. set mannully for one
2. pull /data/misc/wifi/ipconfig.txt
3. push to other devices

如何安装证书

make certs like this tutorial, http://forum.xda-developers.com/google-nexus-5/help/howto-install-custom-cert-network-t2533550
but push it to /data/misc/user/0/cacerts-added/

安卓开发中的Context

在安卓当中,Context几乎是无处不在的,每一个Activity是一个Context,每一个Service也是一个Context。

但是如果你新起了一个线程的话,你需要显式地把Context传递进去。

比如下面的例子:

“`
public class DumpLocationLog extends Thread {
LocationManager lm;
LocationHelper loc;
public DumpLocationLog(Context context) {
loc = new LocationHelper();
lm = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
}
public void run() {
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000L, 500.0f, loc);
}
}
“`

然后使用这个线程的时候,把this,也就是一个context的实例传递进去

`new DumpLocationLog(this);`

if you are in a fragment, use getAcitvity()

if you are in an anoynmous onclicklistener, `this` is MainActivity.this

为安卓编译64位的dropbear

## 如何使用dropbear

这里主要是需要在安卓上生成 host key,以及把自己的公钥传到安卓上

“`
dropbearkey -t rsa -f /data/local/dropbear_host_key # 在安卓上生成key
adb push ~/.ssh/id_rsa.pub /data/local/authorized_keys # 在宿主机把自己的密钥传过去
dropbear -F -E -r /data/local/dropbear_host_key -A -N root -C jk -R /data/local/authorized_keys # 按照给定的key启动dropbear
dropbear -P /data/local/dropbear.pid -r /data/local/dropbear_host_key -A -N root -C jk -R /data/local/authorized_keys # 以daemon形式启动dropbear
“`

## 如何为64位的安卓机器编译 dropbear

需要更改如下代码(svr-chansession.c):

“`
addnewvar(“LD_LIBRARY_PATH”, “/system/lib”);

to:

addnewvar(“LD_LIBRARY_PATH”, “/system/lib64”);
“`

## 使用AIL把dropbear添加为服务

“`
service sshd /system/xbin/dropbear -s
user root
group root
oneshot
“`
试过了,但是没有成功

## 如何重启adb(wifi)

“`
setprop service.adb.tcp.port 5555
stop adbd
start adbd
“`

# 关闭 ssh key 验证

“`
Host *
StrictHostKeyChecking no
“`

mount -o remount,rw /system

参考

1. http://forum.xda-developers.com/nexus-7-2013/general/guide-compiling-dropbear-2016-73-t3351671
2. http://forum.xda-developers.com/nexus-7-2013/general/guide-compiling-dropbear-2015-67-t3142412/page3

安卓的 AsyncTask

asynchronusally run task without explicitly creating thread.

# Usage

“`
doInBackground(Params…)
onProgressUpdate(Progress…)
onPostExecute(Result)
“`

Here is an example of subclassing:

“`
 private class DownloadFilesTask extends AsyncTask {
     protected Long doInBackground(URL… urls) {
         int count = urls.length;
         long totalSize = 0;
         for (int i = 0; i < count; i++) {              totalSize += Downloader.downloadFile(urls[i]);              publishProgress((int) ((i / (float) count) * 100));              // Escape early if cancel() is called              if (isCancelled()) break;          }          return totalSize;      }      protected void onProgressUpdate(Integer... progress) {          setProgressPercent(progress[0]);      }      protected void onPostExecute(Long result) {          showDialog("Downloaded " + result + " bytes");      }  } ```   Once created, a task is executed very simply: ``` new DownloadFilesTask().execute(url1, url2, url3); ``` template parameters can be `Void, Void, Void` see https://developer.android.com/reference/android/os/AsyncTask.html

android public key pinning

# What is public key pinning?

to view https traffic, you could sign your own root CA, and perform mitm attack to view the traffic. HPKP (http public key pinning) stops this sniffing by only trust given CA, thus, your self-signed certs will be invalid. To let given app to trust your certs, you will have to modify the apk file.

# How to break it?
## Introducing Xposed

decompile, modify and then recompile the apk file can be very diffcult. so you’d better hook to some api to let the app you trying to intercept trust your certs. xposed offers this kind of ability. moreover, a xposed module called JustTrustMe have done the tedious work for you. just install xposed and JustTrustMe and you are off to go. Here are the detaild steps:

1. Install Xposed Installer

for android 5.0 above, use the xposed installer.

NOTE: 对于 MIUI,需要搜索 Xposed 安装器 MIUI 专版。

2. Install Xposed from xposed installer, note, you have to give root privilege to xposed installer

3. Install JustTrustMe