垃圾小白寫了本身看的
/**
* service 文件
*/
public class SocketService extends Service {
//本身定義接口用來傳參
private static addNewOrderInterface mInterface;
private SocketBinder socketBinder = new SocketBinder();
public static WebSocketClient client;
public static String address = "ws://192.168.0.2:8080/websocket/";
// 發送心跳包
private static Handler mHandler = new Handler();
private static Runnable heartBeatRunnable = new Runnable() {
@Override
public void run() {
mHandler.postDelayed(this, 10 * 1000);
sendMsg("@heart");
}
};
public static String message;
@Override
public void onCreate() {
super.onCreate();
try {
initSocketClient(SharedUtils.getInstance().getToken());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
L.e("執行了onStartCommand()");
connect();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
L.e("執行了onDestory()");
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return socketBinder;
}
@Override
public boolean onUnbind(Intent intent) {
L.e("綁定服務");
return super.onUnbind(intent);
}
@Override
public void unbindService(ServiceConnection conn) {
L.e("解綁服務");
super.unbindService(conn);
}
public static void receiverMessage(String msg) {
if (mInterface != null) {
mInterface.addNewData(msg);
}
}
public static class SocketBinder extends Binder {
public void service_connect_Activity() {
mHandler.post(heartBeatRunnable);
L.e("Service關聯了Activity,並在Activity執行了Service的方法");
}
public String getNewOrder() {
return message;
}
public void getOrder(String orderId) {
JSONObject object = new JSONObject();
try {
object.put("service", "RECEIVEORDER");
object.put("orderNo", orderId);
} catch (JSONException e) {
e.printStackTrace();
}
sendMsg(object.toString());
}
public void addNewOrderInterface(addNewOrderInterface anInterface) {
mInterface = anInterface;
}
}
//斷開鏈接
public static void closeConnect() {
try {
client.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
client = null;
}
}
/**
* 發送消息
*/
public static void sendMsg(String msg) {
L.e(msg);
if (client == null)
return;
try {
client.send(msg);
} catch (WebsocketNotConnectedException e) {
e.printStackTrace();
closeConnect();
try {
initSocketClient(SharedUtils.getInstance().getToken());
} catch (URISyntaxException ee) {
ee.printStackTrace();
}
connect();
}
}
public static void initSocketClient(String token) throws URISyntaxException {
if (client == null) {
client = new WebSocketClient(new URI(address + token)) {
@Override
public void onOpen(ServerHandshake serverHandshake) {
//鏈接成功
L.e("socket鏈接成功");
}
@Override
public void onMessage(String s) {
//服務端發送消息 經過接口傳給fragment
receiverMessage(s);
}
@Override
public void onClose(int i, String s, boolean remote) {
//鏈接斷開,remote斷定是客戶端斷開仍是服務端斷開
L.e("Connection closed by " + (remote ? "remote peer?" : "us") + ", info=" + s);
}
@Override
public void onError(Exception e) {
L.e("error:" + e);
}
};
}
}
//鏈接
public static void connect() {
new Thread() {
@Override
public void run() {
if (client != null) {
try {
client.connect();
} catch (IllegalStateException e) {
L.e(e.toString());
}
}
L.e("socket鏈接");
}
}.start();
}
}
/**
* 本身定義的接口
*/
public interface addNewOrderInterface {
void addNewData(String s);
}
/**
* 省略不少代碼 從項目裏摘出來的
* fragment的文件
*/
import static android.content.Context.BIND_AUTO_CREATE;
//BaseFragment 本身寫的
public class OrderReceiveFragment extends BaseFragment implements addNewOrderInterface {
private Order.OrderData.OrderList newOrder;
private SocketService.SocketBinder socketBinder = new SocketService.SocketBinder();
private ServiceConnection connection = new ServiceConnection() {
//重寫onServiceConnected()方法和onServiceDisconnected()方法
// 在Activity與Service創建關聯和解除關聯的時候調用
@Override
public void onServiceDisconnected(ComponentName name) {
}
//
// 在Activity與Service解除關聯的時候調用
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
//實例化Service的內部類myBinder
// 經過向下轉型獲得了MyBinder的實例
socketBinder = (SocketService.SocketBinder) service;
//在Activity調用Service類的方法
socketBinder.service_connect_Activity();
socketBinder.addNewOrderInterface(OrderReceiveFragment.this);
}
};
private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 0:
//推單
data.add(0, newOrder);
adapter.notifyDataSetChanged();
break;
case 1:
//心跳
break;
case 2:
//搶單
break;
}
}
};
//綁定service並啓動服務
@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
Intent intent = new Intent(context, SocketService.class);
getActivity().getApplicationContext().bindService(intent, connection, BIND_AUTO_CREATE);
getActivity().getApplicationContext().startService(intent);
}
//本身寫的接口裏的方法
@Override
public void addNewData(String s) {
try {
JSONObject jsonObject = new JSONObject(s);
String data = jsonObject.getString("data");
//使用handler更新數據 直接更新會空指針
Message message = new Message();
if (data.indexOf("receiveOrder") != -1) {
//搶單成功
message.what = 2;
}
if (data.indexOf("heart") != -1) {
//心跳
message.what = 1;
}
if (data.indexOf("pushOrder") != -1) {
Gson gson = new Gson();
newOrder = gson.fromJson(data, Order.OrderData.OrderList.class);
message.what = 0;
message.obj = newOrder;
}
handler.sendMessage(message);
// update(newOrder);
} catch (JSONException e) {
e.printStackTrace();
}
}