草庐IT

java - 更新到 Android 5.0 后媒体样式通知不起作用

coder 2023-12-07 原文

我尝试使用这个 link 实现 Media Style Notification .但是,当我最近更新到 Android 5.0 SDK 时,createSession 方法不起作用。

mMediaPlayer = new MediaPlayer();
mManager = (MediaSessionManager) getSystemService(Context.MEDIA_SESSION_SERVICE);
mSession = mManager.createSession("sample session"); //shows compile error
mController = MediaController.fromToken( mSession.getSessionToken() );

还有其他方法需要使用吗?当我检查更改日志时,它说 createSession 不再使用。那么实现此类媒体样式通知的替代方案是什么。

最佳答案

您不再使用 MediaController.fromToken,而是使用 MediaSessin.getController . 您不再使用 MediaSessionManager.createSession,而是创建一个新的 MediaSession 对象和 MediaSession.getSessionToken检索您的 MediaSession.Token .

一个非常基本的示例实现可能是这样的:

private static final String ACTION_TOGGLE_PLAYBACK = "com.your.package.name.TOGGLE_PLAYBACK";
private static final String ACTION_PREV = "com.your.package.name.PREV";
private static final String ACTION_NEXT = "com.your.package.name.NEXT";

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    ...

    final Bitmap artwork = ...;

    // Create a new MediaSession
    final MediaSession mediaSession = new MediaSession(this, "debug tag");
    // Update the current metadata
    mediaSession.setMetadata(new MediaMetadata.Builder()
            .putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, artwork)
            .putString(MediaMetadata.METADATA_KEY_ARTIST, "Pink Floyd")
            .putString(MediaMetadata.METADATA_KEY_ALBUM, "Dark Side of the Moon")
            .putString(MediaMetadata.METADATA_KEY_TITLE, "The Great Gig in the Sky")
            .build());
    // Indicate you're ready to receive media commands
    mediaSession.setActive(true);
    // Attach a new Callback to receive MediaSession updates
    mediaSession.setCallback(new MediaSession.Callback() {

        // Implement your callbacks

    });
    // Indicate you want to receive transport controls via your Callback
    mediaSession.setFlags(MediaSession.FLAG_HANDLES_TRANSPORT_CONTROLS);

    // Create a new Notification
    final Notification noti = new Notification.Builder(this)
            // Hide the timestamp
            .setShowWhen(false)
            // Set the Notification style
            .setStyle(new Notification.MediaStyle()
                    // Attach our MediaSession token
                    .setMediaSession(mediaSession.getSessionToken())
                    // Show our playback controls in the compat view
                    .setShowActionsInCompactView(0, 1, 2))
            // Set the Notification color
            .setColor(0xFFDB4437)
            // Set the large and small icons
            .setLargeIcon(artwork)
            .setSmallIcon(R.drawable.your_small_icon)
            // Set Notification content information
            .setContentText("Pink Floyd")
            .setContentInfo("Dark Side of the Moon")
            .setContentTitle("The Great Gig in the Sky")
            // Add some playback controls
            .addAction(R.drawable.your_prev_icon, "prev", retreivePlaybackAction(3))
            .addAction(R.drawable.your_pause_icon, "pause", retreivePlaybackAction(1))
            .addAction(R.drawable.your_next_icon, "next", retreivePlaybackAction(2))
            .build();

    // Do something with your TransportControls
    final TransportControls controls = mediaSession.getController().getTransportControls();

    ((NotificationManager) getSystemService(NOTIFICATION_SERVICE)).notify(1, noti);
}

private PendingIntent retreivePlaybackAction(int which) {
    Intent action;
    PendingIntent pendingIntent;
    final ComponentName serviceName = new ComponentName(this, YourPlaybackService.class);
    switch (which) {
        case 1:
            // Play and pause
            action = new Intent(ACTION_TOGGLE_PLAYBACK);
            action.setComponent(serviceName);
            pendingIntent = PendingIntent.getService(this, 1, action, 0);
            return pendingIntent;
        case 2:
            // Skip tracks
            action = new Intent(ACTION_NEXT);
            action.setComponent(serviceName);
            pendingIntent = PendingIntent.getService(this, 2, action, 0);
            return pendingIntent;
        case 3:
            // Previous tracks
            action = new Intent(ACTION_PREV);
            action.setComponent(serviceName);
            pendingIntent = PendingIntent.getService(this, 3, action, 0);
            return pendingIntent;
        default:
            break;
    }
    return null;
}

结果

关于java - 更新到 Android 5.0 后媒体样式通知不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27209596/

