简体   繁体   English

管理Android版本:每个版本使用不同的类

[英]Managing Android versions: using different classes for each version

I am using this class from my main activity: 我正在主要活动中使用此类:

public class MediaInfo {
    public String name;
    public String label;
    // ... (other String and int fields)
    public MediaSession mSession;
}

within an ArrayList: 在ArrayList中:

public class MainActivity extends ActionBarActivity implements AsyncResponse {

    private static final String TAG = "MainActivity";

    ArrayList<MediaInfo> myMediaList;
    private Context mContext;

    public void onCreate(Bundle savedInstanceState) {
        // ...
    }

    // ...
}

The problem I have is that MediaSession is a class that belongs to Android API version 21, and I am trying to make an app from version 14 on. 我的问题是MediaSession是一个属于Android API版本21的类,并且我正在尝试从版本14开始制作一个应用程序。

I would like the activity (or the class) to ignore the field containing the MediaSession class when the version is < 21. The first idea I have come across is using an abstract class and extend it when the version is >= 21, but then I would have to declare different ArrayLists, and I am not sure how I could do it. 我希望活动(或类)在版本小于21时忽略包含MediaSession类的字段。我遇到的第一个想法是使用抽象类,并在版本大于等于21时对其进行扩展,但是我将不得不声明不同的ArrayLists,而且我不确定该怎么做。 And maybe this is not the best way... 也许这不是最好的方法...

Any ideas...? 有任何想法吗...?

Thank you for your advice 感谢您的意见

The problem I have is that MediaSession is a class that belongs to Android API version 21, and I am trying to make an app from version 14 on. 我的问题是MediaSession是一个属于Android API版本21的类,并且我正在尝试从版本14开始制作一个应用程序。

Looking at the Android support library , it seems there is a backward compatible version of MediaSession, called MediaSessionCompat . 查看Android支持库 ,似乎有一个MediaSession的向后兼容版本,称为MediaSessionCompat

user3829751's answer looks good for this case. 在这种情况下,user3829751的答案看起来不错。

For this generic problem I would lead you to this question: Programmatically obtain the Android API level of a device? 对于这个一般性问题,我将带您到以下问题:以编程方式获取设备的Android API级别?

Also check the @TargetApi annotation. 还要检查@TargetApi批注。 You can extract your "version-21" to a method and call it only if the runtime if version 21. You can see an example here: https://stackoverflow.com/a/18449951/3032209 您可以将“ version-21”提取到方法中,并且仅在运行时为21版时才调用它。您可以在此处查看示例: https : //stackoverflow.com/a/18449951/3032209

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM