Android misc

 

Android三种实现定时器的方法

 

From<http://blog.csdn.net/yhm2046/article/details/8213629>

 

 

 

Android application main activity 谁先启动?

 

 

 

Application contextActivitycontext的区别

ApplicationContext只针对整个应用,而Activity 中的Context针对不同的Activity,也就是说,Application Context是户口本影响全局,Activity 中的Context是户口本中每个人的身份证影响单个人 ,范围不同

 

 

 

Android Context

Context不是函数而是一个类,Context的对象储存关于程序、窗口的一些资源。

 

 

Android  Service 两种启动方式

http://www.cnblogs.com/yejiurui/p/3429451.html

 

 

 

Android 四大组件

http://www.cnblogs.com/bravestarrhu/archive/2012/05/02/2479461.html

 

 

 

WakefulBroadcastReceiver

startWakefulService

IntentService

BroadcastReceiver :

  • It is not guaranteed that CPU will stay awake if you initiate some long running process. CPU may go immediately back to sleep.

WakefulBroadcastReceiver :

  • It is guaranteed that CPU will stay awake until you fire completeWakefulIntent.

Example:

 

From<http://stackoverflow.com/questions/26380534/broadcastreceiver-vs-wakefulbroadcastreceiver>

 

 

 

Android onCreate or onStartCommandfor starting service

onCreate()is called when the Service object is instantiated (ie: when the service iscreated). You should do things in this method that you need to do only once(ie: initialize some variables, etc.). onCreate() will only ever be called onceper instantiated object.

 

You onlyneed to implement onCreate() if you actually want/need to initialize somethingonly once.

 

onStartCommand()is called every time a client starts the service using startService(Intentintent). This means that onStartCommand() can get called multiple times. Youshould do the things in this method that are needed each time a client requestssomething from your service. This depends a lot on what your service does andhow it communicates with the clients (and vice-versa).

 

If youdon't implement onStartCommand() then you won't be able to get any informationfrom the Intent that the client passes to onStartCommand() and your servicemight not be able to do any useful work.

 

 

 

Android Web View

 

shouldOverrideUrlLoading(拦截url加载,除资源请求的url) shouldInterceptRequest(拦截所有url请求)

 

What's the difference betweensetWebViewClient vs. setWebChromeClient?

UsingWebChromeClient allows you to handle Javascript dialogs, favicons, titles, andthe progress. Take a look of this example: Adding alert() support to a WebView

 

At first glance,there are too many differences WebViewClient & WebChromeClient. But,basically: if you are developing a WebView that won't require too many featuresbut rendering HTML, you can just use a WebViewClient. On the other hand, if youwant to (for instance) load the favicon of the page you are rendering, youshould use a WebChromeClient object and override the onReceivedIcon(WebViewview, Bitmap icon).

 

Most of the times,if you don't want to worry about those things... you can just do this:

 

webView= (WebView)findViewById(R.id.webview);

webView.setWebChromeClient(newWebChromeClient());

webView.setWebViewClient(newWebViewClient());

webView.getSettings().setJavaScriptEnabled(true);

webView.loadUrl(url);

And your WebViewwill (in theory) have all features implemented (as the android native browser).

 

 

WebView的设计中,不是什么事都要WebView类干的,有些杂事是分给其他人的,这样WebView专心干好自己的解析、渲染工作就行了。WebViewClient就是帮助WebView处理各种通知、请求事件的,具体来说包括:

 

 

如果您在编写HTML5应用,需要在JS代码中访问Java中的函数,则您会用到WebViewaddJavascriptInterface()函数。因为安全问题,在Android4.2(如果应用的android:targetSdkVersion数值为17+)JS只能访问带有 @JavascriptInterface注解的Java函数。

 

之前,任何Public的函数都可以在JS代码中访问,而Java对象继承关系会导致很多Public的函数都可以在JS中访问,其中一个重要的函数就是  getClass()。然后JS可以通过反射来访问其他一些内容。通过引入 @JavascriptInterface注解,则在JS中只能访问 @JavascriptInterface注解的函数。这样就可以增强安全性。

 

如果您的应用android:targetSdkVersion数值为17或者大于17记得添加@JavascriptInterface 注解

 

 

 

Android WebKit version

http://jimbergman.net/webkit-version-in-android-version/

 

Use this website tocheck you android phone's webkit version:

http://gs.statcounter.com/detect

Thumbnail

 

Android4.0 -> 4.3 webkit version are 534.30, after my write two black div html and use android origin web broswerto do experiment, webkit 543.30 doesn't support " width=device width,  minimum-scale=0.5, initial-scale=0.5, maximum-scale=0.5", this is html5 element

 

 

try using thismethod of WebSetting class

setUseWideViewPort(boolean use)

I use this to tellAndroid webview to consider my "viewport" tag,

// during my experiment I use the system default webbrowser, doesn't do any setting, does it by default accept viewport?  The default is false. From android dev docs

 

After use coa with setUseWideViewPort (true) webSettings.setLoadWithOverviewMode(true), hacked to open my blackdiv  the initial-scale still doesn't work

After use a new webview hello world also doesn't work

 

Some one confirmed

http://stackoverflow.com/questions/24636515/android-4-1-viewport-scaling-setinitialscale-meta-initial-scale-not-working

 

Solution

http://stackoverflow.com/questions/24636515/android-4-1-viewport-scaling-setinitialscale-meta-initial-scale-not-working

 

CSS issue

