无法检查Android服务问题 [英] Not able to check Android Service Issue

查看:82
本文介绍了无法检查Android服务问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做的只是通过服务控制应用程序中的背景音乐,这样我就可以启动和停止任何活动.

All I want to do is simply control background music in my app through a service so I am able to start it and stop it from any activity.

当我告诉Toast服务启动和销毁时,我的一切都设置得很好,但是只要我将媒体播放器放到那里,它就会开始并开始播放音乐,但是只要单击一下就可以了一个停止服务的按钮,我得到一个错误,并强行关闭.

I have everything set up perfectly when I tell the service to Toast when it is started and destroyed but as soon as I put the media play-in in there instead It starts fine and starts playing the music but as soon as a click a button to stop the service I get an error and a force close.

有人可以建议我做错了什么吗?

Can anyone suggest what I am doing wrong?

这是我的代码:

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.widget.Toast;

public class MyService extends Service {

private MediaPlayer player;

@Override    
public IBinder onBind(Intent intent) {
returnnull;
}

@Override    
publicvoid onCreate() { 
super.onCreate(); 
Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();
MediaPlayer player = MediaPlayer.create(MyService.this, R.raw.oceanwavestest);
player.start();
player.setLooping(true);

}

   @Override    
   publicvoid onDestroy() {
   super.onDestroy();
   player.stop();
   Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();
   } 
} 

推荐答案

我在您的代码中看到了几件事,我会检查我是否在您的位置.

There are a few things that I see in your code that I would check out if I were in your position.

  • 您试图在onDestroy中调用成员MediaPlayer对象"player"上的"stop",但是在onCreate中,使用代码行创建MediaPlayer对象"player"

"MediaPlayer播放器= MediaPlayer.create(MyService.this,R.raw.oceanwavestest);"

"MediaPlayer player = MediaPlayer.create(MyService.this, R.raw.oceanwavestest);"

我相信会创建一个播放器对象,您将失去该函数范围之外的范围.

which i believe creates a player object that you will loose scope of outside of the function.

此代码的1行修正是仅使用"player = MediaPlayer.create(MyService.this,R.raw.oceanwavestest);",这种方式使用成员变量而不是局部变量

The 1 line fix for this code is to just use "player = MediaPlayer.create(MyService.this, R.raw.oceanwavestest);", this way the member variable is used rather than a local variable

如果这是我的代码,我会将成员变量更改为m_player或mPlayer之类的名称,以便您知道它是代码中的成员变量.

If this were my code I would change the member variable to be called something like m_player or mPlayer so that you know it is a member variable in your code.

  • (可能是拼写错误)"returnnull;"在onBind中应为返回null;"

  • (probably a typo) "returnnull;" in onBind should be "return null;"

您可能还想尝试致电

player.stop(); Toast.makeText(this,服务已停止",Toast.LENGTH_SHORT).show();

player.stop(); Toast.makeText(this, "Service Stopped", Toast.LENGTH_SHORT).show();

在调用super.onDestroy()之前

before you call super.onDestroy()

让我知道这是否有帮助

这篇关于无法检查Android服务问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