What's the best practice for sharing classes between a Wear and Android app?

北城余情 提交于 2019-11-28 21:11:01

问题


I'm using a class that I serialize in my Android Phone app, and deserialize in my Android Wear app. They are both in the same Android Studio Project, and are deployed as one.

How can I share the class between the two without having a copy of the class in each package? Right now I'm copy/pasting it, but is there any way for me to include it in both apps?

The directory structure being:

./
    mobile/
           ...src/etc
    wear/
           ...src/etc

How do I handle common classes?


回答1:


You can create a new "Android Library" Module in the project, and place your common classes there.

Then you simply add it as a dependency of both the Mobile and Wear modules (in Project Structure -> Dependencies -> Add -> Module dependency). That way you can create/use instances of these classes from both modules.




回答2:


Usually for share a code base the modularization is used. AndroidStudio uses module naming.

A module is a collection of source files and build settings that allow you to divide your project into discrete units of functionality.

It can be Android Library(.aar) or Java Library(.jar). In both cases a new module will be created with apply plugin: 'com.android.library' line in build.gradle file. You can use it to put a shared code.

To include/add this module you should use

File -> New -> Import Module...

This command add all necessary information into settings.gradle file and you will be able use it via

implementation project(':<module_name>')


来源:https://stackoverflow.com/questions/24592027/whats-the-best-practice-for-sharing-classes-between-a-wear-and-android-app

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!