实现SocketIO和Service通信使用Notification通知

首先,分清楚 Service 和 IntentService。

之前做的一个笔记:

http://hackeris.me/2014/02/01/android-notifications/

参考:

Service vs IntentService:

http://stackoverflow.com/questions/15524280/service-vs-intent-service

一篇对比了 Service、Thread、IntentService、AsyncTask 四者关系的文章:

http://techtej.blogspot.com.es/2011/03/android-thread-constructspart-4.html

安卓官方参考资料:

http://developer.android.com/training/run-background-service/create-service.html

开始

由于 IntentService 比较方便所以就直接使用 IntentService 了。

新建类,继承 IntentService。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class CallingService extends IntentService {

	public CallingService(String name) {
		super(name);
		// TODO Auto-generated constructor stub
	}

	@Override
	protected void onHandleIntent(Intent intent) {
		// TODO Auto-generated method stub
		
		//do work here
		
		System.out.println(" 成功启动 ");
	}

}

如果这样直接启动 Service 很容易会报 InstantiationException(就在这里卡了一会)
解决:

http://stackoverflow.com/questions/6176255/why-do-i-get-an-instantiationexception-if-i-try-to-start-a-service

只要把构造函数改改就 OK 了

1
2
3
public CallingService() {
	   super("CallingService");
}

启动 IntentService

1
2
Intent intent=new Intent(this, CallingService.class);
startService(intent);

在这个 Service 实现一个内部类, 继承 IOCallback

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
class MySocketIO implements IOCallback  { 
	
	// 构造函数
	public MySocketIO(){

	}
	
	
	@Override
	public void onDisconnect() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onConnect() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onMessage(String data, IOAcknowledge ack) {
		System.out.println("Server said: " + data);
		
	}

	@Override
	public void onMessage(JSONObject json, IOAcknowledge ack) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void on(String event, IOAcknowledge ack, Object... args) {
		// TODO Auto-generated method stub
            
            // 这里接收广播
		
	}

	@Override
	public void onError(SocketIOException socketIOException) {
		// TODO Auto-generated method stub
		
	}

}

Notification 参考上一篇文章。

整个代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
public class CallingService extends IntentService {
	
	private MySocketIO socket;
	long vT[]={300,100,300,100};
	int id, no;
	
	public CallingService() {
	    super("CallingService");
	}

	public CallingService(String name) {
		super(name);
		
	}
	
    @Override
    public IBinder onBind(Intent intent) { 
        Log.d("test", "onBind()"); 
        return super.onBind(intent); 
    } 
  
    @Override
    public void onCreate() { 
        Log.d("test", "onCreate()"); 
        super.onCreate(); 
    } 
  
    @Override
    public void onDestroy() { 
        Log.d("test", "onDestroy()"); 
        super.onDestroy(); 
    } 
  
    @Override
    public void onStart(Intent intent, int startId) { 
        Log.d("test", "onStart()"); 
        super.onStart(intent, startId); 
    } 
  
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) { 
        Log.d("test", "onStartCommand()"); 
        return super.onStartCommand(intent, flags, startId); 
    } 

	@Override 
	protected void onHandleIntent(Intent intent) {
		
		no = intent.getIntExtra("no", -1);
        id = intent.getIntExtra("id", -1);
        socket=new MySocketIO(Common.LOCALHOST, id);
        initNotification(no);
	}
	
	/**
	 * 
	 * @param Myno 拿到的号数
	 * @param nowNo 现在叫的号数
	 */
	@SuppressLint("NewApi")
	private void initNotification(int nowNo){
		
	Intent resultIntent = new Intent(this, MainPager.class);
	

	TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
	
	stackBuilder.addNextIntent(resultIntent);

	PendingIntent resultPendingIntent = 
	                stackBuilder.getPendingIntent(
	                    0,
	                    PendingIntent.FLAG_UPDATE_CURRENT
	                );

	NotificationCompat.Builder mBuilder =           //Notification 的兼容类
	
	                new NotificationCompat.Builder(this)
	
	                .setSmallIcon(R.drawable.ic_launcher)   // 若没有设置 largeicon,此为左边的大 icon,设置了 largeicon,则为右下角的小 icon,无论怎样,都影响 Notifications area 显示的图标
	
	                .setContentTitle(" 您的号数:"+no) // 标题
	
	                .setContentText(" 现叫号数:"+nowNo)         // 正文
	
	                .setOngoing(true)      //true 使 notification 变为 ongoing,用户不能手动清除,类似 QQ,false 或者不设置则为普通的通知
	                
	                .setContentIntent(resultPendingIntent);      
	
	if(no==nowNo){
		mBuilder.setVibrate(vT) ; // 震动
		mBuilder.setDefaults(Notification.DEFAULT_SOUND);// 设置声音,此为默认声音
		mBuilder.setAutoCancel(true);// 点击之后自动消失
	}
				
	
	NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
	
	mNotificationManager.notify(1000, mBuilder.build());


		}
	
	class MySocketIO implements IOCallback  { 

		public SocketIO socket;

		/**
		 * 企业 id
		 */
		private int flag;
		
		// 构造函数
		public MySocketIO( String url,int flag)
		{
			this.flag=flag;
			socket = new SocketIO();
			try { 
				
				socket.connect(url, this);
				
				
			} catch (MalformedURLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		@Override
		public void onDisconnect() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onConnect() {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void onMessage(String data, IOAcknowledge ack) {
			System.out.println("Server said: " + data);
			
		}

		@Override
		public void onMessage(JSONObject json, IOAcknowledge ack) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void on(String event, IOAcknowledge ack, Object... args) {
			// TODO Auto-generated method stub
			if(event.endsWith("nowNumber") ){
				JSONObject object=null;
				if(args.length>0)
				{
					
					 try {
						object=new JSONObject(args[0].toString());
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
					
				}
				int checkFlag = -1 ;
				try {
					checkFlag=object.getInt("id");
				} catch (JSONException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
				if(checkFlag==(flag)){
					try {
						
						initNotification(object.getInt("no"));
						Log.v("test", object.getInt("no")+"");
					} catch (JSONException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}

				}

			}
			
		}

		@Override
		public void onError(SocketIOException socketIOException) {
			// TODO Auto-generated method stub
			
		}

	}

}

实现 SocketIO 和 Service 通信使用 Notification 通知。