Usea snip code substitute jquery document ready

Documents.ready(document.body.style.zoom = 0.75)

 

           use js to set the width as thedevice width

 

 

Android 4.4 make abig progress use 536  and it's just thesame as chrome rendering engine, so now android origin webview will has thesame effect as android chrome

 

 

 

 

 

 

 

 

Android 页面布局initial-scale

http://www.wufangbo.com/mobile-browser-viewport/

http://www.cnblogs.com/2050/p/3877280.html

 

一种是把网页缩放到很小,你可以看到整个网页但是看不清字了;或者只看网页的一个局部,然后上下左右移动来看其他部分。现在的手机浏览器把两种模式结合使用

 

简单来说,就是手机浏览器把自己冒充为拥有一个更宽的屏幕,这样页面的布局就能跟桌面浏览器一样了。不同浏览器冒充的数值不一样:iPhone是神奇的980——960它表弟;Android是保守的800——冒充一个800*600的显示器;而Windows Phone 7则是1024——冒充一个1024*768的显示器(充分体现微软的庸俗特质)。

 

自己总结: Viewport width height 就相当于告诉原网页的作者,现在我正在用一个宽 width height "浏览器"去打开你的页面,(大部分网页制作者都会保证自己网页的宽和浏览器的宽一样,所以现在我们希望作者页面的宽和我们"浏览器"的宽一样)  width height 的单位是 电脑像素px = 物理像素px   但是手机像素px 不等于 物理像素, 因为手机分辨率高, 手机像素px 精细度高很多

 

 

所以如果安卓没有 <meta viewport> 就会默认当成一个  900 px * 900px的页面 (姑且将px当成一个物理单位) 但手机宽度只有320px 就会出现横向条

 

 

其实无论电脑,手机,人的肉眼希望看的是几乎统一的物理大小相同的文字和图片(手机可能就稍微小那么一点儿)

 

 

 

webview.setInitialScale(75);

//give a screenshotof origin page, then show the 75% of this page.  

//no layout change,all the layout like title words still too big and switch to a new line.   Doesn't get the effect as   <meta initial-scale>

 

 

 

Android version
http://socialcompare.com/en/comparison/android-versions-comparison

 

 

 

按Home键后,当前Activity会进入神马状态

onpause()->onstop()   所以再进来就会重新开始生命周期了 进入main activity,

当你按下手机的Home键的时候,系统会默认调用程序栈中最上层Activity的stop()方法,然后整个应用程序都会被隐藏起来,当你再次点击手机桌面上应用程序图标时,系统会调用最上层Activity的OnResume()方法,此时不会重新打开程序,而是直接进入,会直接显示程序栈中最上层的Activity

 

 

 

Android windows 差别

Android 组件的生死不由自己控制(系统会回收控制), windows 用户点了叉才会关闭

Android 都是全屏的 (除了alert, dialog)windows可以控制窗口大小

Android基于linux

 

以往基于应用(application)的程序开发中,程序具有明确的边界,一个程序就是一个应用,一个应用为了实现功能可以采用开辟新线程甚至新进程来辅助,但是应用与应用之间不能复用资源和功能。而Android引入了基于组件开发的软件架构,虽然我们开发android程序,仍然使用一个apk工程一个Application的开发形式,但是对于Aplication的开发就用到了Activity、service等四大组件,其中的每一个组件,都是可以被跨应用复用的哦,这个就是android的神奇之处。

 

 

 

Activity哪些资源是显示资源 onstart() 初始化, 哪些资源是完整生命周期资源oncreate() 初始化?

 

Machine generated alternative text:onRestart OnCræte On_Destroy OnStart OnStop OnResume OnPause

Activity完整的生命周期:从第一次调用onCreate()开始直到调用onDestroy()结束

通常用于初始化设置:1、为Activity设置所要使用的布局文件2、为按钮绑定监听器等静态的设置操作

      onCreate(Bundle savedInstanceState);

Activity的可视生命周期:从调用onStart()到相应的调用onStop()

 在这两个方法之间,可以保持显示Activity所需要的资源。如在onStart()中注册一个广播接收者监听影响你的UI的改变,在onStop()中注销。

 

 

如果所有的初始化都在onCreate()中实现,会有什么问题?

    首先,ActivityonCreate()被调用时,Activity还不可见,如果要做一些动画,既然视图还不存在,在onCreate中来启动动画,明显有问题;

    其次,AActivity 切换到 BActivity,再切换到 AActivity(我们假定是AActivity的同一个实例),由于实例已经存在,所以onCreate不会再被调用,那AActivity从后台切换至前台时,有可能需要一些初始化,那就没法再被调用到了,也有问题;

 

如果所有的初始化都在onStart()中实现,会有什么问题?

    首先,onCreate()注释中,是明确建议 setContentView()findViewById() 要在 onCreate()中被调用,但我实测了一下,在onStart()中调用 setContentView()findViewById() 功能也是正常的;

    其次,onStart() 被调用时,Activity可能是可见了,但还不是可交互的,onResume()的注释中都明确地说了这不是Activity对用户是可见的最好的指示器onStart() 在这之前被调用,那有一些特殊的初始化相关的逻辑在这里被调用也会有问题。

 

