package com.shawn.tcpclient;
import java.util.ArrayList;
import java.util.HashMap;
import android.R.integer;
import android.os.Bundle;
import android.os.IBinder;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.text.TextUtils;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import com.shawn.tcpclient.MsgRev;
public class MainActivity extends Activity {
/**
* 27 * 通过ServiceConnection的内部类实现来连接Service和Activity 28 * 29
*/
public static final String TAG = "AnetTest";
private static final boolean DEBUG = true; // false
private String msg = "";
private UpdateReceiver mReceiver;
private Context mContext;
private MsgRev mMsgRev;
private int nCount = 0;
private boolean isBinded = false;
EditText sendEditText;
Button sendButton, bindButton, unbindButton, cleanButton;
ListView showList;
SimpleAdapter showItemAdapter; // ListView的适配器
ArrayList<HashMap<String, Object>> showItem; // ListView的数据源,这里是一个HashMap的列表
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContext = MainActivity.this;
// Button bn_conn = (Button) findViewById(R.id.bn_conn);
sendButton = (Button) findViewById(R.id.btn_send);
bindButton = (Button) findViewById(R.id.btn_bind);
unbindButton = (Button) findViewById(R.id.btn_unbind);
cleanButton = (Button) findViewById(R.id.btn_clean);
sendEditText = (EditText) findViewById(R.id.et_send);
showList = (ListView) findViewById(R.id.lv_show);
showItem = new ArrayList<HashMap<String, Object>>(); // listview
showItemAdapter = new SimpleAdapter(this, showItem, R.layout.listview,
new String[] { "image", "title", "text" }, new int[] {
R.id.ItemImage, R.id.ItemTitle, R.id.ItemText });
showList.setAdapter(showItemAdapter);
// 实例化自定义的 BroadcastReceiver
mReceiver = new UpdateReceiver();
IntentFilter filter = new IntentFilter();
// 为 BroadcastReceiver 指定 action ,使之用于接收同 action 的广播
filter.addAction("com.shawn.tcpclient.msg");
// 以编程方式注册 BroadcastReceiver 。配置方式注册 BroadcastReceiver 的例子见
// AndroidManifest.xml 文件
// 一般在 OnStart 时注册,在 OnStop 时取消注册
this.registerReceiver(mReceiver, filter);
/**
* Activity和本地服务交互,需要使用bind和unbind方法
* */
bindButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.d(TAG, "btn_bind onClicked!");
isBinded = bindService(new Intent(
"com.shawn.tcpclient.MsgRev"),
serviceConnection, BIND_AUTO_CREATE);
}
});
unbindButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
try {
Log.d(TAG, "btn_unbind onClicked!");
mContext.unbindService(serviceConnection);
isBinded = false;
} catch (IllegalArgumentException e) {
Toast.makeText(MainActivity.this,
"Service Not Binded,Bind First ~~", 0).show();
Log.e(TAG, "Unbind ERROR: " + e.toString());
e.printStackTrace();
}
}
});
sendButton.setOnClickListener(new OnClickListener() {
public void onClick(View arg0) {
Log.d(TAG, "btn_send onClicked!");
mMsgRev.SendMsg2Server(sendEditText.getText().toString());
}
});
cleanButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Log.d(TAG, "btn_clean onClicked");
nCount = 0;
showItem.clear();
showItemAdapter.notifyDataSetChanged();
}
});
}
// 实现一个 BroadcastReceiver,用于接收指定的 Broadcast
public class UpdateReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d(TAG, "onReceive: " + intent);
msg = intent.getStringExtra("msg");
addItem("第" + nCount++ + "条", msg);
}
}
private ServiceConnection serviceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mMsgRev = ((MsgRev.LocalBinder) service).getService();
Log.d(TAG, "on serivce connected");
}
@Override
public void onServiceDisconnected(ComponentName name) {
mMsgRev = null;
}
};
private void addItem(String title, String context) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("image", R.drawable.ic_launcher);
map.put("title", title);
map.put("text", context);
showItem.add(map);
showItemAdapter.notifyDataSetChanged();
}
private void deleteItem() {
int size = showItem.size();
if (size > 0) {
showItem.remove(showItem.size() - 1);
showItemAdapter.notifyDataSetChanged();
}
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
if (isBinded == true)
unbindService(serviceConnection);
unregisterReceiver(mReceiver);
}
}
ListView动态增删显示操作:http://hi.baidu.com/adxpalpdzbbiuwr/item/68b3aa3bab85f6f4a88428c6
今天碰到一个奇怪的现象,原本正常的程序,在我把layout中的EditText控件跟ListView互换位置后(垂直线性布局,上下调换位置),调试程序出现异常:
03-08 16:57:48.820: E/AndroidRuntime(23411): FATAL EXCEPTION: main
03-08 16:57:48.820: E/AndroidRuntime(23411): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.shawn.tcpclient/com.shawn.tcpclient.MainActivity}: java.lang.ClassCastException: android.widget.ListView
03-08 16:57:48.820: E/AndroidRuntime(23411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
03-08 16:57:48.820: E/AndroidRuntime(23411): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
03-08 16:57:48.820: E/AndroidRuntime(23411): at android.app.ActivityThread.access$1500(ActivityThread.java:117)
03-08 16:57:48.820: E/AndroidRuntime(23411): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
03-08 16:57:48.820: E/AndroidRuntime(23411): at android.os.Handler.dispatchMessage(Handler.java:99)
03-08 16:57:48.820: E/AndroidRuntime(23411): at android.os.Looper.loop(Looper.java:130)
03-08 16:57:48.820: E/AndroidRuntime(23411): at android.app.ActivityThread.main(ActivityThread.java:3687)
03-08 16:57:48.820: E/AndroidRuntime(23411): at java.lang.reflect.Method.invokeNative(Native Method)
03-08 16:57:48.820: E/AndroidRuntime(23411): at java.lang.reflect.Method.invoke(Method.java:507)
03-08 16:57:48.820: E/AndroidRuntime(23411): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
03-08 16:57:48.820: E/AndroidRuntime(23411): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
03-08 16:57:48.820: E/AndroidRuntime(23411): at dalvik.system.NativeStart.main(Native Method)
03-08 16:57:48.820: E/AndroidRuntime(23411): Caused by: java.lang.ClassCastException: android.widget.ListView
03-08 16:57:48.820: E/AndroidRuntime(23411): at com.witcos.shawn.tcpclient.MainActivity.onCreate(MainActivity.java:61)
03-08 16:57:48.820: E/AndroidRuntime(23411): at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
03-08 16:57:48.820: E/AndroidRuntime(23411): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)
03-08 16:57:48.820: E/AndroidRuntime(23411): ... 11 more
后来听看网上的Clean一下就好了,project->clean,估计是资源id没有更新的缘故吧,应该属于sdk的bug,以后注意在修改layout文件后记得clean一下。
ListView的几个重要属性:http://hi.baidu.com/lihezhao/item/52cbc1143b4781f9756a843a
属性重要,android:transcriptMode="alwaysScroll" //适合动态加载,需要看到最新的项时,使用该属性,可以自动滚动
android 如何优雅的主动终止并等待线程的结束? :http://www.dewen.org/q/1957
设置一个BOOLEAN 值去控制, while(isContinue){}每一次循环检测这个BOOLEAN 值变量即可。
Tcp 客户端Client 基于Service,根据网上的代码改的:http://blog.csdn.net/archfree/article/details/6001009
activity代码:
service代码:
package com.shawn.tcpclient;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.channels.SocketChannel;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class MsgRev extends Service {
private final String TAG = "MsgRev service";
private final String ServerIp = "192.168.2.200";
private Integer ServerPort = 12345;
private SocketChannel client = null;
private InetSocketAddress ServerAddress = null;
private ServerListener serverListener;
private boolean isRecieve = false;
public void onCreate() {
Log.d(TAG, "---onCreate---");
super.onCreate();
Connect2Server();
StartServerListener();
}
public void onDestroy() {
Log.d(TAG, "---onDestroy---");
super.onDestroy();
DisConnect2Server();
}
public void onStart(Intent intent, int startId) {
Log.d(TAG, "---onStart---");
super.onStart(intent, startId);
}
/*
* IBinder方法 , LocalBinder 类,mBinder接口这三项用于
* Activity进行Service的绑定,点击发送消息按钮之后触发绑定 并通过Intent将Activity中的EditText的值
* 传送到Service中向服务器发送
*/
@Override
public IBinder onBind(Intent arg0) {
Log.d(TAG, "---onBind---");
return mBinder;
}
public class LocalBinder extends Binder {
MsgRev getService() {
return MsgRev.this;
}
}
private final IBinder mBinder = new LocalBinder();
public void Connect2Server() {
try {
client = SocketChannel.open();
ServerAddress = new InetSocketAddress(ServerIp, ServerPort);
client.connect(ServerAddress);
client.configureBlocking(false);
isRecieve = true;
} catch (Exception e) {
Log.e(TAG, "Connect 2 server ERROR!");
Toast.makeText(MsgRev.this, "Connect Failed!", 0).show();
e.printStackTrace();
}
}
private void DisConnect2Server() {
try {
isRecieve = false; // stop recieve thread
client.close();
} catch (IOException e) {
Log.e(TAG, "Server Disconnect ERROR!!!");
e.printStackTrace();
}
}
// 启动服务器端的监听线程,从Server端接收消息
private void StartServerListener() {
serverListener = new ServerListener();
serverListener.start();
}
private class ServerListener extends Thread {
// private ByteBuffer buf = ByteBuffer.allocate(1024);
public void run() {
try {
// 无限循环,监听服务器,如果有不为空的信息送达,则更新Activity的UI
Log.d(TAG, "ServerListener running...");
ByteBuffer buffer = ByteBuffer.allocate(1024);
while (isRecieve) {
buffer.clear();
client.read(buffer);
buffer.flip();
Charset charset = Charset.forName("UTF-8");
CharsetDecoder decoder = charset.newDecoder();
CharBuffer charBuffer;
charBuffer = decoder.decode(buffer);
String result = charBuffer.toString();
if (result.length() > 0) {
Log.d(TAG, "#####get data-->>>" + result);
// shownotification(result);
broadcastMsg(result);
}
try {
Thread.sleep(200);
} catch (Exception e) {
Log.e(TAG, "Thread sleep failed!!!");
}
}
} catch (CharacterCodingException e) {
Log.e(TAG, "Character Coding Error");
e.printStackTrace();
} catch (IOException e) {
Log.e(TAG, "Server Listener IO error");
e.printStackTrace();
}
Log.d(TAG, "ServerListener stoped~~~");
}
}
private void broadcastMsg(String msg) {
// 指定广播目标的 action (注:指定了此 action 的 receiver 会接收此广播)
Intent intent = new Intent("com.shawn.tcpclient.msg");
// 需要传递的参数
intent.putExtra("msg", msg);
// 发送广播
Log.d(TAG, "####### Broadcast Msg-->>>" + msg);
this.sendBroadcast(intent);
}
public void SendMsg2Server(String msg) {
Log.d(TAG, "#####Send msg 2 server-->>>" + msg);
try {
ByteBuffer bytebufer = ByteBuffer.allocate(1024);
bytebufer = ByteBuffer.wrap(msg.getBytes("UTF-8"));
client.write(bytebufer);
bytebufer.flip();
} catch (Exception e) {
Log.e(TAG, "Send msg 2 server ERROR!!!");
e.printStackTrace();
}
}
private void shownotification(String tab) {
System.out.println("shownotification=====" + tab);
NotificationManager barmanager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification msg = new Notification(
android.R.drawable.stat_notify_chat, "A Message Coming!",
System.currentTimeMillis());
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, MainActivity.class),
PendingIntent.FLAG_ONE_SHOT);
msg.setLatestEventInfo(this, "Message", "Message:" + tab, contentIntent);
barmanager.notify(0, msg);
}
}
xml代码 main:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<ListView
android:id="@+id/lv_show"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.05"
android:fadeScrollbars="true"
android:transcriptMode="alwaysScroll" >
</ListView>
<EditText
android:id="@+id/et_send"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:hint="send" >
</EditText>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btn_bind"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Bind" />
<Button
android:id="@+id/btn_unbind"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Unbind" />
</LinearLayout>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content" >
<Button
android:id="@+id/btn_send"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Send" />
<Button
android:id="@+id/btn_clean"
android:layout_width="95dp"
android:layout_height="wrap_content"
android:layout_weight="0.5"
android:text="Clean" />
</LinearLayout>
</LinearLayout>
listview代码xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/RelativeLayout01"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:paddingBottom="4dip"
android:paddingLeft="12dip"
android:paddingRight="12dip" >
<ImageView
android:id="@+id/ItemImage"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:paddingTop="4dip"
android:src="@drawable/ic_launcher" >
</ImageView>
<TextView
android:id="@+id/ItemTitle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="@+id/ItemImage"
android:text="Hello World"
android:textSize="24dip" >
</TextView>
<TextView
android:id="@+id/ItemText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/ItemTitle"
android:layout_toRightOf="@+id/ItemImage"
android:text=" shingykongcn@gmail.com">
</TextView>
</RelativeLayout>