Android Intent Service 上的错误



您好,我的代码有问题,我想在后台播放音乐,这将适用于Android IntentService。但是如果我实现该行,我的 SDk 会给我一个错误。

收音机.java

public class Radio extends Activity implements OnCompletionListener,
OnPreparedListener, OnErrorListener, OnBufferingUpdateListener, MusicFocusable, ViewFactory {

....

play.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View btn) {
            if (!playState) {
                play.setImageResource(R.drawable.stop);
                handler.postDelayed(handlePlayRequest, 300);
                 startService(new Intent(this, MyService.class));
                "Here is Error 1"
            }
            else {
                play.setImageResource(R.drawable.play);
                status.setText("Drücke Play!");
                handler.postDelayed(handlePlayRequest, 300);
                stopService(new Intent(this, MyService.class));
                 "Here is Error 2"
            }
        }

我的服务.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() {

这意味着你引用的类不再this,所以要访问/识别类,你必须使用类名。所以你应该使用这个:

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.this 来使代码更易于复制到其他类。那看起来像这样:

startService(new Intent(btn.getContext(), MyService.class));

相关内容