如果把所有的去初始化都在onStop()中实现,会有什么问题?

    1、 在 onResume() 的注释中,建议是在onResume()中打开独占设备(比如相机),与onResume()对应的是onPause(),所以所有的去初始化操作放在onStop()中执行,可能会引出新的问题;

    2onStop() 的注释中明确地写了,在内存不足而导致系统无法保留此进程的情况下,onStop() 可能都不会被执行。

    我的老Android手机相机应用如果未正常关闭,相机在不重启系统的情况下就无法再正常启动,估计就和这个机制有关;相机进程是被强制杀掉的,而导致去初始化操作未被正常执行。

 

From<http://www.bubuko.com/infodetail_120329.html>

 

 

 

 

两个activity切换  onStop()  onStart() 谁先执行?

 

onPause(ONE) - onCreate(Three) - onStart(Three) - onResume(Three) -onStop(ONE)

即当下一个activity到了前台并且获得了焦点,上一个acitivty才会onstop

 

 

 

内存不足时,Dalvak 虚拟机会根据其内存回收规则来回收内存

 

      1. 先回收与其他Activity或Service/Intent Receiver 无关的进程(即优先回收独

 

立的Activity)因此建议,我们的一些(耗时)后台操作,最好是作成Service的形式

 

      2.不可见(处于Stopped状态的)Activity

 

      3.Service进程(除非真的没有内存可用时会被销毁)

 

      4.非活动的可见的(Paused状态的)Activity

 

      5.当前正在运行(Active/Running状态的)Activity

 

 

 

 

 

onSaveInstanceState和onRestoreInstanceState触发的时机

 

方法onSaveInstanceState()用来保存Activity被杀之前的状态,onPause()之前被触发

 

 Android calls onSaveInstanceState() before theactivity becomes vulnerable to being destroyed by the system, but does notbother calling it when the instance is actually being destroyed by a useraction (such as pressing the BACK key)

 

 

从这句话可以知道,当某个activity变得“容易”被系统销毁时,该activityonSaveInstanceState就会被执行,除非该activity是被用户主动销毁的,例如当用户按BACK键的时候。

 

注意上面的双引号,何为“容易”?言下之意就是该activity还没有被销毁,而仅仅是一种可能性。这种可能性有哪些?通过重写一个activity的所有生命周期的onXXX方法,包括onSaveInstanceStateonRestoreInstanceState方法,我们可以清楚地知道当某个activity(假定为activityA)显示在当前task的最上层时,其onSaveInstanceState方法会在什么时候被执行,有这么几种情况:

 

 

1、当用户按下HOME键时。

 

这是显而易见的,系统不知道你按下HOME后要运行多少其他的程序,自然也不知道activity A是否会被销毁,故系统会调用onSaveInstanceState,让用户有机会保存某些非永久性的数据。以下几种情况的分析都遵循该原则

 

 

2、长按HOME键,选择运行其他的程序时。

 

 

3、按下电源按键(关闭屏幕显示)时。

 

 

4、从activity A中启动一个新的activity时。

 

 

5、屏幕方向切换时,例如从竖屏切换到横屏时。

 

在屏幕切换之前,系统会销毁activityA,在屏幕切换之后系统又会自动地创建activity A,所以onSaveInstanceState一定会被执行

 

引发activity摧毁和重建的其他情形

 

除了系统处于内存不足的原因会摧毁activity之外, 某些系统设置的改变也会导致activity的摧毁和重建. 例如改变屏幕方向(见上例), 改变设备语言设定, 键盘弹出等.

 

 

总而言之,onSaveInstanceState的调用遵循一个重要原则,即当系统“未经你许可”时销毁了你的activity,则onSaveInstanceState会被系统调用,这是系统的责任,因为它必须要提供一个机会让你保存你的数据(当然你不保存那就随便你了)。

 

 

至于onRestoreInstanceState方法,需要注意的是,onSaveInstanceState方法和onRestoreInstanceState方法“不一定”是成对的被调用的,onRestoreInstanceState被调用的前提是,activity A“确实”被系统销毁了,而如果仅仅是停留在有这种可能性的情况下,则该方法不会被调用,例如,当正在显示activity A的时候,用户按下HOME键回到主界面,然后用户紧接着又返回到activity A,这种情况下activityA一般不会因为内存的原因被系统销毁,故activity AonRestoreInstanceState方法不会被执行

 

 

另外,onRestoreInstanceStatebundle参数也会传递到onCreate方法中,你也可以选择在onCreate方法中做数据还原

 

onSaveInstanceState-->

onPause-->

onStop-->

onDestroy-->

onCreate-->

onStart-->

onRestoreInstanceState-->

onResume-->

 

 

 

Activity Service 所在的进程?

 

但是一个组件(包括service)所在的进程必须是在组件所在的Aplication进程中

 

启动一个Activity时,Ams首先会去查询该Activity所在的应用是否开启,如果没有开启则会启动一个进程去Run这个Application

 

From<http://www.cnblogs.com/franksunny/archive/2012/04/17/2453403.html>

 

 

 

是否一个application(apk) 就一个进程?

另外通过对service的应用,可以得出结论,一个apk,即一个应用(Application)可以跑在多个进程中,一个进程在一个虚拟机中运行,也即一个apk可以启动多个虚拟机。

通过shareuserID可以将多个apk,跑在同一个进程中。

从而得出结论:一个虚拟机只能跑一个进程,一个进程里可以跑多个应用,一个应用也可以跑在多个进程中,这就是他们的关系。

 

From<http://www.cnblogs.com/franksunny/archive/2012/04/17/2453403.html>

 

 

 

一个Intent 被多个receiver 或者activity 注册?

 


 

