微信聊天

client_MainActivity

package com.example.day3;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
public class MainActivity extends AppCompatActivity {
  private EditText input;
  private TextView info;
  private final int UPDATE_UI = 1;
  @SuppressLint("HandlerLeak") private Handler mHandler = new Handler() {
    @Override public void handleMessage(Message msg) {
      switch (msg.what) {
        case UPDATE_UI:
          info.setText(msg.obj.toString());
          break;
      }
    }
  };
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    input = findViewById(R.id.input);
    info = findViewById(R.id.info);
    findViewById(R.id.query).setOnClickListener(new View.OnClickListener() {
      @Override public void onClick(View v) {
        new Thread(
            new Runnable() {
              @Override public void run() {
                //在build.gradle中声明使用
                //添加依赖
                //getRequestData(input.getText().toString());
                postRequestData(input.getText().toString());
              }
            }
        ).start();
      }
    });
  }
  private String url = "http://tcc.taobao.com/cc/json/mobile_tel_segment.htm";
  private void getRequestData(String phoneNum) {
    //1 创建 HttpClient
    HttpClient client = HttpClients.createDefault();
    //HttpUriRequest
    HttpGet get = new HttpGet(url + "?tel=" + phoneNum);
    try {
      //shift f6 重构
      //执行请求
      HttpResponse response = client.execute(get);
      //获取结果
      int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode == 200) {
        String result = EntityUtils.toString(response.getEntity());
        mHandler.sendMessage(mHandler.obtainMessage(UPDATE_UI, result));
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }/
  private void postRequestData(String phoneNum) {
    try {
      //创建HttpClient
      HttpClient client = HttpClients.createDefault();
      //post请求
      HttpPost post = new HttpPost(url);
      // 构建请求参数
      List<NameValuePair> params = new ArrayList<>();
      params.add(new BasicNameValuePair("tel", phoneNum));
      //请求体
      post.setEntity(new UrlEncodedFormEntity(params));
      //执行请求
      HttpResponse response = client.execute(post);
      //获取结果
      int statusCode = response.getStatusLine().getStatusCode();
      if (statusCode == 200) {
        String result = EntityUtils.toString(response.getEntity());
        mHandler.sendMessage(mHandler.obtainMessage(UPDATE_UI, result));
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
}

Message_MainActivity

import android.annotation.SuppressLint;
import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class MainActivity extends AppCompatActivity {

  private MessageAdapter mAdapter;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ListView listView = findViewById(R.id.messages);
    mAdapter = new MessageAdapter(this);
    listView.setAdapter(mAdapter);

    mockData();
  }

  @SuppressLint("StaticFieldLeak") private void mockData() {
    new AsyncTask<Void, Void, List<MessageBean>>(){
      @Override protected List<MessageBean> doInBackground(Void... voids) {
        List<MessageBean> result = new ArrayList<>();

        Random random = new Random();

        for (int i = 0; i < 20; i++) {
          result.add(new MessageBean("消息: " + i, random.nextBoolean()));
        }

        return result;
      }

      @Override protected void onPostExecute(List<MessageBean> messageBeans) {
        mAdapter.setDatas(messageBeans);
      }
    }.execute();
  }
}

MessageAdapter

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;
import java.util.ArrayList;
import java.util.List;

public class MessageAdapter extends BaseAdapter {
  private List<MessageBean> mDatas;
  private Context mContext;
  //总共有两种条目:左    右
  					item_count
  private final int ITEM_COUNT = 2;// 0 - 1
  					left_item
  private final int LEFT_ITEM = 0;
  					right_item
  private final int RIGHT_ITEM = 1;
  //1  0
  //为什么

  @Override public int getItemViewType(int position) {
    if (getItem(position).isRec()) {
      return LEFT_ITEM;
    } else {
      return RIGHT_ITEM;
    }
  }

  @Override public int getViewTypeCount() {
    return ITEM_COUNT;
  }

  public MessageAdapter(Context mContext) {
    this.mContext = mContext;
    mDatas = new ArrayList<>();
  }

  public void setDatas(List<MessageBean> datas) {
    this.mDatas = datas;
    notifyDataSetChanged();
  }

  @Override public int getCount() {
    return mDatas.size();
  }

  @Override public MessageBean getItem(int position) {
    return mDatas.get(position);
  }

  @Override public long getItemId(int position) {
    return position;
  }

  @Override public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder viewHolder;
    if (convertView == null) {
      //加载布局
      convertView = LayoutInflater.from(mContext).inflate(
          getItemViewType(position) == LEFT_ITEM ? R.layout.left_item : R.layout.right_item
          , parent, false);
      viewHolder = new ViewHolder();
      viewHolder.message = convertView.findViewById(R.id.message);
      convertView.setTag(viewHolder);
    } else {
      viewHolder = (ViewHolder) convertView.getTag();
    }

    //
    viewHolder.message.setText(getItem(position).getMessage());

    return convertView;
  }

  class ViewHolder {
    private TextView message;
  }
}

展开阅读全文

没有更多推荐了,返回首页