Android无法绑定到服务 [英] Android can't bind to service

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

问题描述

新到Android,试图找出服务。我想一个服务绑定到一个活动,我下面的文档中的例子,但我不断收到下面标线NullPointerException异常(appService.playSong(标题))。检查它在调试器中显示,AppService服务确实为空。

New to android, trying to figure out Services. I'm trying to bind a service to an activity, I'm following the examples in the documentation, but I keep getting a NullPointerException on the line marked below(appService.playSong(title)). Checking it in the debugger reveals that appService is indeed null.

public class Song extends Activity implements OnClickListener,Runnable {
protected static int currentPosition;
private ProgressBar progress;
private TextView songTitle;
private MPService appService;

private ServiceConnection onService = new ServiceConnection() {
    public void onServiceConnected(ComponentName className,
            IBinder rawBinder) {
        appService = ((MPService.LocalBinder)rawBinder).getService();
    }

    public void onServiceDisconnected(ComponentName classname) {
        appService = null;
    }
};


public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.song);

    Intent bindIntent = new Intent(Song.this,MPService.class);
    bindService(bindIntent,onService,
            Context.BIND_AUTO_CREATE);

    Bundle b = getIntent().getBundleExtra("songdata");
    String title = b.getString("song title");

    // ... 

    appService.playSong(title); // nullpointerexception

    // ...

}

下面是该服务的相关部分:

Here's the relevant part of the service:

package org.example.music;

// imports

public class MPService extends Service {
private MediaPlayer mp;
public static int currentPosition = 0;
public List<String> songs = new ArrayList<String>();
public static String songTitle;
private static final String MEDIA_PATH = new String("/mnt/sdcard/");

@Override
public void onCreate() {
    super.onCreate();

    mp = new MediaPlayer();
    songs = Music.songs;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    return Service.START_STICKY;
}

public class LocalBinder extends Binder {
    MPService getService() {
        return MPService.this;
    }
}

private final IBinder binder = new LocalBinder();

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

public void playSong(String songPath) {
try {
    mp.reset();
    mp.setDataSource(songPath);
    mp.prepare();
    mp.start();

    mp.setOnCompletionListener(new OnCompletionListener() {
        public void onCompletion(MediaPlayer arg0) {
            nextSong();
        }
    });

    songTitle = songPath.substring(12,songPath.length()-4);

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

public void nextSong() {
if (++currentPosition >= songs.size()) {
    currentPosition = 0;
}
String song = MEDIA_PATH+songs.get(currentPosition);
playSong(song);
} 

public void prevSong() {
if (--currentPosition<0) {
    currentPosition=songs.size()-1;
}
String song = Music.MEDIA_PATH+songs.get(currentPosition);
playSong(song);
}

public int getSongPosition() {
return mp.getCurrentPosition();
}

public MediaPlayer getMP() {
return mp;
}
}

我已经注册在AndroidManifest.xml中的服务和设置的android:启用=真。你在这里看到任何明显的错误?

I have registered the service in AndroidManifest.xml and set android:enabled="true". Do you see any obvious mistakes here?

推荐答案

正在假设bindService()将连接到服务同步,但连接将只提供后的onCreate()finshed。

You are assuming that the bindService() will connect to the service synchronously, but the connection will be available only after onCreate() finshed.

该框架运行的onCreate()在UI线程上和bindService()只是让一个音符后连接到服务。连接到服务永远做在UI线程,因此这可能是的onCreate执行后才会发生。你甚至不能指望连接被建立后的onCreate正确的()。这将是:)后的某个时候发生的。此外,框架可能它的将断开的服务,但是它应该只发生在内存不足的情况​​。

The framework runs onCreate() on the UI thread and bindService() just makes a note to connect to the service later. Connecting to a service will always be done on the UI thread, so this can only happen after onCreate was executed. You can't even count on the connection being set up right after onCreate(). It will happen sometime after that :). Also, the framework might disconnect the service on it's will, though it should only happen in low memory conditions.

因此​​,将code这与AppService服务工作从的onCreate()来onServiceConnected(),它是要去工作。

So, move the code which works with appService from onCreate() to onServiceConnected() and it's gonna work.

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

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