Android的三个基本组件——ActivityServiceBroadcast Receiver——都是通过Intent机制激活的,不同类型的组件有不同的传递Intent方式:

 

1.1 要激活一个新的Activity,或者让一个现有的Activity做新的操作,可以通过调用Context.startActivity()或者Activity.startActivityForResult()方法。

1.2 要启动一个新的Service,或者向一个已有的Service传递新的指令,调用Context.startService()方法或者调用Context.bindService()方法将调用此方法的上下文对象与Service绑定。

 

1.3Context.sendBroadcast()Context.sendOrderBroadcast()Context.sendStickBroadcast()这三个方法可以发送Broadcast Intent。发送之后,所有已注册的并且拥有与之相匹配IntentFilterBroadcastReceiver就会被激活。

Intent一旦发出,Android都会准确找到相匹配的一个或多个ActivityService或者BroadcastReceiver作响应。所以,不同类型的Intent消息不会出现重叠,即BroadcastIntent消息只会发送给BroadcastReceiver,而决不会发送给Activity或者Service。由startActivity()传递的消息也只会发给Activity,由startService()传递的Intent只会发送给Service

 

From<http://blog.csdn.net/t12x3456/article/details/7688154>

 

 

 

 

 

Intent component action 关系

 

二、Intent的构造函数

 

公共构造函数:

 

1、Intent() 空构造函数

 

2、Intent(Intent o) 拷贝构造函数

 

3、Intent(String action) 指定action类型的构造函数

 

4、Intent(String action, Uri uri)指定Action类型和Uri的构造函数,URI主要是结合程序之间的数据共享ContentProvider

 

5、Intent(Context packageContext, Class<?> cls)传入组件的构造函数,也就是上文提到的

 

6、Intent(String action, Uri uri, Context packageContext,Class<?> cls) 前两种结合体

 

Intent有六种构造函数,3、4、5是最常用的,并不是其他没用!

 

intent的解析:

在应用中,我们可以以两种形式来使用Intent

1.1 显式Intent:指定了component属性的Intent(调用setComponent(ComponentName)或者setClass(Context, Class)来指定)。通过指定具体的组件类,通知应用启动对应的组件。

2.2 隐式Intent:没有指定comonent属性的Intent。这些Intent需要包含足够的信息,这样系统才能根据这些信息,在在所有的可用组件中,确定满足此Intent的组件。

对于直接IntentAndroid不需要去做解析,因为目标组件已经很明确,Android需要解析的是那些间接Intent,通过解析将Intent映射给可以处理此IntentActivityServiceBroadcast Receiver

Intent解析机制

Intent解析机制主要是通过查找已注册在AndroidManifest.xml中的所有<intent-filter>及其中定义的Intent,通过PackageManager(注:PackageManager能够得到当前设备上所安装的

application package的信息)来查找能处理这个Intentcomponent。在这个解析过程中,Android是通过Intentactiontypecategory这三个属性来进行判断的,判断方法如下:

1.1  如果Intent指明定了action,则目标组件的IntentFilteraction列表中就必须包含有这个action,否则不能匹配;

1.2  如果Intent没有提供type,系统将从data中得到数据类型。和action一样,目标组件的数据类型列表中必须包含Intent的数据类型,否则不能匹配。

1.3  如果Intent中的数据不是content:类型的URI,而且Intent也没有明确指定type,将根据Intent中数据的scheme(比如 http:或者mailto:)进行匹配。同上,Intent scheme必须出现在目标组件的scheme列表中。

1.4 如果Intent指定了一个或多个category,这些类别必须全部出现在组建的类别列表中。比如Intent中包含了两个类别:LAUNCHER_CATEGORYALTERNATIVE_CATEGORY,解析得到的目标组件必须至少包含这两个类别。

 

From<http://blog.csdn.net/t12x3456/article/details/7688154>

 

总结

Intent 指明谁来处理(component),处理什么任务(action),任务详细(uri)

如果不指明谁来处理,那么所有能处理此任务的人都会被调用到

 

 

 

 

Java 反射

 

反射就是:在任意一个方法里:

1.如果我知道一个类的名称/或者它的一个实例对象, 我就能把这个类的所有方法和变量的信息找出来(方法名,变量名,方法,修饰符,类型,方法参数等等所有信息)。

2.如果我还明确知道这个类里某个变量的名称,我还能得到这个变量当前的值。

2.当然,如果我明确知道这个类里的某个方法名+参数个数类型,我还能通过传递参数来运行那个类里的那个方法。

 

JAVA的反射是指,可以通过一个类名来探察这个类里面的信息,比如说类的属性名,属性名的修饰符,方法名,方法返回值,方法修饰符等等,反正除了方法体得不到,其他都可以用反射得到;反射还可以生成类的实例,通过这个实例定义属性,调用方法,特别是能调用私有的属性和私有的方法。

 

为什么使用反射

 

你有一套系统,根据不同版本连接多重不同的数据库,通过反射的方式,你可以通过传递一个字符串的方式来调用某个数据库连接类的方法。如果用set,get方法的话,每新增加一个数据库,就需要新增加一个方法,也就是说需要修改原有的已经写好的类。而使用反射,直接创建一个新的类,然后直接调用就可以了,无需修改任何原有的类

 

实例

http://blog.csdn.net/yemaozi2009/article/details/4245207

 

 

 

 

 

JNI 优缺点

使用java与本地已编译的代码交互,通常会丧失平台可移植性。但是,有些情况下这样做是可以接受的,甚至是必须的,比如,使用一些旧的库,与硬件、操作系统进行交互,或者为了提高程序的性能。JNI标准至少保证本地代码能工作在任何Java虚拟机实现下。

 

From<http://www.eoeandroid.com/thread-185939-1-1.html>

 

优点

1 性能

安全性 c库不被反编译)

有些库只有c

 

 

 

Implement a tts engine

https://android.googlesource.com/platform/development/+/f39a078023bd2f89212f352624eb2c5830c45496/samples/TtsEngine/AndroidManifest.xml?autodive=0

 

http://stackoverflow.com/questions/7223680/how-to-create-custom-text-to-speech-engine/12495672#12495672

 

http://luohaoxuan320.blog.163.com/blog/static/207784109201291234426481/

 

 

 

Let gradle build support so file

To include native libraries you need:

  1. create "jar" file with special structure containing ".so" files;
  2. include that file in dependencies list.

To create jar file, use the following snippet:

task nativeLibsToJar(type: Zip, description: 'create ajar archive of the native libs') {
    destinationDir file("$buildDir/native-libs")
    baseName 'native-libs'
    extension 'jar'
    from fileTree(dir: 'libs', include: '**/*.so')
    into'lib/'
}

tasks.withType(Compile) {
    compileTask ->compileTask.dependsOn(nativeLibsToJar)
}

To include resulting file, paste the following line into"dependencies" section in "build.gradle" file:

compile fileTree(dir: "$buildDir/native-libs", include: 'native-libs.jar')

 

From<http://stackoverflow.com/questions/16683775/include-so-library-in-apk-in-android-studio>

 

 

 

 

Why C/C++ has head file?

User doesn't know theimplement of function, just call according to the .h interface

 

 

 

Android CortanaApp:Application 的生命周期是怎么样的?

为什么后台还有service running main activity关闭后 CortanaApp 会重新调用oncreate()所以导致原来的变量清空了

 

 

 

Androidactivity service 是在同一个线程里面吗?

同一个apk下面的serviceActivity没有特殊的情况下,一般是在同一个进程的同一个线程里面的。

都在主UI线程,这就是为什么我们在serviceonstart onbind中不能做延时较长的操作。

同一个包内的activity和service,如果service没有设定属性android:process=":remote"的话,service会和activity跑在同一个进程中,由于一个进程只有一个UI线程,所以,service和acitivity就是在同一个线程里面的。

From<http://bbs.csdn.net/topics/330159598>

另外activity,service之类的组件可以通过process属性设置,可以放到不同进程里

 

 

android 为什么不能在子线程更新UI

 

因为UI的方法基本都是没有做线程同步的,如果其他线程也去操作的话会导致数据不一致,出现异常情况。

 

都是在UI线程更新UI嘛!否则时会报错的,类如Onlythe original thread that created a view hierarchy can touch its views.之类的错。

 

android中默认的一些view都是主线程创建并添加到windowmanager中的,所以UI都在主线程操作

特例: sufaceview就可以在子线程更新ui,因为它在绘制前有加锁。其他情况下不安全是因为没加锁,如果几个子线程同时更新,就会有问题。

 

From<http://www.eoeandroid.com/thread-537014-1-1.html>

 

 

线程安全效率就低,谷歌为了追求效率,舍弃了安全,所以UI是线程不安全的

 

 

 

Android 主线程 子线程职责

主线程和子线程的职责。主线程的职责是创建、显示和更新UI控件、处理UI事件、启动子线程、停止子线程;子线程的职责是计算逝去的时间和向主线程发出更新UI消息,而不是直接更新UI

 

From<http://www.cnblogs.com/Gaojiecai/archive/2012/12/01/2797311.html>

 

 

 

Android 子线程主线程通信

通过handler 子线程就可以将详细发送给主线程

 

Android中的Handler, Looper, MessageQueue和Thread

一个线程只有一个LooperMessageQueue,但可以有多个handler, 多个handler公用LooperMessageQueue

 

Message:消息,其中包含了消息ID,消息处理对象以及处理的数据等,由MessageQueue统一列队,终由Handler处理。

 

Handler:处理者,负责Message的发送及处理。使用Handler时,需要实现handleMessage(Messagemsg)方法来对特定的Message进行处理,例如更新UI等。

 

MessageQueue:消息队列,用来存放Handler发送过来的消息,并按照FIFO规则执行。当然,存放Message并非实际意义的保存,而是将Message以链表的方式串联起来的,等待Looper的抽取。

 

Looper:消息泵,不断地从MessageQueue中抽取Message执行。因此,一个MessageQueue需要一个Looper。

 

Thread:线程,负责调度整个消息循环,即消息循环的执行场所。

 

 

[Image 2]the image of how handler works

 

From<http://developer.samsung.com/technical-doc/view.do?v=T000000025>

 

 

 

android 最简单的demo WebView.loadUrl 竟然直接打开了浏览器

Root cause, there isa tunnel redirect,  the first response isempty page with js, then redirect to the real destination page

 

Solution 1:

myWebView.getSettings().setJavaScriptEnabled(true);

 

Solution 2:

    protected void onCreate(BundlesavedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

 

        WebView myWebView = (WebView)findViewById(R.id.webview);

       myWebView.loadUrl("http://www.baidu.com");

    }

 

 

 

webview javascript 注入方法

 

Method1: 

Read the js file tostring

