Android Intent服务出错
您好,我的代码有问题。我想在后台播放音乐,这将与Android的Android Intent服务出错,android,service,intentservice,Android,Service,Intentservice,您好,我的代码有问题。我想在后台播放音乐,这将与Android的IntentService一起运行。 但是如果我实现该行,我的SDk会给我一个错误 Radio.java public class Radio extends Activity implements OnCompletionListener, OnPreparedListener, OnErrorListener, OnBufferingUpdateListener, MusicFocusable, ViewFactory {
IntentService
一起运行。
但是如果我实现该行,我的SDk会给我一个错误
Radio.java
public class Radio extends Activity implements OnCompletionListener,
OnPreparedListener, OnErrorListener, OnBufferingUpdateListener, MusicFocusable, ViewFactory {
及
MyService.java
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MyService extends Service {
private static final String TAG = "MyService";
MediaPlayer player;
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player.start();
}
}
如果你需要更多的代码,就说出来吧 错误是因为您在
onClickListener
中使用this
,并且必须在其中使用ClassName.this
。根据答案,这是因为:
使用时,您正在创建一个匿名内部类
这部分代码:new OnClickListener(){
这意味着您所引用的类不再是此,因此要访问/标识该类,您必须使用类名。因此,您应该使用此:
play.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View btn) {
if (!playState) {
play.setImageResource(R.drawable.stop);
handler.postDelayed(handlePlayRequest, 300);
startService(new Intent(Radio.this, MyService.class));
}
else {
play.setImageResource(R.drawable.play);
status.setText("Drücke Play!");
handler.postDelayed(handlePlayRequest, 300);
stopService(new Intent(Radio.this, MyService.class));
}
}
}
此外,您还可以使用btn.getContext()
而不是Classname。这样可以使代码更容易复制到其他类。如下所示:
startService(new Intent(btn.getContext(), MyService.class));
发布错误和相关日志以启动
startService(new Intent(btn.getContext(), MyService.class));