Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

CL-64: To tear down TCP connection upon unsubscribe

  • Loading branch information...
commit 2266fb249a594a7b042fe3981666087510927a92 1 parent b31de70
authored
2  android/PubnubAndroidTest/AndroidManifest.xml
@@ -7,6 +7,8 @@
7 7
 	
8 8
 	<uses-permission android:name="android.permission.INTERNET" />
9 9
 	<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
  10
+	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  11
+	<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
10 12
 
11 13
     <application android:icon="@drawable/icon" android:label="@string/app_name">
12 14
         <activity android:name=".PubnubTestActivity"
1  android/PubnubAndroidTest/lint.xml
... ...
@@ -1,3 +1,4 @@
1 1
 <?xml version="1.0" encoding="UTF-8"?>
2 2
 <lint>
  3
+    <issue id="ParserError" severity="ignore" />
3 4
 </lint>
78  android/PubnubAndroidTest/src/com/fbt/Pubnub.java
@@ -6,7 +6,9 @@
6 6
 import java.io.UnsupportedEncodingException;
7 7
 import java.net.URLEncoder;
8 8
 import java.util.ArrayList;
  9
+import java.util.Enumeration;
9 10
 import java.util.HashMap;
  11
+import java.util.Hashtable;
10 12
 import java.util.Iterator;
11 13
 import java.util.List;
12 14
 import java.util.UUID;
@@ -21,10 +23,14 @@
21 23
 import org.apache.http.client.methods.HttpGet;
22 24
 import org.apache.http.client.methods.HttpUriRequest;
23 25
 import org.apache.http.impl.client.DefaultHttpClient;
  26
+import org.apache.http.params.BasicHttpParams;
  27
+import org.apache.http.params.HttpConnectionParams;
  28
+import org.apache.http.params.HttpParams;
24 29
 import org.json.JSONArray;
25 30
 import org.json.JSONObject;
26 31
 
27 32
 import pubnub.PubnubCrypto;
  33
+import android.content.Context;
28 34
 
29 35
 /**
30 36
  * PubNub 3.1 Real-time Push Cloud API
@@ -44,6 +50,8 @@
44 50
         boolean connected, first;
45 51
     }
46 52
     private List<ChannelStatus> subscriptions;
  53
+	private Hashtable<String, Object> connection = new Hashtable<String, Object>();
  54
+	private Context mContext;
47 55
 
48 56
     /**
49 57
      * PubNub 3.1 with Cipher Key
@@ -247,7 +255,7 @@ public JSONArray publish( HashMap<String, Object> args ) {
247 255
         url.add(message.toString());
248 256
 
249 257
         // Return JSONArray
250  
-        return _request(url);
  258
+		return _request(url, channel);
251 259
     }
252 260
 
253 261
     /**
@@ -353,7 +361,7 @@ private void _subscribe( HashMap<String, Object> args ) {
353 361
                     return;
354 362
 
355 363
                 // Wait for Message
356  
-                JSONArray response = _request(url);
  364
+				JSONArray response = _request(url, channel);
357 365
 
358 366
                 // Stop Connection?
359 367
                 for (ChannelStatus it : subscriptions) {
@@ -500,9 +508,9 @@ public JSONArray history( HashMap<String, Object> args ) {
500 508
         if (this.CIPHER_KEY.length() > 0) {
501 509
             // Decrpyt Messages
502 510
             PubnubCrypto pc = new PubnubCrypto(this.CIPHER_KEY);
503  
-            return pc.decryptJSONArray(_request(url));
  511
+			return pc.decryptJSONArray(_request(url, channel));
504 512
         } else {
505  
-            return _request(url);
  513
+			return _request(url, channel);
506 514
         }
507 515
     }
508 516
 
@@ -519,7 +527,7 @@ public double time() {
519 527
         url.add("time");
520 528
         url.add("0");
521 529
 
522  
-        JSONArray response = _request(url);
  530
+		JSONArray response = _request(url, null);
523 531
         return response.optDouble(0);
524 532
     }
525 533
 
@@ -551,6 +559,18 @@ public void unsubscribe( HashMap<String, Object> args ) {
551 559
                 break;
552 560
             }
553 561
         }
  562
+		Enumeration<String> e = connection.keys();
  563
+		while (e.hasMoreElements()) {
  564
+
  565
+			String ch = (String) e.nextElement();
  566
+			if (ch.equals(channel))
  567
+			{
  568
+				HttpClient http = (HttpClient) connection.get(ch);
  569
+				http.getConnectionManager().shutdown();
  570
+				if (connection.containsKey(ch))
  571
+					connection.remove(ch);
  572
+			}
  573
+		}
554 574
     }
555 575
 
556 576
     /**
@@ -559,7 +579,7 @@ public void unsubscribe( HashMap<String, Object> args ) {
559 579
      * @param List<String> request of url directories.
560 580
      * @return JSONArray from JSON response.
561 581
      */
