实习笔记-20

App真正的入口

ActivityThread 中的main方法,一个应用程序对应一个ActivityThread对象,Zygote孵化出一个进程后,就会执行main方法

  • 准备Looper和消息队列
  • thread.attach()方法绑定到ActivityManagerService中

attach方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
private void attach(boolean system, long startSeq) {
sCurrentActivityThread = this;
mConfigurationController = new ConfigurationController(this);
mSystemThread = system;
if (!system) {
android.ddm.DdmHandleAppName.setAppName("<pre-initialized>",
UserHandle.myUserId());
RuntimeInit.setApplicationObject(mAppThread.asBinder());
final IActivityManager mgr = ActivityManager.getService();
try {
mgr.attachApplication(mAppThread, startSeq);
//
} catch (RemoteException ex) {
throw ex.rethrowFromSystemServer();
}
// Watch for getting close to heap limit.
BinderInternal.addGcWatcher(new Runnable() {
@Override public void run() {
if (!mSomeActivitiesChanged) {
return;
}
Runtime runtime = Runtime.getRuntime();
long dalvikMax = runtime.maxMemory();
long dalvikUsed = runtime.totalMemory() - runtime.freeMemory();
if (dalvikUsed > ((3*dalvikMax)/4)) {
if (DEBUG_MEMORY_TRIM) Slog.d(TAG, "Dalvik max=" + (dalvikMax/1024)
+ " total=" + (runtime.totalMemory()/1024)
+ " used=" + (dalvikUsed/1024));
mSomeActivitiesChanged = false;
try {
ActivityTaskManager.getService().releaseSomeActivities(mAppThread);
} catch (RemoteException e) {
throw e.rethrowFromSystemServer();
}
}
}
});
} else {
// Don't set application object here -- if the system crashes,
// we can't display an alert, we just want to die die die.
android.ddm.DdmHandleAppName.setAppName("system_process",
UserHandle.myUserId());
try {
mInstrumentation = new Instrumentation();
mInstrumentation.basicInit(this);
ContextImpl context = ContextImpl.createAppContext(
this, getSystemContext().mPackageInfo);
mInitialApplication = context.mPackageInfo.makeApplication(true, null);
mInitialApplication.onCreate();
} catch (Exception e) {
throw new RuntimeException(
"Unable to instantiate Application():" + e.toString(), e);
}
}

ViewRootImpl.ConfigChangedCallback configChangedCallback = (Configuration globalConfig) -> {
synchronized (mResourcesManager) {
// TODO (b/135719017): Temporary log for debugging IME service.
if (Build.IS_DEBUGGABLE && mHasImeComponent) {
Log.d(TAG, "ViewRootImpl.ConfigChangedCallback for IME, "
+ "config=" + globalConfig);
}

// We need to apply this change to the resources immediately, because upon returning
// the view hierarchy will be informed about it.
if (mResourcesManager.applyConfigurationToResources(globalConfig,
null /* compat */,
mInitialApplication.getResources().getDisplayAdjustments())) {
mConfigurationController.updateLocaleListFromAppContext(
mInitialApplication.getApplicationContext());

// This actually changed the resources! Tell everyone about it.
final Configuration updatedConfig =
mConfigurationController.updatePendingConfiguration(globalConfig);
if (updatedConfig != null) {
sendMessage(H.CONFIGURATION_CHANGED, globalConfig);
mPendingConfiguration = updatedConfig;
}
}
}
};
ViewRootImpl.addConfigCallback(configChangedCallback);
}

实习笔记-19

SlidingPaneLayout

windowSizeClass – 屏幕布局决策

ActivityEmbedding

Box With Constraints – 不同展示内容决策

Custom Layout – 不同方式布局

阅读更多

实习笔记-24

设备到设备文件传输

如果您的应用以 Android 11 或更高版本为目标平台,您将无法使用 allowBackup 属性停用应用文件的设备到设备迁移。系统会自动启用此功能。

不过,即使您的应用以 Android 11 或更高版本为目标平台,您也可以通过将 allowBackup 属性设为 false 来停用应用文件的云端备份和恢复。

