一、在AndroidManifest.xml中定义action事件
<service
android:name=".service.NettyService">
<intent-filter>
<action android:name="com.hovans.netty.ACTION_CHECK_SESSION" />
<action android:name="com.hovans.netty.ACTION_HEARTBEAT" />
<action android:name="com.hovans.netty.ACTION_CONNECT_SESSION" />
<action android:name="com.hovans.netty.ACTION_DISCONNECT_SESSION" />
</intent-filter>
</service>
二、定义一个Intent类
public class NettyIntent {
public static final String ACTION_CHECK_SESSION = "com.hovans.netty.ACTION_CHECK_SESSION";
public static final String ACTION_HEARTBEAT = "com.hovans.netty.ACTION_HEARTBEAT";
public static final String ACTION_CONNECT_SESSION = "com.hovans.netty.ACTION_CONNECT_SESSION";
public static final String ACTION_DISCONNECT_SESSION = "com.hovans.netty.ACTION_DISCONNECT_SESSION";
}
三、action出发示例代码:
public void onStartClick(View view) {
System.out.println("duanliang,HomeActivity.onStartClick");
startService(new Intent(NettyIntent.ACTION_CONNECT_SESSION));
}
四、action响应示例代码:
public void onWorkerRequest(Intent intent, int i) {
if (NettyIntent.ACTION_CONNECT_SESSION.equals(intent.getAction())) {
if(mChannel != null) {
disconnectSessionIfItNeeds();
}
connectSessionIfItNeeds();
} else if(NettyIntent.ACTION_HEARTBEAT.equals(intent.getAction())) {
if(checkConnection() == false) {
connectSessionIfItNeeds();
}
} else if(NettyIntent.ACTION_CHECK_SESSION.equals(intent.getAction())) {
scheduleToReconnect();
} else if(NettyIntent.ACTION_DISCONNECT_SESSION.equals(intent.getAction())) {
disconnectSessionIfItNeeds();
}
}
其中onWorkerRequest(Intent intent, int i)的定义见博文(待补充)