有关java - 更新到 Android 5.0 后媒体样式通知不起作用的更多相关文章

  1. ruby-on-rails - 如何验证 update_all 是否实际在 Rails 中更新 - 2

    给定这段代码defcreate@upgrades=User.update_all(["role=?","upgraded"],:id=>params[:upgrade])redirect_toadmin_upgrades_path,:notice=>"Successfullyupgradeduser."end我如何在该操作中实际验证它们是否已保存或未重定向到适当的页面和消息? 最佳答案 在Rails3中,update_all不返回任何有意义的信息,除了已更新的记录数(这可能取决于您的DBMS是否返回该信息)。http://ar.ru

  2. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  3. ruby - 如何使用文字标量样式在 YAML 中转储字符串? - 2

    我有一大串格式化数据(例如JSON),我想使用Psychinruby​​同时保留格式转储到YAML。基本上,我希望JSON使用literalstyle出现在YAML中:---json:|{"page":1,"results":["item","another"],"total_pages":0}但是,当我使用YAML.dump时,它不使用文字样式。我得到这样的东西:---json:!"{\n\"page\":1,\n\"results\":[\n\"item\",\"another\"\n],\n\"total_pages\":0\n}\n"我如何告诉Psych以想要的样式转储标量?解

  4. ruby - 如何在 Ruby 中拆分参数字符串 Bash 样式? - 2

    我正在为一个项目制作一个简单的shell,我希望像在Bash中一样解析参数字符串。foobar"helloworld"fooz应该变成:["foo","bar","helloworld","fooz"]等等。到目前为止,我一直在使用CSV::parse_line,将列分隔符设置为""和.compact输出。问题是我现在必须选择是要支持单引号还是双引号。CSV不支持超过一个分隔符。Python有一个名为shlex的模块:>>>shlex.split("Test'helloworld'foo")['Test','helloworld','foo']>>>shlex.split('Test"

  5. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  6. ruby-on-rails - 使用 rails 4 设计而不更新用户 - 2

    我将应用程序升级到Rails4,一切正常。我可以登录并转到我的编辑页面。也更新了观点。使用标准View时,用户会更新。但是当我添加例如字段:name时,它​​不会在表单中更新。使用devise3.1.1和gem'protected_attributes'我需要在设备或数据库上运行某种更新命令吗?我也搜索过这个地方,找到了许多不同的解决方案,但没有一个会更新我的用户字段。我没有添加任何自定义字段。 最佳答案 如果您想允许额外的参数,您可以在ApplicationController中使用beforefilter,因为Rails4将参数

  7. java - 等价于 Java 中的 Ruby Hash - 2

    我真的很习惯使用Ruby编写以下代码:my_hash={}my_hash['test']=1Java中对应的数据结构是什么? 最佳答案 HashMapmap=newHashMap();map.put("test",1);我假设? 关于java-等价于Java中的RubyHash,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/22737685/

  8. java - 从 JRuby 调用 Java 类的问题 - 2

    我正在尝试使用boilerpipe来自JRuby。我看过guide从JRuby调用Java,并成功地将它与另一个Java包一起使用,但无法弄清楚为什么同样的东西不能用于boilerpipe。我正在尝试基本上从JRuby中执行与此Java等效的操作:URLurl=newURL("http://www.example.com/some-location/index.html");Stringtext=ArticleExtractor.INSTANCE.getText(url);在JRuby中试过这个:require'java'url=java.net.URL.new("http://www

  9. ruby-on-rails - 添加回形针新样式不影响旧上传的图像 - 2

    我有带有Logo图像的公司模型has_attached_file:logo我用他们的Logo创建了许多公司。现在,我需要添加新样式has_attached_file:logo,:styles=>{:small=>"30x15>",:medium=>"155x85>"}我是否应该重新上传所有旧数据以重新生成新样式?我不这么认为……或者有什么rake任务可以重新生成样式吗? 最佳答案 参见Thumbnail-Generation.如果rake任务不适合你,你应该能够在控制台中使用一个片段来调用重新处理!关于相关公司

  10. java - 我的模型类或其他类中应该有逻辑吗 - 2

    我只想对我一直在思考的这个问题有其他意见,例如我有classuser_controller和classuserclassUserattr_accessor:name,:usernameendclassUserController//dosomethingaboutanythingaboutusersend问题是我的User类中是否应该有逻辑user=User.newuser.do_something(user1)oritshouldbeuser_controller=UserController.newuser_controller.do_something(user1,user2)我

随机推荐