【问题标题】:How do you pass a value such as R.raw.twelve_chimes from an activity to a service?如何将诸如 R.raw.twelve_chimes 之类的值从活动传递到服务?
【发布时间】:2011-11-14 22:00:13
【问题描述】:

如果我在 res 的原始文件夹中有一个名为 12_chimes.mp3 的 mp3 文件,你能告诉我使用什么编码将它从我的活动传递到服务以及如何接收传递的信息吗?

目前我正在使用此代码调用服务:

startService(new Intent(this, MyService.class));

在服务中,这就是我播放媒体文件的方式:

player = MediaPlayer.create(this, R.raw.twelve_chimes);
player.setLooping(false);
player.start();

如果无法传递 R.raw.twelve_chimes,是否可以将其作为传入的字符串并以某种方式使用该字符串在服务中播放?

谢谢。

真的, 埃马德

【问题讨论】:

    标签: android service android-activity parameter-passing


    【解决方案1】:

    在这种情况下,您不应将文件放在 /res 文件夹中。将其放在项目的 /assets 文件夹中。然后你可以通过AssetManager访问它

    /res/raw 和 /assets 文件夹的区别在于,可以将 /assets 中的文件作为二进制流访问。另一方面,可以本地化 /res 文件夹下的文件。

    【讨论】:

    • 您好 user375251,感谢您的帮助。我需要更多地查看资产文件夹。真的,埃马德
    【解决方案2】:

    如果 Service 与 Activity 位于同一个 Android 包中,则 R.raw.twelve_chimes 应该可供 Service 使用:您应该能够将其作为 Intent 中的 Integer 传递:

    Intent i = new Intent(this, MyService.class);
    i.putExtra("OPTION", R.raw.twelve_chimes);
    

    在Service的onStartCommand中:

    player = MediaPlayer.create(this, intent.getIntExtra("OPTION"));
    player.setLooping(false);
    player.start();
    

    可能需要进行一些更改来处理您呼叫player 的位置,但这或多或少应该可行。

    【讨论】:

    • 嗨,Femi,效果很好!我不得不添加这一行: startService(i);在活动和服务中: player = MediaPlayer.create(this, intent.getIntExtra("OPTION", 0));非常感谢。真的,埃马德
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多