onpageFinished()   loadurl(js: string)

 

Method2:

onpageFinished()   loadurl(js: the js add <script> tohtml which load js url)

 

From<http://www.cnblogs.com/rayray/p/3680500.html>

 

Method3:

onpageFinished()loadurl(js:  the js add <script> tohtml which contain the js html)

http://stackoverflow.com/questions/21552912/android-web-view-inject-local-javascript-file-to-remote-webpage

 

 

 

Android之WebViewClient与WebChromeClient的区别

Must setwebviewclient you can back click link in your webview, not go to system defaultweb browser

 

ANDROID应用开发的时候可能会用到WEBVIEW这个组件,使用过程中可能会接触到WEBVIEWCLIENTWEBCHROMECLIENT,那么这两个类到底有什么不同呢?

 

WebViewClient主要帮助WebView处理各种通知、请求事件的,比如:

onLoadResource

onPageStart

onPageFinish

onReceiveError

onReceivedHttpAuthRequest

 

WebChromeClient主要辅助WebView处理Javascript的对话框、网站图标、网站title、加载进度等比如

onCloseWindow(关闭WebView)

onCreateWindow()

onJsAlert(WebViewalert无效,需要定制WebChromeClient处理弹出)

onJsPrompt

onJsConfirm

onProgressChanged

onReceivedIcon

onReceivedTitle

看上去他们有很多不同,实际使用的话,如果你的WebView只是用来处理一些html的页面内容,只用WebViewClient就行了,如果需要更丰富的处理效果,比如JS、进度条等,就要用到WebChromeClient

更多的时候,你可以这样

 

 

Web View onPageFinished 的时候js load 好了吗

onPageFinishedandroid official doc said when called, picture may not rendered, during test,if  onPageFinsihed sleep 5s, the page isblank,  that means after onPageFinished,  the webPage prompt

 

 

 

 

Set onclick this

http://www.cnblogs.com/uedt/articles/1748422.html

 

 

 

Webview onPageFinished inject js "window.οnlοad=function() {……" to<head><script> doesn't work

Maybe whenonPageFinished() run, window.onload already runned

 

 

Without sdcard, it can still visit /sdcard

 

 

 

 

Vivo PreferenceFragment background color always black


http://stackoverflow.com/questions/20934265/change-the-background-color-of-preferencefragment

 

http://www.cnblogs.com/mengdd/archive/2013/01/08/2851368.html

 

http://stackoverflow.com/questions/18675535/preferencefragment-not-working-after-oncreateview

 

 

 

Label name, app name, manager app name

 

I noticed there are some differences in how the app name canturn up in Lollipop devices. Before Lollipop, you can have different app nameswith this:

<application
    android:label="@string/app_name"> // <-- appears inmanage app info
    <activity
        android:name=".MainActivity"
        android:label="@string/action_bar_title"> // <-- appears inactionbar title
        <intent-filterandroid:label="@string/name_in_icon_launcher"> // <-- appears inicon launcher
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>
    <activity
...

In Lollipop, it will be like this:

<application
    android:label="@string/name_in_manage_app_info">
    <activity
        android:name=".MainActivity"
        android:label="@string/name_in_actionbar_and_icon_launcher">
        <intent-filterandroid:label="@string/this_is_useless">
            <action android:name="android.intent.action.MAIN"/>
            <category android:name="android.intent.category.LAUNCHER"/>
        </intent-filter>
    </activity>

In Lollipop, android:label in intent-filter is basically useless, while actionbartitle and icon launcher is identical. So, if you want a different title inactionbar, you have no choice but to set dynamically

getSupportActionBar().setTitle(R.string.app_name);

 

From<http://stackoverflow.com/questions/5443304/how-to-change-an-android-apps-name>

 

 

 

Can I launch different Activities on startup dependingon user preferences?

 

From<http://stackoverflow.com/questions/4074840/can-i-launch-different-activities-on-startup-depending-on-user-preferences>

 

 

 

Android splash activity

http://www.jb51.net/article/36190.htm

 

 

 

Window Parameter

 

FLAG_NOT_FOCUSABLE 

不许获得焦点。

不能获得按键输入焦点,所以不能向它发送按键或按钮事件。那些时间将发送给它后面的可以获得焦点的窗口。此选项还会设置FLAG_NOT_TOUCH_MODAL选项。设置此选项,意味着窗口不能与软输入法进行交互,所以它的Z序独立于任何活动的输入法(换句话说,它可以全屏显示,如果需要的话,可覆盖输入法窗口)。要修改这一行为,可参考FLAG_ALT_FOCUSALBE_IM选项。

public static finalint FLAG_NOT_FOCUSABLE     = 0x00000008;

悬浮窗之外的屏幕点击都传递给了后面

后退键, home 键单击双击,功能键可以用,都传递给了后面应用

可以设置音量, 相当于传递给了后面的主界面应用

不可以setontouchlistener

 

 

不接受触摸屏事件。

public static finalint FLAG_NOT_TOUCHABLE     = 0x00000010;

 

 

 

当窗口可以获得焦点(没有设置FLAG_NOT_FOCUSALBE选项)时,仍然将窗口范围之外的点设备事件(鼠标、触摸屏)发送给后面的窗口处理。否则它将独占所有的点设备事件,而不管它们是不是发生在窗口范围之内。

public static finalint FLAG_NOT_TOUCH_MODAL   = 0x00000020;

悬浮窗之外的屏幕点击都传递给了后面

