2017-09-12 58 views
0

我目前正在掌握一個Android應用程序來製作一個新版本。該應用程序已經沒有活動也沒有碎片。要知道,一個應用程序被人用抽象passionated開發......在那裏,這個概念MortarScope使用無處不在,但真的無法弄清楚它是如何工作的,什麼是這樣做的目的,以及砂漿。我知道有文件here,但一個明確的解釋將不勝感激。Android - MortarScope如何工作?

+1

當我搜索的搜索引擎'方砂漿android',我發現資源,如https://medium.com/square-corner-blog/simpler-android-apps-with-flow-and-mortar-5beafcd83761和https://www.bignerdranch.com/blog/an-investigation-into-flow-and-mortar/和https://academy.realm.io/posts/using-flow-mortar/。你可能想編輯你的問題,並特別解釋**你不明白的東西。 – CommonsWare

回答

0

MortarScopeMap<String, Object>,它可以具有它繼承自父。

// vague behavior mock-up 
public class MortarScope { 
    Map<String, Object> services = new LinkedHashMap<>(); 
    MortarScope parent; 

    Map<String, MortarScope> children = new LinkedHashMap<>(); 

    public MortarScope(MortarScope parent) { 
     this.parent = parent; 
    } 

    public boolean hasService(String tag) { 
     return services.contains(tag); 
    } 

    @Nullable 
    public <T> T getService(String tag) { 
     if(services.contains(tag)) { 
      // noinspection unchecked 
      return (T)services.get(tag); 
     } 
     if(parent == null) { 
      return null; 
     } 
     return parent.getService(tag); 
    } 
} 

棘手的是,MortarScope可以放入一個MortarContextWrapper,使用mortarScope.createContext(context),這將允許您使用getSystemService獲得來自MortarScope服務(顯然只在地方一級)。

這是可行的,因爲ContextWrapper s創建一個層次結構,getSystemService()也做了層次查找。

class MortarContextWrapper extends ContextWrapper { 
    private final MortarScope scope; 

    private LayoutInflater inflater; 

    public MortarContextWrapper(Context context, MortarScope scope) { 
    super(context); 
    this.scope = scope; 
    } 

    @Override public Object getSystemService(String name) { 
    if (LAYOUT_INFLATER_SERVICE.equals(name)) { 
     if (inflater == null) { 
     inflater = LayoutInflater.from(getBaseContext()).cloneInContext(this); 
     } 
     return inflater; 
    } 
    return scope.hasService(name) ? scope.getService(name) : super.getSystemService(name); 
    } 
} 

這可以使畫面的內容包裝存儲MortarScope如果是這樣創造

LayoutInflater.from(mortarScope.createContext(this)).inflate(R.layout.view, parent, false); 

這意味着,當你做這樣的事情:

public class MyService { 
    public static MyService get(Context context) { 
     // noinspection ResourceType 
     return (MyService)context.getSystemService("MY_SERVICE"); 
    } 
} 

public class MyView extends View { 
    ... 
    MyService myService = MyService.get(getContext()); 

然後你可以強制getSystemService()從通過跨越上下文(視圖,行爲,應用程序)的層次查找你上面的任何級別獲得MyService


家長保留孩子,除非明確地破壞,所以Activity範圍由Application範圍保持活力,並View範圍由Activity範圍維持生命,因此配置更改不破壞存儲內的服務MortarScope。

+0

非常感謝您的回覆。所以如果我理解的很好,Mortar和MortarScope的主要目的是將服務封裝在上下文中並允許通過getSystemService使用它們? –

+0

是的,確切!另外,除非明確銷燬,否則父母會使迫擊炮彈保持活動狀態,因此迫擊炮彈中的所有服務都會在配置更改後仍然存在(f.ex.旋轉) – EpicPandaForce