android 小知識總結

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="   [email protected]">
    </TextView>

</RelativeLayout>




發佈了36 篇原創文章 · 獲贊 7 · 訪問量 20萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章