我正在开发一个聊天应用程序,我创建了一个后台服务用于连接socket.io,但是当发送消息时,服务器断开了。我需要Socket。io连接总是在后台服务中工作。我该怎么做呢?
这是我的后台服务:
public class BackService extends Service {
SocketIO socket;
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
try {
socket = new SocketIO("http://192.168.9.43:8001/");
socket.connect(new IOCallback() {
public void onMessage(JSONObject json, IOAcknowledge ack) {
try {
System.out.println("Server said:" + json.toString(2));
} catch (JSONException e) {
e.printStackTrace();
}
}
public void onMessage(String data, IOAcknowledge ack) {
System.out.println("Server said: " + data);
}
public void onError(SocketIOException socketIOException) {
System.out.println("an Error occured");
socketIOException.printStackTrace();
}
public void onDisconnect() {
System.out.println("Connection terminated.");
}
public void onConnect() {
System.out.println("Connection established");
}
public void on(String event, IOAcknowledge ack, Object... args) {
System.out.println("Server triggered event '" + event + "'");
Toast.makeText(getApplicationContext(), "yeni mesaj var", Toast.LENGTH_LONG).show();
System.out.println("yeni mesaj var");
}
});
} catch (MalformedURLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
return START_STICKY;
}
}
这是我的screenchat for chat:
public class ScreenChat extends Activity {
EditText mEditMessage;
Button mBtnSend;
ListView mListMessage;
public static final String TAG = "socketIO";
boolean isConnected;
public static final String KEY_DEVICE_ID = "sender";
public static final String KEY_MESSAGE = "message";
public String device_id;
SocketIOClient mClient;
MessageAdapter mMessageAdapter;
String userName;
ArrayList<Message> mMessages = new ArrayList<Message>();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_chat);
device_id = Secure.getString(getContentResolver(), Secure.ANDROID_ID);
Bundle extras = getIntent().getExtras();
if (extras != null) {
userName = extras.getString("UserName");
}
mBtnSend = (Button) findViewById(R.id.btn_send);
mEditMessage = (EditText) findViewById(R.id.txt_message);
mListMessage = (ListView) findViewById(R.id.list_message);
mMessageAdapter = new MessageAdapter(this, mMessages);
mListMessage.setAdapter(mMessageAdapter);
mMessageAdapter.notifyDataSetChanged();
mBtnSend.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View view) {
if (mClient == null)
return;
Message message = new Message();
message.setMessage(mEditMessage.getText().toString());
message.setSender(userName);
Gson gson = new Gson();
String json = gson.toJson(message);
if (mClient.isConnected()) {
mClient.emit(json);
mEditMessage.getText().clear();
mMessages.add(message);
mMessageAdapter.notifyDataSetChanged();
}
}
});
SocketIOClient.connect(AsyncHttpClient.getDefaultInstance(),
"http://192.168.9.43:8001/", mConnectCallback);
}
public void scrollMyListViewToBottom() {
mListMessage.post(new Runnable() {
@Override
public void run() {
mMessageAdapter.notifyDataSetChanged();
mListMessage.setSelection(mMessageAdapter.getCount() - 1);
}
});
}
ConnectCallback mConnectCallback = new ConnectCallback() {
@Override
public void onConnectCompleted(Exception ex, SocketIOClient client) {
if (ex != null) {
ex.printStackTrace();
return;
}
client.setStringCallback(new StringCallback() {
@Override
public void onString(String string, Acknowledge acknowledge) {
Log.d("SOCKET", string);
}
});
client.setJSONCallback(new JSONCallback() {
@Override
public void onJSON(JSONObject jsonObject,
Acknowledge acknowledge) {
Log.d("SOCKET", jsonObject.toString());
}
});
client.on("event", new EventCallback() {
@Override
public void onEvent(JSONArray jsonArray, Acknowledge acknowledge) {
Log.d("SOCKET", jsonArray.toString());
Type listType = new TypeToken<ArrayList<Message>>() {
}.getType();
Gson gson = new Gson();
ArrayList<Message> messages = gson.fromJson(
jsonArray.toString(), listType);
mMessages.addAll(messages);
scrollMyListViewToBottom();
}
});
mClient = client;
}
};
}
我怎么做工作插座。IO作为后台服务连续运行吗?
你可以在你的主活动中敲掉重复的代码。你只需要在你的主活动中初始化这个服务。
private void startMyService(){
Intent ServiceIntent = new Intent(this, BackService.class);
//ServiceIntent.putExtra(USER_DATA, obj.toString()); if you want to provide any info to the service class
this.startService(ServiceIntent);
}