非 SDK 接口限制

相机

媒体 intent 操作需要系统默认相机
从 Android 11 开始,只有预装的系统相机应用可以响应以下 intent 操作:

阅读更多

实习笔记-25

创建型

单例

优点

  • 节省资源
    • 内存
    • 重对象中包含的io,文件指针
  • 调用方便

缺点

  • 适用于昂贵对象,对于轻量对象,为了维护单例造成的同步等开销比创建一个对象更高。得不偿失
  • 不方便mock,(可以把单例对象作为函数参数则可以mock),相较于静态方法更方便(静态方法需要代理的方式mock)
  • 测试时常常并行测试,使用单例会降低效率
    函数式编程,拷贝
    云控,打点 Alex
    静态工具方法,少用,不要有状态,确保永远不会变
阅读更多

Kotlin学习笔记——BroadCast

1
#define 小毛驴 xml

收发广播

使用场景:Fragment想要向外传递信息

  1. 在Fragment中发送广播
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    class BlankFragment : Fragment() {
    var ctx:Context? = null
    var mPosition:Int = 0
    var mInageId:Int = 0
    var mDesc:String = ""
    var title:String = ""

    val colorNames = listOf<String>("红色","黄色","绿色","青色","蓝色")
    val colors = intArrayOf(Color.RED, Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE)
    var mSeq:Int = 0
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    ctx = activity
    if (arguments != null) {
    mPosition = arguments!!.getInt("position", 0)
    mInageId = arguments!!.getInt("image_id", 0)
    mDesc = arguments!!.getString("desc")
    title = arguments!!.getString("title")
    }
    val view = inflater.inflate(R.layout.show_info, container, false)

    view.findViewById<ImageView>(R.id.imageView).setImageResource(mInageId)
    view.findViewById<TextView>(R.id.textView).text = mDesc
    view.findViewById<Button>(R.id.se).setOnClickListener {
    ctx!!.selector("选择颜色", colorNames) {
    mSeq = it

    val intent = Intent(BlankFragment.EVENT)
    intent.putExtra("seq", it)
    intent.putExtra("color", colors[it])
    ctx!!.sendBroadcast(intent)//发送广播
    }
    }
    return view
    }

    companion object {
    const val EVENT:String = "changeColor"//const,编译期常量
    fun newInstance(position:Int, image_id:Int, desc:String, title:String) : BlankFragment {

    val fragment = BlankFragment()
    val bundle = Bundle()
    bundle.putInt("position", position)
    bundle.putInt("image_id", image_id)
    bundle.putString("desc", desc)
    bundle.putString("title", title)
    fragment.arguments = bundle
    return fragment
    }
    }
    }
  2. 在要接收广播的页面注册receiver
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    class MainActivity : FragmentActivity(){
    private var BGChangeRecever:myBgChangeRecever? = null
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    var vp:ViewPager = findViewById(R.id.vp)
    var title: PagerTabStrip = findViewById(R.id.title)

    val pics = arrayOf(R.mipmap.basic, R.mipmap.close, R.mipmap.debug, R.mipmap.edit)
    val list:MutableList<itemInfo> = mutableListOf()
    for (i in pics.indices) {
    list.add(itemInfo((i+1).toString(), pics[i], ((i+1)*(i+1)).toString()))
    }
    vp.adapter = infoPagerAdapter(supportFragmentManager, list)
    vp.currentItem = 0
    }

    public override fun onStart() {
    super.onStart()
    BGChangeRecever = myBgChangeRecever()

    val filiter = IntentFilter(BlankFragment.EVENT)//广播过滤器,过滤掉参数以外的广播
    registerReceiver(BGChangeRecever,filiter)//开始时注册接收器

    }

    public override fun onStop() {
    unregisterReceiver(BGChangeRecever)//结束前注销接收器
    super.onStop()
    }

    private inner class myBgChangeRecever : BroadcastReceiver() {//广播接收器
    override fun onReceive(context: Context?, intent: Intent?) {//接收广播后执行的操作
    if (intent != null) {
    val color = intent.getIntExtra("color", Color.GREEN)
    textView2.setTextColor(color)
    }
    }

    }
    }

