【问题标题】:Calling a Service method from Activity从 Activity 调用 Service 方法
【发布时间】:2012-02-20 17:42:36
【问题描述】:

在我的活动中,我有:

play.setOnClickListener(new View.OnClickListener() {

        @Override                           
        public void onClick(View v) {

        service.playSong(MEDIA_PATH);

        }
    });

这是在服务中:

void playSong(String file) {
        try {

                mp.reset();
                System.out.println(file+songs.get(currentPosition));
                mp.setDataSource(file+ songs.get(currentPosition));

                mp.prepare();
                mp.start();

                mp.setOnCompletionListener(new OnCompletionListener() {

                     public void onCompletion(MediaPlayer arg0) {
                             nextSong();
                     }
             });

        } catch (IOException e) {
                Log.e(getString(R.string.app_name), e.getMessage());
        }
}

正如您在我的活动中的上面代码中看到的那样,当我单击播放按钮时,我正在将路径传递给服务以播放音乐,但它崩溃了这是怎么回事?

【问题讨论】:

  • 您应该使用 Logcat 中的异常添加堆栈跟踪。
  • 由于我是 Android 新手,能否请您详细说明一下?
  • 我真的不明白你在说什么......你能告诉我任何例子吗?
  • 您的应用程序正在抛出异常。在 Eclipse 中转到 Logcat(在 ddms developer.android.com/guide/developing/debugging/ddms.html 中)并复制包含异常的堆栈跟踪(红色文本)。
  • 我已经声明了ServiceMP3服务;在活动类和活动中,我尝试通过以下方式访问 Service 方法: service.playSound() 这是正确的,我还需要做什么?

标签: android


【解决方案1】:

【讨论】:

  • 这两个中的哪一个是我的情况?我认为是第二个,对吧?
  • 是不是很可能调用一个Service方法??我仍然无法让它工作
  • @Samuel:是的。查找如何绑定到 Service 的示例。
  • 是这样的吗?? play= (Button)findViewById(R.id.play); play.setOnClickListener(new StartClick());私有类 StartClick 实现 View.OnClickListener { public void onClick(View v) { Intent intent = new Intent(MainMP3.this,ServiceMP3.class); MainMP3.this.bindService(intent, connection, Context.BIND_AUTO_CREATE); } }
猜你喜欢
  • 1970-01-01
  • 2012-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多