我正在开发一个 Android 3.1 平板电脑应用程序。
这个应用程序将运行一个线程。在它的服务上,我有这个代码:
public class UDPSocketBackgroundService extends Service
{
@Override
public void onCreate()
{
super.onCreate();
Log.v(TAG, "in onCreate()");
// xxxxxx
Looper.prepare();
mServiceHandler = new Handler() {
/**
*
*/
public void handleMessage(Message msg)
{
DatagramPacket packet = (DatagramPacket) msg.obj;
//String received = new String(packet.getData(), 0, packet.getLength());
Message backMsg = Message.obtain();
backMsg.arg1 = Activity.RESULT_OK;;
Bundle bundle = new Bundle();
bundle.putByteArray("CLIENT_DATA", packet.getData());
bundle.putString("CLIENT_HOST", packet.getAddress().getHostAddress());
bundle.putString("CLIENT_PORT", new Integer(packet.getPort()).toString());
backMsg.setData(bundle);
try
{
outMessenger.send(backMsg);
}
catch (android.os.RemoteException e1)
{
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
};
Looper.loop();
}
但我不知道为什么(因为这是我第一次使用服务)我在这里遇到异常:
Looper.prepare();
更新
服务的 onBind 事件:
public IBinder onBind(Intent intent)
{
Bundle extras = intent.getExtras();
// Get messager from the Activity
if (extras != null) {
outMessenger = (Messenger) extras.get("MESSENGER");
}
try
{
myThread = new UDPServerThread("X", 8888, mServiceHandler);
myThread.start();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return mMessenger.getBinder();
}
这就是我从主要活动启动服务的方式:
protected void onResume()
{
super.onResume();
Intent intent = null;
intent = new Intent(this, UDPSocketBackgroundService.class);
// Create a new Messenger for the communication back
// From the Service to the Activity
Messenger messenger = new Messenger(handler);
intent.putExtra("MESSENGER", messenger);
bindService(intent, conn, Context.BIND_AUTO_CREATE);
}
我究竟做错了什么?