接收系统广播

静态注册

阅读更多

Kotlin学习笔记——Button

实现短按长按的方法

调用函数

方法 参数 参数解释 返回值 备注
setOnClickListener lambda表达式 lambda的参数为发生点击动作的View,返回值Unit Unit 相当于override fun onClickListener(v:View)
setOnLongClickListener lambda表达式 lambda的参数为发生点击动作的View,返回值Boolean(true表示这个事件已经消耗完了,false表示事件继续传递,会触发一次短按事件) Unit 相当于override fun onLongClick(v:View):Boolean

例子

1
2
3
4
5
6
7
btn.setOnClickListener {
toast("click")
}
btn.setOnLongClickListener {
toast("Long Click")
true
}

使用内部类

阅读更多

Kotlin学习笔记——EditText

输入监听器

方便起见,在activity的内部写一个内部类,用来监听输入

编写监听器

1
2
3
4
5
6
7
8
9
10
11
inner class EditWatcher : TextWatcher {
override fun afterTextChanged(s:Editable) {

}
override fun beforeTextChanged(s:CharSequence, start:Int, count:Int, after:Int) {

}
override fun onTextChanged(s:CharSequence, start:Int, count:Int, after:Int) {

}
}

注意

  1. 把Editable直接toString()就是用户当前的输入
阅读更多

Kotlin学习笔记——Fragment

1
#define 小毛驴 xml

使用方法

Fragment与ViewPager搭配,实现翻页,实现每页多个控件

  1. 写好每个item的小毛驴文件和数据传送类
  2. 继承Fragment类,自定义一个fragment
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    class BlankFragment : Fragment() {
    var ctx:Context? = null
    var mPosition:Int = 0
    var mInageId:Int = 0
    var mDesc:String = ""
    var title:String = ""

    val colorNames = listOf<String>("红色","黄色","绿色","青色","蓝色")
    val colors = intArrayOf(Color.RED, Color.YELLOW, Color.GREEN, Color.CYAN, Color.BLUE)
    var mSeq:Int = 0
    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    ctx = activity
    if (arguments != null) {
    mPosition = arguments!!.getInt("position", 0)
    mInageId = arguments!!.getInt("image_id", 0)
    mDesc = arguments!!.getString("desc")
    title = arguments!!.getString("title")
    }//获取数据
    val view = inflater.inflate(R.layout.show_info, container, false)

    view.findViewById<ImageView>(R.id.imageView).setImageResource(mInageId)
    view.findViewById<TextView>(R.id.textView).text = mDesc
    //显示数据
    return view
    }

    companion object {
    fun newInstance(position:Int, image_id:Int, desc:String, title:String) : BlankFragment {//调用这个函数,创建新的fragment

    val fragment = BlankFragment()
    val bundle = Bundle()
    bundle.putInt("position", position)
    bundle.putInt("image_id", image_id)
    bundle.putString("desc", desc)
    bundle.putString("title", title)
    fragment.arguments = bundle
    return fragment
    }
    }
    }
  3. ViewPager的适配器
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    class infoPagerAdapter(val fragManger: FragmentManager, val itemList:MutableList<itemInfo>) : FragmentStatePagerAdapter(fragManger) {
    override fun getCount(): Int = itemList.size
    override fun getItem(p0: Int): Fragment {
    val item = itemList[p0]
    return BlankFragment.newInstance(p0, item.pic, item.desc, item.name)
    }

    override fun getPageTitle(position: Int): CharSequence? {
    return itemList[position].name
    }
    }
    4.给ViewPager添加适配器
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    class MainActivity : FragmentActivity(){
    //这个时候,继承的是FragmentActivity
    override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    var vp:ViewPager = findViewById(R.id.vp)
    var title: PagerTabStrip = findViewById(R.id.title)
    val list:MutableList<itemInfo> = mutableListOf()
    //省略中间给list赋值的过程
    vp.adapter = infoPagerAdapter(supportFragmentManager, list)
    vp.currentItem = 0
    }
    }