Java tutorial
/****************************************************************************** * * Copyright 2011 Tavendo GmbH * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ /****************************************************************************** * * Modified By Magnux as an example for IOBahn * ******************************************************************************/ package com.magnux.iobahn.simpleevents; import java.util.Date; import com.magnux.iobahn.SocketIO; import com.magnux.iobahn.SocketIOConnection; import com.magnux.iobahn.simpleevents.R; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.net.ConnectivityManager; import android.net.NetworkInfo; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.TextView; import android.widget.Toast; import java.io.IOException; import java.io.InputStreamReader; import java.net.URI; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.message.BasicNameValuePair; import org.apache.http.NameValuePair; import org.apache.http.util.EntityUtils; import java.util.ArrayList; import java.util.List; import java.util.Timer; import java.util.TimerTask; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; public class SimpleEventsActivity extends Activity { @SuppressWarnings("unused") private static final String TAG = "com.magnux.iobahn.simpleevents"; private static final String PREFS_NAME = "IOBahnSimpleEvents"; private SharedPreferences mSettings; public static Boolean isWantOnline; public static Timer timerReconnect; public static MyTask taskReconnect; public static SimpleEventsActivity currentActive; private static EditText mHostname; private static EditText mPort; private static EditText tfUserId; private static EditText tfUserName; private static Button btnLogin; private static TextView mStatusline; private static Button mStart; private static Button mBtnChat; private static String sessionId; private static String userName; private static String roomId; private static String[] joinRooms; private static EditText tfChat; private final SocketIO mConnection = new SocketIOConnection(); private void alert(String message) { Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); } private void loadPrefs() { mHostname.setText(mSettings.getString("hostname", "54.225.101.120")); mPort.setText(mSettings.getString("port", "8124")); } private void savePrefs() { SharedPreferences.Editor editor = mSettings.edit(); editor.putString("hostname", mHostname.getText().toString()); editor.putString("port", mPort.getText().toString()); editor.commit(); } private void setButtonConnect() { mStart.setText("Connect"); mStart.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { doConnect(); } }); mBtnChat.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { _sendChat(); } }); } private void setButtonDisconnect() { mStart.setText("Disconnect"); mStart.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { SimpleEventsActivity.isWantOnline = false; mConnection.emit("forceDisconnect", null); //mConnection.disconnect(); } }); } class MyTask extends TimerTask { //times member represent calling times. private int times = 0; public void run() { times++; if (times <= 10) { Log.i("Retry Connect Timer: ", "key try reconenct..."); try { if (SimpleEventsActivity.currentActive.isNetworkAvailable()) { //SimpleEventsActivity.currentActive.getDispatchedEpnsPushServerIp(); SimpleEventsActivity.currentActive.doConnect(); } } catch (Exception e) { e.printStackTrace(); } } else { Log.i("Retry Connect Timer:", "Timer stops now....."); //Stop Timer. this.cancel(); } } } /** * We want PubSub events delivered to us in JSON payload to be automatically * converted to this domain POJO. We specify this class later when we subscribe. */ private static class MyEvent { public String text; public Date date; public int millis; @Override public String toString() { return "\ntext: " + text + "\ndate: " + date + "\nmillis: " + millis; } } private static class AddMeEvent { public String userId; public String userName; public String[] joinRooms; public String roomId; public String sessionId; @Override public String toString() { return " userId" + this.userId + "\n userName: " + this.userName + "\n roomId: " + roomId; } } private static class SendChatEvent { public String msg; public String roomId; public String[] joinRooms; public String dateTime; public String senderId; public String senderName; public String sessionId; @Override public String toString() { return " msg" + this.msg + "\n senderName: " + this.senderName; } } private static class TalkEvent { public String created; public String file; public String lat; public String lng; public String talk_session_id; public String[] talk_session_user_ids; @Override public String toString() { return " file" + this.file + "\n talk_session_id: " + this.talk_session_id; } } private static class ConnectionNewEvnet { @Override public String toString() { return ""; } } private static class ConnectionRecoveryEvent { @Override public String toString() { return ""; } } //check internet connetion public boolean isNetworkAvailable() { ConnectivityManager cm = (ConnectivityManager) this.getSystemService(Context.CONNECTIVITY_SERVICE); NetworkInfo ni = cm.getActiveNetworkInfo(); if (ni != null && ni.isConnected()) { // System.out.println("ni.isConnected() = "+ni.isConnected()); return ni.isConnected(); } else { // System.out.println("ni.isConnected() = "+ni.isConnected()); return false; } } public void doConnect() { if (SimpleEventsActivity.taskReconnect != null) { SimpleEventsActivity.taskReconnect.cancel(); } SimpleEventsActivity.taskReconnect = null; //getDispatchedEpnsPushServerIp(); SimpleEventsActivity.currentActive = this; final String wsuri = "ws://" + mHostname.getText() + ":" + mPort.getText(); mStatusline.setText("Connecting to\n" + wsuri + " .."); setButtonDisconnect(); // we establish a connection by giving the WebSockets URL of the server // and the handler for open/close events mConnection.connect(wsuri, new SocketIO.ConnectionHandler() { @Override public void onOpen() { if (SimpleEventsActivity.taskReconnect != null) { SimpleEventsActivity.taskReconnect.cancel(); } SimpleEventsActivity.taskReconnect = null; // The connection was successfully established. we set the status // and save the host/port as Android application preference for next time. mStatusline.setText("Connected to\n" + wsuri); savePrefs(); AddMeEvent addMeEvent = new AddMeEvent(); addMeEvent.sessionId = SimpleEventsActivity.sessionId; // addMeEvent.userName = SimpleEventsActivity.userName; // addMeEvent.roomId = SimpleEventsActivity.roomId; // addMeEvent.joinRooms = SimpleEventsActivity.joinRooms; mConnection.emit("addme", addMeEvent); SimpleEventsActivity.isWantOnline = true; mConnection.on("chat", SendChatEvent.class, new SocketIO.EventHandler() { public void onEvent(Object event) { // when we get an event, we safely can cast to the type we specified previously SendChatEvent evt = (SendChatEvent) event; //alert("Event received : " + evt.toString()); mStatusline.setText("Event received : chat " + evt.senderName + ": " + evt.msg); } }); mConnection.on("connectionNew", ConnectionNewEvnet.class, new SocketIO.EventHandler() { public void onEvent(Object event) { // when we get an event, we safely can cast to the type we specified previously //ConnectionNewEvnet evt = (ConnectionNewEvnet) event; Log.i("connection", "connect to push server new "); } }); mConnection.on("connectionRecovery", ConnectionRecoveryEvent.class, new SocketIO.EventHandler() { public void onEvent(Object event) { // when we get an event, we safely can cast to the type we specified previously //ConnectionNewEvnet evt = (ConnectionNewEvnet) event; Log.i("connection", "connect to push server recovery "); } }); mConnection.on("tw.com.elead.apps.eztalk/talk", TalkEvent.class, new SocketIO.EventHandler() { public void onEvent(Object event) { // when we get an event, we safely can cast to the type we specified previously TalkEvent evt = (TalkEvent) event; //alert("Event received : " + evt.toString()); mStatusline.setText("Event received : evt.file " + evt.talk_session_id + ": " + evt.file); Log.i("talk", "talk Event received : evt.file " + evt.talk_session_id + ": " + evt.file); } }); } @Override public void onClose(int code, String reason) { getDispatchedEpnsPushServerIp(); // The connection was closed. Set the status line, show a message box, // and set the button to allow to connect again. mStatusline.setText("Connection closed."); alert(reason); setButtonConnect(); if (SimpleEventsActivity.isWantOnline) { //1- Taking an instance of Timer class. SimpleEventsActivity.timerReconnect = new Timer("TryReconnect"); //2- Taking an instance of class contains your repeated method. SimpleEventsActivity.taskReconnect = new MyTask(); //TimerTask is a class implements Runnable interface so //You have to override run method with your certain code black //Second Parameter is the specified the Starting Time for your timer in //MilliSeconds or Date //Third Parameter is the specified the Period between consecutive //calling for the method. SimpleEventsActivity.timerReconnect.schedule(SimpleEventsActivity.taskReconnect, 0, 5000); } } }); } private void _sendChat() { SendChatEvent sendChatEvent = new SendChatEvent(); sendChatEvent.msg = SimpleEventsActivity.tfChat.getText().toString(); sendChatEvent.joinRooms = SimpleEventsActivity.joinRooms; sendChatEvent.roomId = SimpleEventsActivity.roomId; sendChatEvent.dateTime = new Date().toString(); sendChatEvent.sessionId = SimpleEventsActivity.sessionId; sendChatEvent.senderName = SimpleEventsActivity.userName; mConnection.emit("sendchat", sendChatEvent); } public void getDispatchedEpnsPushServerIp() { if (SimpleEventsActivity.taskReconnect != null) { SimpleEventsActivity.taskReconnect.cancel(); } SimpleEventsActivity.taskReconnect = null; // Create a new HttpClient and Post Header HttpClient httpclient = new DefaultHttpClient(); HttpPost httppost = new HttpPost("http://192.168.10.11:8124/epns-ip"); //ewhereToken/000jlj9eueatpkvq3k23cuop54 try { // Add your data List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2); nameValuePairs.add(new BasicNameValuePair("ewhereToken", "008ngk6tlh9uc9aojbqcamar36")); nameValuePairs.add(new BasicNameValuePair("epnsToken", "q3kluvhuv0277a62n7e0bomd20")); httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs)); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httppost); if (response.getStatusLine().getStatusCode() == 200) { String strJSONValue = EntityUtils.toString(response.getEntity()); //String strJSONValue = EntityUtils.toString(resEntityGet); JSONObject object = new JSONObject(strJSONValue); //String host = object.getString("host"); String host = "192.168.10.11"; String port = object.getString("port"); String epnsTokenNew = object.getString("epnsToken"); if (!epnsTokenNew.equals("q3kluvhuv0277a62n7e0bomd20")) { Log.i("get epns ip", " redo register EPNS API again, record maybe delete by epns worker"); } else { Log.i("get epns ip", "epnsToken is valid.."); Log.i("GET RESPONSE", host + port + epnsTokenNew); tfUserId.setText(epnsTokenNew); mHostname.setText(host); mPort.setText(port); SimpleEventsActivity.sessionId = tfUserId.getText().toString(); } } } catch (ClientProtocolException e) { // TODO Auto-generated catch block } catch (IOException e) { // TODO Auto-generated catch block } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } // // try { // HttpClient client = new DefaultHttpClient(); // String getURL = "http://192.168.10.11:8124/epns-ip"; // //String getURL = "http://epns.e-where.com.tw:8124/epns-ip"; // HttpGet get = new HttpGet(getURL); // HttpResponse responseGet = client.execute(get); // HttpEntity resEntityGet = responseGet.getEntity(); // if (resEntityGet != null) { // //do something with the response // // String strJSONValue = EntityUtils.toString(resEntityGet); // // JSONObject object = new JSONObject(strJSONValue); // String host = object.getString("host"); // String port = object.getString("port"); // Log.i("GET RESPONSE",host + port); // // mHostname.setText(host); // mPort.setText(port); // // } // } catch (Exception e) { // e.printStackTrace(); // } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); SimpleEventsActivity.currentActive = this; setContentView(R.layout.main); this.isWantOnline = false; mHostname = (EditText) findViewById(R.id.hostname); mPort = (EditText) findViewById(R.id.port); mStatusline = (TextView) findViewById(R.id.statusline); mStart = (Button) findViewById(R.id.start); mBtnChat = (Button) findViewById(R.id.btnChat); tfChat = (EditText) findViewById(R.id.tfChat); tfUserId = (EditText) findViewById(R.id.tfUserId); tfUserName = (EditText) findViewById(R.id.tfUserName); btnLogin = (Button) findViewById(R.id.btnLogin); btnLogin.setOnClickListener(new Button.OnClickListener() { public void onClick(View v) { SimpleEventsActivity.sessionId = tfUserId.getText().toString(); SimpleEventsActivity.userName = tfUserName.getText().toString(); } }); this.roomId = "room1"; this.joinRooms = new String[] { "room1", "room2" }; mSettings = getSharedPreferences(PREFS_NAME, 0); loadPrefs(); setButtonConnect(); getDispatchedEpnsPushServerIp(); } }