562  
-    private JSONArray _request(List<String> url_components) {
  582
+	private JSONArray _request(List<String> url_components, String channel) {
563 583
         String   json         = "";
564 584
         StringBuilder url     = new StringBuilder();
565 585
         Iterator<String> url_iterator = url_components.iterator();
@@ -574,15 +594,16 @@ private JSONArray _request(List<String> url_components) {
574 594
             } catch (Exception e) {
575 595
                 e.printStackTrace();
576 596
                 JSONArray jsono = new JSONArray();
577  
-                try { jsono.put("Failed UTF-8 Encoding URL."); }
  597
+                try {
  598
+                	jsono.put(0);
  599
+                	jsono.put("Failed UTF-8 Encoding URL."); }
578 600
                 catch (Exception jsone) {}
579 601
                 return jsono;
580 602
             }
581 603
         }
582 604
 
583 605
         try {
584  
-            
585  
-            PubnubHttpRequest request = new PubnubHttpRequest(url.toString());
  606
+            PubnubHttpRequest request = new PubnubHttpRequest(url.toString(),channel);
586 607
             FutureTask<String> task = new FutureTask<String>(request);
587 608
             Thread t = new Thread(task);
588 609
             t.start();
@@ -592,12 +613,12 @@ private JSONArray _request(List<String> url_components) {
592 613
                 JSONArray jsono = new JSONArray();
593 614
 
594 615
                 try {
595  
-                    jsono.put("Failed to Concurrent HTTP Request.");
  616
+                	jsono.put(0);
  617
+                    jsono.put("Request failed due to missing Internet connection.");
596 618
                 } catch (Exception jsone) {
597 619
                 }
598 620
 
599  
-                e.printStackTrace();
600  
-                System.out.println(e);
  621
+                System.out.println(e.getMessage());
601 622
 
602 623
                 return jsono;
603 624
             }
@@ -606,10 +627,12 @@ private JSONArray _request(List<String> url_components) {
606 627
 
607 628
             JSONArray jsono = new JSONArray();
608 629
 
609  
-            try { jsono.put("Failed JSONP HTTP Request."); }
  630
+            try {
  631
+            	jsono.put(0);
  632
+            	jsono.put("Failed JSONP HTTP Request."); }
610 633
             catch (Exception jsone) {}
611 634
 
612  
-            System.out.println(e);
  635
+            System.out.println(e.getMessage());
613 636
 
614 637
             return jsono;
615 638
         }
@@ -619,11 +642,12 @@ private JSONArray _request(List<String> url_components) {
619 642
         catch (Exception e) {
620 643
             JSONArray jsono = new JSONArray();
621 644
 
622  
-            try { jsono.put("Failed JSON Parsing."); }
  645
+            try {
  646
+            	jsono.put(0);
  647
+            	jsono.put("Failed JSON Parsing."); }
623 648
             catch (Exception jsone) {}
624 649
 
625  
-            e.printStackTrace();
626  
-            System.out.println(e);
  650
+            System.out.println(e.getMessage());
627 651
 
628 652
             // Return Failure to Parse
629 653
             return jsono;
@@ -632,22 +656,28 @@ private JSONArray _request(List<String> url_components) {
632 656
 
633 657
     private class PubnubHttpRequest implements Callable<String> {
634 658
 
635  
-        String url;
  659
+		String url, channel;
636 660
 
637  
-        public PubnubHttpRequest(String url) {
  661
+		public PubnubHttpRequest(String url, String channel) {
638 662
             this.url = url;
  663
+			this.channel = channel;
639 664
         }
640 665
 
641 666
         @Override
642 667
         public String call() throws Exception {
643 668
             // Prepare request
644 669
             String line = "", json = "";
645  
-            HttpClient httpclient = new DefaultHttpClient();
  670
+            HttpParams httpParams = new BasicHttpParams();
  671
+            HttpConnectionParams.setConnectionTimeout(httpParams, 3000);
  672
+            HttpConnectionParams.setSoTimeout(httpParams, 310000);
  673
+            HttpClient httpclient = new DefaultHttpClient(httpParams);
646 674
             HttpUriRequest request = new HttpGet(url);
647 675
             request.setHeader("V", "3.1");
648 676
             request.setHeader("User-Agent", "Java-Android");
649 677
             request.setHeader("Accept-Encoding", "gzip");
650  
-            httpclient.getParams().setParameter("http.connection.timeout", 310000);
  678
+			if (channel != null) {
  679
+				connection.put(channel, httpclient);
  680
+			}
651 681
 
652 682
             // Execute request
653 683
             HttpResponse response;
@@ -674,8 +704,10 @@ public String call() throws Exception {
674 704
                 }
675 705
                 reader.close();
676 706
             }
677  
-
678  
-            return json;
  707
+            if (channel != null) {
  708
+				connection.remove(channel);
  709
+			}
  710
+			return json;
679 711
         }
680 712
     }
681 713
 
1,018  android/PubnubAndroidTest/src/com/fbt/PubnubTestActivity.java
... ...
@@ -1,498 +1,520 @@
1  
-package com.fbt;
2  
-
3  
-import java.util.ArrayList;
4  
-import java.util.HashMap;
5  
-
6  
-import org.json.JSONArray;
7  
-import org.json.JSONObject;
8  
-
9  
-import android.app.Activity;
10  
-import android.app.AlertDialog;
11  
-import android.content.DialogInterface;
12  
-import android.os.AsyncTask;
13  
-import android.os.Bundle;
14  
-import android.os.Handler;
15  
-import android.os.Message;
16  
-import android.util.Log;
17  
-import android.view.View;
18  
-import android.view.View.OnClickListener;
19  
-import android.widget.Button;
20  
-import android.widget.EditText;
21  
-import android.widget.Toast;
22  
-
23  
-/**
24  
- * PubnubTestActivity
25  
- * 
26  
- */
27  
-public class PubnubTestActivity extends Activity {
28  
-
29  
-	Pubnub pubnub;
30  
-	String myMessage = "", channel = "hello_world";
31  
-	EditText ed;
32  
-	RefreshHandler r = new RefreshHandler();
33  
-	int limit = 5;
34  
-
35  
-	/** Called when the activity is first created. */
36  
-	@Override
37  
-	public void onCreate(Bundle savedInstanceState) {
38  
-		super.onCreate(savedInstanceState);
39  
-		setContentView(R.layout.main);
40  
-
41  
-		ed = (EditText) findViewById(R.id.editText1);
42  
-
43  
-		// Android: (Init)
44  
-		pubnub = new Pubnub("demo", // PUBLISH_KEY
45  
-				"demo",          // SUBSCRIBE_KEY
46  
-				"demo",          // SECRET_KEY
47  
-				"",              // CIPHER_KEY
48  
-				true             // SSL_ON?
49  
-		);
50  
-
51  
-		XMLDownloader d = new XMLDownloader();
52  
-		d.execute("xml");
53  
-
54  
-		Button publishBtn = (Button) findViewById(R.id.publishBtn);
55  
-		publishBtn.setOnClickListener(new OnClickListener() {
56  
-
57  
-			public void onClick(View v) {
58  
-
59  
-				// Android: (Publish)
60  
-
61  
-				// Create JSON Message
62  
-				JSONObject message = new JSONObject();
63  
-				try {
64  
-					if (ed.getText().toString() != null
65  
-							&& !ed.getText().toString().equals(""))
66  
-						message.put("Message", ed.getText().toString());
67  
-				} catch (org.json.JSONException jsonError) {
68  
-				}
69  
-
70  
-				// Publish Message
71  
-				HashMap<String, Object> args = new HashMap<String, Object>(2);
72  
-				args.put("channel", channel); // Channel Name
73  
-				args.put("message", message); // JSON Message
74  
-				JSONArray info = pubnub.publish(args);
75  
-
76  
-				// Print Response from PubNub JSONP REST Service
77  
-				System.out.println(info);
78  
-			}
79  
-		});
80  
-
81  
-		Button unsubscribeBtn = (Button) findViewById(R.id.unsubscribeBtn);
82  
-		unsubscribeBtn.setOnClickListener(new OnClickListener() {
83  
-
84  
-			public void onClick(View v) {
85  
-
86  
-				// Android: (Unsubscribe/disconnect)
87  
-				HashMap<String, Object> args = new HashMap<String, Object>(1);
88  
-				args.put("channel", channel);
89  
-				pubnub.unsubscribe(args);
90  
-			}
91  
-		});
92  
-
93  
-		Button subscribeBtn = (Button) findViewById(R.id.subscribeBtn);
94  
-		subscribeBtn.setOnClickListener(new OnClickListener() {
95  
-
96  
-			public void onClick(View v) {
97  
-
98  
-				// Android: (Subscribe)
99  
-				XMLDownloader d = new XMLDownloader();
100  
-				d.execute("xml");
101  
-			}
102  
-		});
103  
-
104  
-		Button historyBtn = (Button) findViewById(R.id.historyBtn);
105  
-		historyBtn.setOnClickListener(new OnClickListener() {
106  
-
107  
-			public void onClick(View v) {
108  
-
109  
-				// Android: (History)
110  
-
111  
-				System.out.print(" HISTORY: ");
112  
-				HashMap<String, Object> args = new HashMap<String, Object>(2);
113  
-				args.put("channel", channel);
114  
-				args.put("limit", limit);
115  
-
116  
-				// Get History
117  
-				JSONArray response = pubnub.history(args);
118  
-
119  
-				// Print Response from PubNub JSONP REST Service
120  
-				try {
121  
-					if (response != null) {
122  
-						StringBuffer messages = new StringBuffer("");
123  
-						for (int i = 0; i < response.length(); i++) {
124  
-							Object o = response.get(i);
125  
-							String message = o.toString() + "\n\n";
126  
-							messages.append(message);
127  
-						}
128  
-						final AlertDialog.Builder b = new AlertDialog.Builder(
129  
-								PubnubTestActivity.this);
130  
-						b.setIcon(android.R.drawable.ic_dialog_alert);
131  
-						b.setTitle("History: ");
132  
-						b.setMessage(messages.toString());
133  
-						b.setNegativeButton("OK",
134  
-								new DialogInterface.OnClickListener() {
135  
-									public void onClick(DialogInterface dialog,
136  
-											int which) {
137  
-									}
138  
-								});
139  
-						b.show();
140  
-					}
141  
-				} catch (Exception e) {
142  
-					e.printStackTrace();
143  
-				}
144  
-			}
145  
-		});
146  
-
147  
-		Button uuidBtn = (Button) findViewById(R.id.uuidBtn);
148  
-		uuidBtn.setOnClickListener(new OnClickListener() {
149  
-
150  
-			public void onClick(View v) {
151  
-
152  
-				// Android: (UUID)
153  
-
154  
-				String uuid = Pubnub.uuid();
155  
-				System.out.println(" UUID: " + uuid);
156  
-				final AlertDialog.Builder b = new AlertDialog.Builder(
157  
-						PubnubTestActivity.this);
158  
-				b.setIcon(android.R.drawable.ic_dialog_alert);
159  
-				b.setTitle("UUID: ");
160  
-				b.setMessage(uuid);
161  
-				b.setNegativeButton("OK",
162  
-						new DialogInterface.OnClickListener() {
163  
-							public void onClick(DialogInterface dialog,
164  
-									int which) {
165  
-							}
166  
-						});
167  
-				b.show();
168  
-			}
169  
-		});
170  
-
171  
-		Button timeBtn = (Button) findViewById(R.id.timeBtn);
172  
-		timeBtn.setOnClickListener(new OnClickListener() {
173  
-
174  
-			public void onClick(View v) {
175  
-
176  
-				// Android: (Time)
177  
-
178  
-				double time = pubnub.time();
179  
-				System.out.println(" Time: " + Double.toString(time));
180  
-				final AlertDialog.Builder b = new AlertDialog.Builder(
181  
-						PubnubTestActivity.this);
182  
-				b.setIcon(android.R.drawable.ic_dialog_alert);
183  
-				b.setTitle("Time: ");
184  
-				b.setMessage(Double.toString(time));
185  
-				b.setNegativeButton("OK",
186  
-						new DialogInterface.OnClickListener() {
187  
-							public void onClick(DialogInterface dialog,
188  
-									int which) {
189  
-							}
190  
-						});
191  
-				b.show();
192  
-			}
193  
-		});
194  
-	}
195  
-
196  
-	public void allMessageClick(View v) {
197  
-		JSONObject message = new JSONObject();
198  
-		try {
199  
-			message.put("some_val", "Hello World! --> ɂ顶@#$%^&*()!");
200  
-			/*
201  
-			 * message.put( "title", "Android PubNub"); message.put( "text",
202  
-			 * "This is a push to all users! woot!"); message.put( "url",
203  
-			 * "http://www.pubnub.com");
204  
-			 */
205  
-		} catch (org.json.JSONException jsonError) {
206  
-		}
207  
-
208  
-		// Publish
209  
-		HashMap<String, Object> args = new HashMap<String, Object>(2);
210  
-		args.put("channel", channel);
211  
-		args.put("message", message);
212  
-		JSONArray response = null;
213  
-		response = pubnub.publish(args);
214  
-		System.out.println(response);
215  
-
216  
-		args = new HashMap<String, Object>(2);
217  
-		args.put("channel", channel);
218  
-		args.put("message", "Hello World");
219  
-
220  
-		response = pubnub.publish(args);
221  
-		System.out.println(response);
222  
-
223  
-		JSONArray array = new JSONArray();
224  
-		array.put("Sunday");
225  
-		array.put("Monday");
226  
-		array.put("Tuesday");
227  
-		array.put("Wednesday");
228  
-		array.put("Thursday");
229  
-		array.put("Friday");
230  
-		array.put("Saturday");
231  
-
232  
-		args = new HashMap<String, Object>(2);
233  
-		args.put("channel", channel);
234  
-		args.put("message", array);
235  
-
236  
-		response = pubnub.publish(args);
237  
-		System.out.println(response);
238  
-	}
239  
-
240  
-	class RefreshHandler extends Handler {
241  
-		@Override
242  
-		public void handleMessage(Message msg) {
243  
-			Log.v("IN", "HANDLER");
244  
-			Toast.makeText(PubnubTestActivity.this, "You got message",
245  
-					Toast.LENGTH_LONG).show();
246  
-			final AlertDialog.Builder b = new AlertDialog.Builder(
247  
-					PubnubTestActivity.this);
248  
-			b.setIcon(android.R.drawable.ic_dialog_alert);
249  
-			b.setTitle("PUBNUB");
250  
-			b.setMessage(myMessage);
251  
-
252  
-			b.setNegativeButton("OK", new DialogInterface.OnClickListener() {
253  
-				public void onClick(DialogInterface dialog, int which) {
254  
-				}
255  
-			});
256  
-			b.show();
257  
-		}
258  
-	};
259  
-
260  
-	class XMLDownloader extends AsyncTask<String, Void, Boolean> {
261  
-
262  
-		@Override
263  
-		protected Boolean doInBackground(String... params) {
264  
-			try {
265  
-				// Android: (Subscribe)
266  
-				
267  
-				class Receiver implements Callback {
268  
-					public boolean subscribeCallback(String channel,
269  
-							Object message) {
270  
-						Log.i("Message Received", message.toString());
271  
-						myMessage = message.toString();
272  
-						r.sendEmptyMessage(0);
273  
-						return true;
274  
-					}
275  
-
276  
-					@Override
277  
-					public void errorCallback(String channel, Object message) {
278  
-						Log.e("ErrorCallback", "Channel:" + channel + "-"
279  
-								+ message.toString());
280  
-					}
281  
-
282  
-					@Override
283  
-					public void connectCallback(String channel) {
284  
-						Log.i("ConnectCallback", "Connected to channel :"
285  
-								+ channel);
286  
-					}
287  
-
288  
-					@Override
289  
-					public void reconnectCallback(String channel) {
290  
-						Log.i("ReconnectCallback", "Reconnected to channel :"
291  
-								+ channel);
292  
-					}
293  
-
294  
-					@Override
295  
-					public void disconnectCallback(String channel) {
296  
-						Log.i("DisconnectCallback", "Disconnected to channel :"
297  
-								+ channel);
298  
-					}
299  
-				}
300  
-
301  
-				// Listen for Messages (Subscribe)
302  
-				HashMap<String, Object> args = new HashMap<String, Object>(2);
303  
-				args.put("channel", channel);         // Channel Name
304  
-				args.put("callback", new Receiver()); // Callback to get response
305  
-				pubnub.subscribe(args);
306  
-
307  
-			} catch (Exception e) {
308  
-				e.printStackTrace();
309  
-				Log.v("ERROR", "While downloading");
310  
-			}
311  
-
312  
-			return Boolean.TRUE;
313  
-		}
314  
-
315  
-		@Override
316  
-		protected void onPreExecute() {
317  
-		}
318  
-
319  
-		protected void onPostExecute(Boolean result) {
320  
-		}
321  
-	}
322  
-
323  
-	String publish_key = "demo", subscribe_key = "demo";
324  
-	String secret_key = "demo", cipher_key = "";
325  
-	Boolean ssl_on = false;
326  
-
327  
-	// User Supplied Options PubNub
328  
-	Pubnub pubnub_user_supplied_options = new Pubnub(publish_key, // OPTIONAL (supply "" to disable)
329  
-			subscribe_key,   // REQUIRED
330  
-			secret_key,      // OPTIONAL (supply "" to disable)
331  
-			cipher_key,      // OPTIONAL (supply "" to disable)
332  
-			ssl_on           // OPTIONAL (supply "" to disable)
333  
-	);
334  
-
335  
-	// High Security PubNub
336  
-	Pubnub pubnub_high_security = new Pubnub(
337  
-	        // Publish Key
338  
-			"pub-c-a30c030e-9f9c-408d-be89-d70b336ca7a0",
339  
-
340  
-			// Subscribe Key
341  
-			"sub-c-387c90f3-c018-11e1-98c9-a5220e0555fd",
342  
-
343  
-			// Secret Key
344  
-			"sec-c-MTliNDE0NTAtYjY4Ni00MDRkLTllYTItNDhiZGE0N2JlYzBl",
345  
-
346  
-			// Cipher Key
347  
-			"YWxzamRmbVjFaa05HVnGFqZHM3NXRBS73jxmhVMkjiwVVXV1d5UrXR1JLSkZFRr"
348  
-					+ "WVd4emFtUm1iR0TFpUZvbiBoYXMgYmVlbxWkhNaF3uUi8kM0YkJTEVlZYVFjBYi"
349  
-					+ "jFkWFIxSkxTa1pGUjd874hjklaTFpUwRVuIFNob3VsZCB5UwRkxUR1J6YVhlQWa"
350  
-					+ "V1ZkNGVH32mDkdho3pqtRnRVbTFpUjBaeGUgYXNrZWQtZFoKjda40ZWlyYWl1eX"
351  
-					+ "U4RkNtdmNub2l1dHE2TTA1jd84jkdJTbFJXYkZwWlZtRnKkWVrSRhhWbFpZVmFz"
352  
-					+ "c2RkZmTFpUpGa1dGSXhTa3hUYTFwR1Vpkm9yIGluZm9ybWFNfdsWQdSiiYXNWVX"
353  
-					+ "RSblJWYlRGcFVqQmFlRmRyYUU0MFpXbHlZV2wxZVhVNFJrTnR51YjJsMWRIRTJU"
354  
-					+ "W91ciBpbmZvcm1hdGliBzdWJtaXR0ZWQb3UZSBhIHJlc3BvbnNlLCB3ZWxsIHJl"
355  
-					+ "VEExWdHVybiB0am0aW9uIb24gYXMgd2UgcG9zc2libHkgY2FuLuhcFe24ldWVns"
356  
-					+ "dSaTFpU3hVUjFKNllWaFdhRmxZUWpCaQo34gcmVxdWlGFzIHNveqQl83snBfVl3",
357  
-
358  
-			// 2048bit SSL ON - ENABLED TRUE
359  
-			false);
360  
-
361  
-	// Channel | Message Test Data (UTF-8)
362  
-	String message = " ~`â¦â§!@#$%^&*(???)+=[]\\{}|;\':,./<>?abcd";
363  
-	Pubnub _pubnub;
364  
-	ArrayList<String> many_channels = new ArrayList<String>();
365  
-	HashMap<String, Object> status = new HashMap<String, Object>(3);
366  
-	HashMap<String, Object> threads = new HashMap<String, Object>(4);
367  
-	int max_retries = 10;
368  
-
369  
-	// Full Unit Test
370  
-	public void runUnitTest(View v) {
371  
-		/*final AlertDialog.Builder b = new AlertDialog.Builder(
372  
-				PubnubTestActivity.this);
373  
-		b.setIcon(android.R.drawable.ic_dialog_alert);
374  
-		b.setTitle("Unit Test");
375  
-		b.setMessage("Please see the logs (Info) for detailed result.");
376  
-		b.setNegativeButton("OK",
377  
-				new DialogInterface.OnClickListener() {
378  
-					public void onClick(DialogInterface dialog,
379  
-							int which) {
380  
-					}
381  
-				});
382  
-		b.show();*/
383  
-		unitTest(pubnub_user_supplied_options);
384  
-		unitTest(pubnub_high_security);
385  
-	}
386  
-
387  
-	private void unitTest(Pubnub pubnub) {
388  
-		_pubnub = pubnub;
389  
-		for (int i = 0; i < max_retries; i++) {
390  
-			many_channels.add("channel_" + i);
391  
-		}
392  
-
393  
-		status.put("sent", 0);
394  
-		status.put("received", 0);
395  
-		status.put("connections", 0);
396  
-
397  
-		for (final String _channel : many_channels) {
398  
-			Thread t = new Thread() {
399  
-				public void run() {
400  
-					HashMap<String, Object> args = new HashMap<String, Object>(2);
401  
-					args.put("channel", _channel);
402  
-					args.put("callback", new ReceivedMessage()); // Callback to get response
403  
-
404  
-					// Listen for Messages (Subscribe)
405  
-					_pubnub.subscribe(args);
406  
-				};
407  
-			};
408  
-			t.start();
409  
-			threads.put(_channel, t);
410  
-
411  
-			try {
412  
-				Thread.sleep(2000);
413  
-			} catch (InterruptedException e) {
414  
-				e.printStackTrace();
415  
-			}
416  
-		}
417  
-	}
418  
-
419  
-	// Callback Interface when a Message is Received
420  
-	class ReceivedMessage implements Callback {
421  
-
422  
-		@Override
423  
-		public boolean subscribeCallback(String channel, Object message) {
424  
-			Integer sent = (Integer) status.get("sent");
425  
-			Integer received = (Integer) status.get("received");
426  
-
427  
-			test(received <= sent, "many sends");
428  
-			status.remove(received);
429  
-			status.put("received", received.intValue() + 1);
430  
-			HashMap<String, Object> args = new HashMap<String, Object>(1);
431  
-			args.put("channel", channel);
432  
-			_pubnub.unsubscribe(args);
433  
-
434  
-			HashMap<String, Object> argsHistory = new HashMap<String, Object>(2);
435  
-			argsHistory.put("channel", channel);
436  
-			argsHistory.put("limit", 2);
437  
-
438  
-			// Get History
439  
-			JSONArray response = _pubnub.history(argsHistory);
440  
-			if (response != null) {
441  
-				test(true, " History with channel " + channel);
442  
-			}
443  
-			return true;
444  
-		}
445  
-
446  
-		@Override
447  
-		public void errorCallback(String channel, Object message) {
448  
-			Log.e("Pubnub", "Channel:" + channel + "-" + message.toString());
449  
-		}
450  
-
451  
-		@Override
452  
-		public void connectCallback(String channel) {
453  
-			Log.e("Pubnub", "Connected to channel :" + channel);
454  
-
455  
-			Integer connections = (Integer) status.get("connections");
456  
-			status.remove(connections);
457  
-			status.put("connections", connections.intValue() + 1);
458  
-
459  
-			JSONArray array = new JSONArray();
460  
-			array.put("Sunday");
461  
-			array.put("Monday");
462  
-			array.put("Tuesday");
463  
-			array.put("Wednesday");
464  
-			array.put("Thursday");
465  
-			array.put("Friday");
466  
-			array.put("Saturday");
467  
-
468  
-			HashMap<String, Object> args = new HashMap<String, Object>(2);
469  
-			args.put("channel", channel);
470  
-			args.put("message", array);
471  
-
472  
-			JSONArray response = _pubnub.publish(args);
473  
-			Integer sent = (Integer) status.get("sent");
474  
-			status.remove(sent);
475  
-			status.put("sent", sent.intValue() + 1);
476  
-
477  
-			test(true, "publish complete");
478  
-			test(true, "publish response" + response);
479  
-		}
480  
-
481  
-		@Override
482  
-		public void reconnectCallback(String channel) {
483  
-			Log.e("Pubnub", "Reconnected to channel :" + channel);
484  
-		}
485  
-
486  
-		@Override
487  
-		public void disconnectCallback(String channel) {
488  
-			Log.e("Pubnub", "Disconnected to channel :" + channel);
489  
-		}
490  
-	}
491  
-
492  
-	private void test(Boolean trial, String name) {
493  
-		if (trial)
494  
-			Log.e("PASS ", name);
495  
-		else
496  
-			Log.e("- FAIL - ", name);
497  
-	}
498  
-}
  1
+package com.fbt;
  2
+
  3
+import java.util.ArrayList;
  4
+import java.util.HashMap;
  5
+
  6
+import org.json.JSONArray;
  7
+import org.json.JSONObject;
  8
+
  9
+import android.app.Activity;
  10
+import android.app.AlertDialog;
  11
+import android.content.DialogInterface;
  12
+import android.os.AsyncTask;
  13
+import android.os.Bundle;
  14
+import android.os.Handler;
  15
+import android.os.Message;
  16
+import android.util.Log;
  17
+import android.view.View;
  18
+import android.view.View.OnClickListener;
  19
+import android.widget.Button;
  20
+import android.widget.EditText;
  21
+import android.widget.Toast;
  22
+
  23
+/**
  24
+ * PubnubTestActivity
  25
+ * 
  26
+ */
  27
+public class PubnubTestActivity extends Activity {
  28
+
  29
+	Pubnub pubnub;
  30
+	String myMessage = "", channel = "hello_world";
  31
+	EditText ed;
  32
+	RefreshHandler r = new RefreshHandler();
  33
+	int limit = 5;
  34
+
  35
+	/** Called when the activity is first created. */
  36
+	@Override
  37
+	public void onCreate(Bundle savedInstanceState) {
  38
+		super.onCreate(savedInstanceState);
  39
+		setContentView(R.layout.main);
  40
+
  41
+		ed = (EditText) findViewById(R.id.editText1);
  42
+
  43
+		// Android: (Init)
  44
+		pubnub = new Pubnub("demo", // PUBLISH_KEY
  45
+				"demo",          // SUBSCRIBE_KEY
  46
+				"demo",          // SECRET_KEY
  47
+				"",              // CIPHER_KEY
  48
+				true             // SSL_ON?
  49
+		);
  50
+		// pubnub.startPubnub(this);
  51
+		XMLDownloader d = new XMLDownloader();
  52
+		d.execute("xml");
  53
+
  54
+		Button publishBtn = (Button) findViewById(R.id.publishBtn);
  55
+		publishBtn.setOnClickListener(new OnClickListener() {
  56
+
  57
+			public void onClick(View v) {
  58
+
  59
+				// Android: (Publish)
  60
+
  61
+				// Create JSON Message
  62
+				JSONObject message = new JSONObject();
  63
+				try {
  64
+					if (ed.getText().toString() != null
  65
+							&& !ed.getText().toString().equals(""))
  66
+						message.put("Message", ed.getText().toString());
  67
+				} catch (org.json.JSONException jsonError) {
  68
+				}
  69
+
  70
+				// Publish Message
  71
+				HashMap<String, Object> args = new HashMap<String, Object>(2);
  72
+				args.put("channel", channel); // Channel Name
  73
+				args.put("message", message); // JSON Message
  74
+				JSONArray info = pubnub.publish(args);
  75
+
  76
+				// Print Response from PubNub JSONP REST Service
  77
+				System.out.println(info);
  78
+				Log.e("Publish", info.toString());
  79
+			}
  80
+		});
  81
+
  82
+		Button unsubscribeBtn = (Button) findViewById(R.id.unsubscribeBtn);
  83
+		unsubscribeBtn.setOnClickListener(new OnClickListener() {
  84
+
  85
+			public void onClick(View v) {
  86
+
  87
+				// Android: (Unsubscribe/disconnect)
  88
+				HashMap<String, Object> args = new HashMap<String, Object>(1);
  89
+				args.put("channel", channel);
  90
+				pubnub.unsubscribe(args);
  91
+			}
  92
+		});
  93
+
  94
+		Button subscribeBtn = (Button) findViewById(R.id.subscribeBtn);
  95
+		subscribeBtn.setOnClickListener(new OnClickListener() {
  96
+
  97
+			public void onClick(View v) {
  98
+
  99
+				// Android: (Subscribe)
  100
+				XMLDownloader d = new XMLDownloader();
  101
+				d.execute("xml");
  102
+			}
  103
+		});
  104
+
  105
+		Button historyBtn = (Button) findViewById(R.id.historyBtn);
  106
+		historyBtn.setOnClickListener(new OnClickListener() {
  107
+
  108
+			public void onClick(View v) {
  109
+
  110
+				// Android: (History)
  111
+
  112
+				System.out.print(" HISTORY: ");
  113
+				HashMap<String, Object> args = new HashMap<String, Object>(2);
  114
+				args.put("channel", channel);
  115
+				args.put("limit", limit);
  116
+
  117
+				// Get History
  118
+				JSONArray response = pubnub.history(args);
  119
+
  120
+				// Print Response from PubNub JSONP REST Service
  121
+				try {
  122
+					if (response != null) {
  123
+						StringBuffer messages = new StringBuffer("");
  124
+						for (int i = 0; i < response.length(); i++) {
  125
+							Object o = response.get(i);
  126
+							String message = o.toString() + "\n\n";
  127
+							messages.append(message);
  128
+						}
  129
+						final AlertDialog.Builder b = new AlertDialog.Builder(
  130
+								PubnubTestActivity.this);
  131
+						b.setIcon(android.R.drawable.ic_dialog_alert);
  132
+						b.setTitle("History: ");
  133
+						b.setMessage(messages.toString());
  134
+						b.setNegativeButton("OK",
  135
+								new DialogInterface.OnClickListener() {
  136
+									public void onClick(DialogInterface dialog,
  137
+											int which) {
  138
+									}
  139
+								});
  140
+						b.show();
  141
+					}
  142
+				} catch (Exception e) {
  143
+					e.printStackTrace();
  144
+				}
  145
+			}
  146
+		});
  147
+
  148
+		Button uuidBtn = (Button) findViewById(R.id.uuidBtn);
  149
+		uuidBtn.setOnClickListener(new OnClickListener() {
  150
+
  151
+			public void onClick(View v) {
  152
+
  153
+				// Android: (UUID)
  154
+
  155
+				String uuid = Pubnub.uuid();
  156
+				System.out.println(" UUID: " + uuid);
  157
+				final AlertDialog.Builder b = new AlertDialog.Builder(
  158
+						PubnubTestActivity.this);
  159
+				b.setIcon(android.R.drawable.ic_dialog_alert);
  160
+				b.setTitle("UUID: ");
  161
+				b.setMessage(uuid);
  162
+				b.setNegativeButton("OK",
  163
+						new DialogInterface.OnClickListener() {
  164
+							public void onClick(DialogInterface dialog,
  165
+									int which) {
  166
+							}
  167
+						});
  168
+				b.show();
  169
+			}
  170
+		});
  171
+
  172
+		Button timeBtn = (Button) findViewById(R.id.timeBtn);
  173
+		timeBtn.setOnClickListener(new OnClickListener() {
  174
+
  175
+			public void onClick(View v) {
  176
+
  177
+				// Android: (Time)
  178
+
  179
+				double time = pubnub.time();
  180
+				System.out.println(" Time: " + Double.toString(time));
  181
+				final AlertDialog.Builder b = new AlertDialog.Builder(
  182
+						PubnubTestActivity.this);
  183
+				b.setIcon(android.R.drawable.ic_dialog_alert);
  184
+				b.setTitle("Time: ");
  185
+				b.setMessage(Double.toString(time));
  186
+				b.setNegativeButton("OK",
  187
+						new DialogInterface.OnClickListener() {
  188
+							public void onClick(DialogInterface dialog,
  189
+									int which) {
  190
+							}
  191
+						});
  192
+				b.show();
  193
+			}
  194
+		});
  195
+	}
  196
+
  197
+	@Override
  198
+	protected void onDestroy() {
  199
+		// TODO Auto-generated method stub
  200
+		super.onDestroy();
  201
+		// pubnub.stopPubnub();
  202
+	}
  203
+
  204
+	@Override
  205
+	protected void onPause() {
  206
+		// TODO Auto-generated method stub
  207
+		super.onPause();
  208
+		// pubnub.stopPubnub();
  209
+	}
  210
+
  211
+	@Override
  212
+	protected void onResume() {
  213
+		// TODO Auto-generated method stub
  214
+		super.onResume();
  215
+		// pubnub.startPubnub(this);
  216
+	}
  217
+
  218
+	public void allMessageClick(View v) {
  219
+		JSONObject message = new JSONObject();
  220
+		try {
  221
+			message.put("some_val", "Hello World! --> ɂ顶@#$%^&*()!");
  222
+			/*
  223
+			 * message.put( "title", "Android PubNub"); message.put( "text",
  224
+			 * "This is a push to all users! woot!"); message.put( "url",
  225
+			 * "http://www.pubnub.com");
  226
+			 */
  227
+		} catch (org.json.JSONException jsonError) {
  228
+		}
  229
+
  230
+		// Publish
  231
+		HashMap<String, Object> args = new HashMap<String, Object>(2);
  232
+		args.put("channel", channel);
  233
+		args.put("message", message);
  234
+		JSONArray response = null;
  235
+		response = pubnub.publish(args);
  236
+		System.out.println(response);
  237
+
  238
+		args = new HashMap<String, Object>(2);
  239
+		args.put("channel", channel);
  240
+		args.put("message", "Hello World");
  241
+
  242
+		response = pubnub.publish(args);
  243
+		System.out.println(response);
  244
+
  245
+		JSONArray array = new JSONArray();
  246
+		array.put("Sunday");
  247
+		array.put("Monday");
  248
+		array.put("Tuesday");
  249
+		array.put("Wednesday");
  250
+		array.put("Thursday");
  251
+		array.put("Friday");
  252
+		array.put("Saturday");
  253
+
  254
+		args = new HashMap<String, Object>(2);
  255
+		args.put("channel", channel);
  256
+		args.put("message", array);
  257
+
  258
+		response = pubnub.publish(args);
  259
+		System.out.println(response);
  260
+	}
  261
+
  262
+	class RefreshHandler extends Handler {
  263
+		@Override
  264
+		public void handleMessage(Message msg) {
  265
+			Log.v("IN", "HANDLER");
  266
+			Toast.makeText(PubnubTestActivity.this, "You got message",
  267
+					Toast.LENGTH_LONG).show();
  268
+			final AlertDialog.Builder b = new AlertDialog.Builder(
  269
+					PubnubTestActivity.this);
  270
+			b.setIcon(android.R.drawable.ic_dialog_alert);
  271
+			b.setTitle("PUBNUB");
  272
+			b.setMessage(myMessage);
  273
+
  274
+			b.setNegativeButton("OK", new DialogInterface.OnClickListener() {
  275
+				public void onClick(DialogInterface dialog, int which) {
  276
+				}
  277
+			});
  278
+			b.show();
  279
+		}
  280
+	};
  281
+
  282
+	class XMLDownloader extends AsyncTask<String, Void, Boolean> {
  283
+
  284
+		@Override
  285
+		protected Boolean doInBackground(String... params) {
  286
+			try {
  287
+				// Android: (Subscribe)
  288
+				
  289
+				class Receiver implements Callback {
  290
+					public boolean subscribeCallback(String channel,
  291
+							Object message) {
  292
+						Log.e("Message Received", message.toString());
  293
+						myMessage = message.toString();
  294
+						r.sendEmptyMessage(0);
  295
+						return true;
  296
+					}
  297
+
  298
+					@Override
  299
+					public void errorCallback(String channel, Object message) {
  300
+						Log.e("ErrorCallback", "Channel:" + channel + "-"
  301
+								+ message.toString());
  302
+					}
  303
+
  304
+					@Override
  305
+					public void connectCallback(String channel) {
  306
+						Log.e("ConnectCallback", "Connected to channel :"
  307
+								+ channel);
  308
+					}
  309
+
  310
+					@Override
  311
+					public void reconnectCallback(String channel) {
  312
+						Log.e("ReconnectCallback", "Reconnecting to channel :"
  313
+								+ channel);
  314
+					}
  315
+
  316
+					@Override
  317
+					public void disconnectCallback(String channel) {
  318
+						Log.e("DisconnectCallback", "Disconnected to channel :"
  319
+								+ channel);
  320
+					}
  <