如何在我的应用程序和服务之间共享代码?

时间:2018-01-07 18:35:17

标签: android android-activity android-service

为了这个问题,我用评论取代了一些逻辑并简化了这个问题。但问题的主要目的应该是一样的。

所以我有一个带有按钮和textview的活动视图。

layout_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="vertical"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Click me"/>

    <TextView
        android:id="@+id/textView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>
</LinearLayout>

代码背后 MainActivity.java

findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // retrieve data from internet and display in the textview
            findViewById(R.id.textView).setText(response);
        }
    });

现在使用this library,我可以在活动之外的浮动窗口中显示带有服务layout_main。请参阅github页面上的demo gif。使用我的xml上的另一个按钮,我启动了该服务。

startService(new Intent(MainActivity.this, MyService.class));
来自github页面的

Demo code

MyService.java

@Override
public void onCreate() {
    super.onCreate();

    windowManagerContainer = new WindowManagerContainer(this);
    chatHeadManager = new DefaultChatHeadManager<String>(this, windowManagerContainer);
    chatHeadManager.setViewAdapter(new ChatHeadViewAdapter<String>() {

        @Override
        public View attachView(String key, ChatHead chatHead, ViewGroup parent) {
            View cachedView = viewCache.get(key);
            if (cachedView == null) {
                LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
                View view = inflater.inflate(R.layout.layout_main, parent, false);
                // 'problem' here
                cachedView = view;
                viewCache.put(key, view);
            }
            parent.addView(cachedView);
            return cachedView;
        }
...

但现在问题是,我必须在服务中创建重复的代码来处理网络请求并显示文本。它与活动中的代码基本相同。

所以我的问题是,我可以以某种方式分享用于我的活动和服务的'代码隐藏',还是我必须从我的活动中创建代码副本?

1 个答案:

答案 0 :(得分:0)

我确实可以把我的观点作为一个类的参数来处理那里的两个视图

我的活动:

View view = getLayoutInflater().inflate(R.layout_main, null);
setContentView(view);
new ViewHandler(MainActivity.this, view);
...

我的服务:

LayoutInflater inflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.layout_main, false);
new ViewHandler(MyService.this, view);

ViewHandler:

public ViewHandler(Context context, View view) {
    super(context, view);
    // get ids from the view and attach handlers or do other things with it
    Button button = (Button) view.findViewById(R.id.button);
    ....