后退键退出悬浮窗

home键单击双击传递给了后面应用

功能键不能用

不可以设置音量

不可以setontouchlistener

 

 

 

窗口之后的内容变暗。

public static finalint FLAG_DIM_BEHIND       = 0x00000002;

悬浮窗之外的屏幕点击点亮了屏幕,没有传递给后面

后退键退出悬浮窗

home键单击双击传递给了后面应用

功能键不能用

不可以设置音量

可以setontouchlistener

 

 

 

 

Android sign

 

1Android程序包使用的数字证书可以是自签名的,不需要一个权威的数字证书机构签名认证。

 

2)数字证书都是有有效期的,Android只是在应用程序安装的时候才会检查证书的有效期。如果程序已经安装在系统中,即使证书过期也不会影响程序的正常功能。

 

 

 

 

Android security

 

No, theAndroid OS doesn't guarantee that intent data is not seen by anyone. Anymalicious app implementing the intent filter is able to receive the message andthus get hold of your sensitive data. Encrypting data is good idea but makesure that:

 

the keyused for encryption is not stored on the SD card.

you arenot hard-coding the key in the app as it is very trivial to get the source fromthe apk.

Also,make sure that only the app(s) which are intended to receive the message (viaintents) are receiving the intent and that no other app is able to receive thatintent. If you want to communicate confidential data and if you know the classnames the apps that would be communicating via intents, you can either ensurethat only that specific app receives the intent by using the setClassname()method of the intents. For ex:

 

Intent i= new Intent();

i.setClassName(“your.pkg.name”,“your.pkg.name.Destination”);

or byletting apps having only specific permissions receive the intent. For ex:

 

Intent i= new Intent();

i.setAction(“your.own.action”);

sendBroadcast(i,“your.own.permission”);

 

 

http://www.360doc.com/content/15/0320/19/15077656_456766941.shtml

 

 

详细说明:RSA简洁幽雅,但计算速度比较慢,通常加密中并不是直接使用RSA 来对所有的信息进行加密,最常见的情况是随机产生一个对称加密的密钥,然后使用对称加密算法对信息加密,之后用RSA对刚才的加密密钥进行加密。-RSA elegant simplicity, but the computing speed isrelatively slow, usually not direct the use of encryption in the RSA to encryptall the information, the most common situation is a random symmetric encryptionkey, and then use symmetric encryption algorithm for encryption of information,just after the use of RSA encryption keys for encryption.

 

 

 

 

Android intent

setClassName

setClass

setComponentName

Differences

 

调用Intent.setComponent() Intent.setClassName() Intent.setClass()方法明确指定了组件名的Intent为显式意图,显式意图明确指定了Intent应该传递给哪个组件。

 

http://stackoverflow.com/questions/3304304/how-to-get-the-sender-of-an-intent

 

 

 

Android NDK

http://stackoverflow.com/questions/27774604/generating-so-files-in-android-studio-1-0-2-with-ndk

http://stackoverflow.com/questions/29738953/ndkbuild-failure




Proguard

http://blog.csdn.net/banketree/article/details/41928175

 

enum其实是inner class 所以要打开obfuscate的开关不混淆innerclasses -keepattributesInnerClasses,

 

 

Audio Record

http://blog.csdn.net/ameyume/article/details/7885744

 

Blueteeth2.0/2.1/3.0/4.0  BLE

http://blog.sina.com.cn/s/blog_3e33e9a90102v1mf.html



 

http://stackoverflow.com/questions/17068954/are-activity-and-service-running-in-the-same-thread

http://stackoverflow.com/questions/4980106/how-to-bind-two-android-activites-to-one-service

http://stackoverflow.com/questions/2272378/android-using-method-from-a-service-in-an-activity

http://stackoverflow.com/questions/31202391/eventbus-android-implementation-why-reflection
http://stackoverflow.com/questions/4878159/whats-the-best-way-to-share-data-between-activities

http://stackoverflow.com/questions/4918781/why-does-asynctask-run-in-the-main-thread-of-an-application

http://techtej.blogspot.com/2011/02/android-passing-data-between-main.html
https://en.wikipedia.org/wiki/Comparison_of_Java_and_Android_API

http://stackoverflow.com/questions/17474818/difference-between-asynctask-and-thread-runnable

http://stackoverflow.com/questions/4068984/running-multiple-asynctasks-at-the-same-time-not-possible

http://www.mamicode.com/info-detail-517008.html

http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/

http://stackoverflow.com/questions/16161941/exectuorservice-vs-threadpoolexecutor-which-is-using-linkedblockingqueue

http://stackoverflow.com/questions/13441723/android-align-parent-bottom-bottom-margin

 

Activity

逻辑

必须绑定界面view  

物理按键影响逻辑状态,可以捕捉物理按键

应用启动的入口

响应式,可接受intent消息

Service

逻辑 

可以不绑定View(大部分情况都不绑定)

物理按键不影响,无法捕捉物理按键

也可以是应用启动的入口

响应式,可接受intent消息

If therunning logic doesn't need UI, it should be put into service

 

 

Activity Service对应关系

Oneactivity could bind to multiple services at one time,

In oneapp, One service only bind to one activity at one time  (but you can switch different activity bindto one service at different time)

 

 

Activity Service数据传递,方法调用

A改了B的某个属性值,B直到用的时候发现 (类似两个class, 也类似线程)

AB信息,B响应式处理 (类似于两个进程)

A调用B的方法 (类似与两个class)

