木鸟杂记

大规模数据系统

Android Learning Notes (Part 2): Code Organization

Problem

When modularizing, I tried to separate modules like SearchListener and CallManager from MainActivity. However, when responding to events, it was inevitable to change the state of other resources, so it was necessary to obtain their handles. Thus, MainActivity also needed to be passed in as a handle.

What bothered me even more was that due to some asynchronous events (such as requesting permissions), the trigger was in the module (CallManager), while the receiver was in the main view (MainActivity). The preserved parameters then needed to be passed back to MainActivity, going back and forth like this, which made me reflect on the problems in my modularization approach.

Author: 木鸟杂记 https://www.qtmuniao.com, please indicate the source when reposting

Details

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
CallManager.java

public boolean playCall(String phoneNumber) {
if (ContextCompat.checkSelfPermission(activity,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(activity,
new String[]{Manifest.permission.CALL_PHONE},
CALL_PHONE_REQUEST);

MainActivity ma = (MainActivity) activity;
**ma.setPhoneNumber(phoneNumber);**

return false;
...
}

MainActivity.java

private String phoneNumber = null;
public void setPhoneNumber(String number) {this.phoneNumber = number;}
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
switch (requestCode) {
case CallManager.CALL_PHONE_REQUEST:
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {

if (phoneNumber != null ) {
CallManager callManager = new CallManager(this);
callManager.playCall(phoneNumber);

}
}
break;

...
}
}

In Activity, a call event is received and CallManager is invoked, then permissions are requested within it. Using the Set method, PhoneNumber is passed back to Activity. My initial thought was that the code tightly coupled with Activity, such as requesting permissions and executing callback functions after being granted permissions, could be written in MainActivity, while CallManager would only handle the call logic. However, a class variable is still needed to save the phone number for parameter passing between requesting permissions and executing the callback.


我是青藤木鸟,一个喜欢摄影、专注大规模数据系统的程序员,欢迎关注我的公众号:“木鸟杂记”,有更多的分布式系统、存储和数据库相关的文章,欢迎关注。 关注公众号后,回复“资料”可以获取我总结一份分布式数据库学习资料。 回复“优惠券”可以获取我的大规模数据系统付费专栏《系统日知录》的八折优惠券。

我们还有相关的分布式系统和数据库的群,可以添加我的微信号:qtmuniao,我拉你入群。加我时记得备注:“分布式系统群”。 另外,如果你不想加群,还有一个分布式系统和数据库的论坛(点这里),欢迎来玩耍。

wx-distributed-system-s.jpg