所以你可以看成有一个看不见的main函数,里面有一个classarray, 里面放了所有activity service main函数在主thread, 你可以在class中创建其他thread

 

Activity Service通信

共享singleton class传递数据

 

可以通过注册intent broadcast互相传递数据

 

Activity 启动 service 方法一 (理解为调用service类构造函数) startService 创建, 之后无信息传递

Activity 启动 service 方法二 (理解为调用service类构造函数): 可以通过  Activity --- ServiceConnection/Bind--- Service 

(serviceConnection onXXDis/Connect类似activity intent listener,    service  onbind()类似 intent listener

  bind类似Intent中的内容,bind可以拓展一个获取service对象方法, 所以activity 可以直接拿到service 对象, bind也可以拓展其他调用service 的方法,调用bind方法就相当于调用了service方法

  activity 可以直接调用 service 方法

  service 一般通过sendintent 或者messenger 调用activity)

 

 

There are 3ways to binding service with your activity.

  1. IBinder Implementation
  2. Using Messanger
  3. Using AIDL

From <http://stackoverflow.com/questions/2272378/android-using-method-from-a-service-in-an-activity>

 

 

AIDL就是相当于是用aidl文件定义了 bind 的拓展方法, 只不过多加了异常捕获, 系统自动生成了ipc代码

 

 

Messenger 有点类似 bind 提供了获取service对象的方法,activity 调用service方法的时候把activity.this 传进去,这样service也可以访问activity

Messenger 实际就是service 先把自己messageHandler发给activity 之后activity 把自己的messagehandler发给service, 之后双发通过对方的给的messagehandler通信

(感觉实现成本编码量不亚于写intentboardcast)

Messenger也可以用于跨进程通信

Messenger.getBinder() 内部实现用了aidl

 

ServiceService怎么互相传递信息,互相调用?

ActivityActivity 之间只有数据传递,技术上可以方法调用但不这样用

多个Activity之间信息共享 (共享也是一种数据传递)

  • Send data inside intent
  • Use a singleton class
  • Use application singleton
  • Static fields
  • HashMap of WeakReferences
  • Persist objects (sqlite, share preferences, file, etc.)

 

From <http://stackoverflow.com/questions/4878159/whats-the-best-way-to-share-data-between-activities>

 


 

响应式程序和普通程序

最原始情况,只有硬件中断,就写硬件所有中断的所有响应函数 (每个硬件中断都是一个main的入口)
硬件中断
(homeback..) ——> 经系统处理(此时的系统处理相当于启动了一个main函数, main函数维护了一个activity service object list 区别就是如果按home,不掉service onstop只调activity onstop 拓展成 oncreate() onDestroy() 事件暴露给应用(我们相当于写了main中的主要几个函数,但我们看不到main) )  <------ 系统的软件事件 (比如杀死进程发出了软件事件)
 

 

执行流分叉

Thread和异步都使得程序的执行流分叉了,不是一个单一执行流

 

 

多线程

AsyncTask 只是一个简化的帮助类, 本质就是将doInbackground()内容在一个新thread中运行, 其余的如onPost() 还是在调用thread运行

Identify the code segment that you want to execute inbackground thread. (e.g. code that does 忙等待的network i/o, bulk file transfer on local disk, etc) put them intodoInbackground of \

AsyncTaskonly allow running one at a time

 

RunOnUIThread (Runnable()) 一个线程发消息给另一个线程, 消息的内容是需要执行的代码,线程间响应式的进行通信

所以也可以看成一个简化的帮助类,可以通过自己写handler looper替代

 

多线程通过消息通信

Looper 消息队列
Handler 消息处理类,也是暴露给其他thread的消息发送句柄

http://techtej.blogspot.com/2011/02/android-passing-data-between-main.html

Thread.getLooper,   Handler构造函数用Looper作参数

 

互斥锁

无论synchronized关键字加在方法上还是对象上,它取得的锁都是对象,而不是把一段代码或函数当作锁――而且同步方法很可能还会被其他线程的对象访问

http://www.mamicode.com/info-detail-517008.html
http://stackoverflow.com/questions/437620/java-synchronized-static-methods-lock-on-object-or-class

 

 

网络请求

HttpUrlConnection

Java 方法

通过IO write read 操作网络

同步 阻塞

HttpClient

Apach Java Component

httpClient client build execute

同步 阻塞

Framework Volley

 

开源框架

 

 

 

App 启动时候的工作

 

常用的框架,他们解决的问题,实现原理

EventBus

很有可能就是singletonclass 用一个listmap存储维护消息和处理 handler

http://blog.csdn.net/lmj623565791/article/details/40920453

Gson vsJackson

 

 

 

Compare Java and android

https://en.wikipedia.org/wiki/Comparison_of_Java_and_Android_API

JVM

UIcomponent

Threadcommunication java and android are different

AsyncTask, Handler, Looper is android specific

AsyncTasks should ideally be used for short operations (a fewseconds at the most.) If you need to keep threads running for long periods oftime, it is highly recommended you use the various APIs provided by thejava.util.concurrent pacakge such as Executor, ThreadPoolExecutor andFutureTask

http://stackoverflow.com/questions/17474818/difference-between-asynctask-and-thread-runnable

Java executor, future

Executor 就是对thread相关操作的封装  Future是等待thread结果的处理类

http://winterbe.com/posts/2015/04/07/java8-concurrency-tutorial-thread-executor-examples/


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值