Android Studio-個推-實現簡單聊天(三)
阿新 • • 發佈:2018-12-18
因為之前的是寫的主要程式碼,現在貼出全部程式碼,有些瑕疵,哈哈哈哈。那我現在開始貼程式碼吧
1.聊天實體類 (1)聊天實體類 ChatUser.java
package com.smxy.lj.chat; import java.io.Serializable; public class ChatUser implements Serializable { private String cid; private String msg; public ChatUser() { } public ChatUser(String cid, String msg) { this.cid = cid; this.msg = msg; } public String getCid() { return cid; } public void setCid(String cid) { this.cid = cid; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }
(2)聊天介面實體類
package com.smxy.lj.message; public class Message { public static final int TYPE_RECEIVED = 0;//訊息型別-收到的訊息 public static final int TYPE_SENT = 1;//訊息型別-發出的訊息 private String content; //訊息內容 private int type;//訊息型別 public Message(String content, int type) { this.content = content; this.type = type; } public String getContent() { return content; } public int getType() { return type; } }
(3)個推服務類 DemoIntentService.java
package com.smxy.lj.chat; import android.content.Context; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.support.annotation.Nullable; import android.util.Log; import com.igexin.sdk.GTIntentService; import com.igexin.sdk.message.GTCmdMessage; import com.igexin.sdk.message.GTNotificationMessage; import com.igexin.sdk.message.GTTransmitMessage; import com.smxy.lj.utils.MyLog; import com.smxy.lj.utils.SharedPreferencesHelper; /** * 繼承 GTIntentService 接收來自個推的訊息, 所有訊息線上程中回撥, 如果註冊了該服務, 則務必要在 AndroidManifest中宣告, 否則無法接受訊息<br> * onReceiveMessageData 處理透傳訊息<br> * onReceiveClientId 接收 cid <br> * onReceiveOnlineState cid 離線上線通知 <br> * onReceiveCommandResult 各種事件處理回執 <br> */ public class DemoIntentService extends GTIntentService { SharedPreferencesHelper sharedPreferencesHelper ; private OnProgressListener onProgressListener; public void setOnProgressListener(OnProgressListener onProgressListener) { this.onProgressListener = onProgressListener; } @Override public void onReceiveServicePid(Context context, int i) { } @Override public void onReceiveClientId(Context context, String clientid) { Log.e(TAG, "onReceiveClientId -> " + "clientid = " + clientid); sharedPreferencesHelper = new SharedPreferencesHelper(getApplicationContext(),"push_CID"); sharedPreferencesHelper.put("cid",clientid); //MyLog.e("CID="+ sharedPreferencesHelper.getSharedPreference("cid",null)); } //接收訊息 ---透傳 @Override public void onReceiveMessageData(Context context, GTTransmitMessage gtTransmitMessage) { Log.e(TAG, "onReceiveMessageData -> " + "message = " + new String(gtTransmitMessage.getPayload())); if (onProgressListener!=null){ onProgressListener.onProgress(new String(gtTransmitMessage.getPayload())); } } @Nullable @Override public IBinder onBind(Intent intent) { return new MyGeTui(); } public class MyGeTui extends Binder{ public DemoIntentService get(){ return DemoIntentService.this; } } @Override public void onReceiveOnlineState(Context context, boolean b) { } @Override public void onReceiveCommandResult(Context context, GTCmdMessage gtCmdMessage) { } @Override public void onNotificationMessageArrived(Context context, GTNotificationMessage gtNotificationMessage) { } @Override public void onNotificationMessageClicked(Context context, GTNotificationMessage gtNotificationMessage) { } //回撥,將接收的內容傳到主介面 public interface OnProgressListener { void onProgress(String progress); } }
2.首先是聊天介面 (1)寫聊天介面的adapter message_adapter.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="10dp">
<LinearLayout
android:id="@+id/left_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:background="@drawable/message_left">
<TextView
android:id="@+id/left_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp" />
</LinearLayout>
<LinearLayout
android:id="@+id/right_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="right"
android:background="@drawable/message_right">
<TextView
android:id="@+id/right_msg"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="10dp" />
</LinearLayout>
</LinearLayout>
MsgAdapter.java
package com.smxy.lj.message;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;
import com.smxy.lj.officedemo.R;
import org.w3c.dom.Text;
import java.util.List;
public class MsgAdapter extends RecyclerView.Adapter<MsgAdapter.ViewHolder> {
private List<Message> mMsgList;
static class ViewHolder extends RecyclerView.ViewHolder {
LinearLayout leftLayout, rightLayout;
TextView leftMsg, rightMsg;
public ViewHolder(View view) {
super( view );
leftLayout = view.findViewById( R.id.left_layout );
rightLayout = view.findViewById( R.id.right_layout );
leftMsg = view.findViewById( R.id.left_msg );
rightMsg = view.findViewById( R.id.right_msg );
}
}
public MsgAdapter(List<Message> mMsgList) {//構造方法
this.mMsgList = mMsgList;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from( parent.getContext() ).inflate( R.layout.message_item, parent, false );
return new ViewHolder( view );
}
@Override
public void onBindViewHolder(MsgAdapter.ViewHolder holder, int position) {
Message msg = mMsgList.get( position );
switch (msg.getType()) {
//收到訊息,顯示左邊佈局,隱藏右邊佈局
case Message.TYPE_RECEIVED:
holder.leftLayout.setVisibility( View.VISIBLE );
holder.rightLayout.setVisibility( View.GONE );
holder.leftMsg.setText( msg.getContent() );
break;
//傳送訊息,顯示右邊佈局,隱藏左邊佈局
case Message.TYPE_SENT:
holder.leftLayout.setVisibility( View.GONE );
holder.rightLayout.setVisibility( View.VISIBLE );
holder.rightMsg.setText( msg.getContent() );
break;
default:
break;
}
}
@Override
public int getItemCount() {
return mMsgList.size();
}
}
(2)聊天介面 memo_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v7.widget.RecyclerView
android:id="@+id/msg_recycler_view"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1"/>
<LinearLayout
android:layout_width="match_parent"
android:orientation="horizontal"
android:layout_height="wrap_content">
<EditText
android:id="@+id/message_text"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:hint="Type Something Here"
/>
<Button
android:id="@+id/message_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="傳送" />
</LinearLayout>
</LinearLayout>
MessageFragment.java
package com.smxy.lj.myfragment;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.smxy.lj.adapter.MessageNoticeAdapter;
import com.smxy.lj.chat.ChatUser;
import com.smxy.lj.chat.DemoIntentService;
import com.smxy.lj.message.Message;
import com.smxy.lj.message.MsgAdapter;
import com.smxy.lj.officedemo.R;
import com.smxy.lj.okhttputil.HttpUtil;
import com.smxy.lj.pojo.MessageNotice;
import com.smxy.lj.utils.MyLog;
import com.smxy.lj.utils.ServletUrl;
import com.smxy.lj.utils.SharedPreferencesHelper;
import java.io.IOException;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;
public class MessageFragment extends BaseFragement {
ChatUser chatUser;
//public static String URL = "http://lj1757620885.6655.la:54746/office/pushMessage?cid=";
private SharedPreferencesHelper sharedPreferencesHelper;
private String CID,sendMesageContent;//好友的CID
private List<Message> msgList = new ArrayList<>();
@BindView(R.id.message_text) EditText inputText;
@BindView(R.id.msg_recycler_view) RecyclerView msgRecyclerView;
private MsgAdapter msgAdapter;
private DemoIntentService msgService;
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.memo_lists, null);
ButterKnife.bind(this,view);
Intent intent = new Intent(getActivity(), DemoIntentService.class);
getActivity().bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
initMsgs();
inputText = view.findViewById(R.id.message_text);
msgRecyclerView = view.findViewById(R.id.msg_recycler_view);
LinearLayoutManager layoutManager = new LinearLayoutManager(getActivity());
msgRecyclerView.setLayoutManager(layoutManager);
msgAdapter = new MsgAdapter(msgList);
msgRecyclerView.setAdapter(msgAdapter);
return view;
}
private void initMsgs() {
//chatUser = new ChatUser();
sharedPreferencesHelper = new SharedPreferencesHelper(getContext(),"push_CID");
CID = (String) sharedPreferencesHelper.getSharedPreference("cid",null);
MyLog.e("CID==="+CID);
Message msg1 = new Message("物一群的邀請碼是多少", Message.TYPE_RECEIVED);
msgList.add(msg1);
Message msg2 = new Message("0X897888V", Message.TYPE_SENT);
msgList.add(msg2);
Message msg3 = new Message("謝謝你", Message.TYPE_RECEIVED);
msgList.add(msg3);
}
@OnClick(R.id.message_send)
public void sedMessage(){
sendMesageContent = inputText.getText().toString();
chatUser = new ChatUser();
chatUser.setCid("fb61f569efd33cf3eb536eb945537acb");
chatUser.setMsg(sendMesageContent);
if (!"".equals(sendMesageContent)) {
Message msg = new Message(sendMesageContent, Message.TYPE_SENT);
msgList.add(msg);
//當有新訊息時,呼叫介面卡notifyItemInserted通知列表有新的資料插入,重新整理RecyclerView
msgAdapter.notifyItemInserted(msgList.size() - 1);
//將RecyclerView定位到最後一行,保證可以看到最新訊息
msgRecyclerView.scrollToPosition(msgList.size() - 1);
inputText.setText("");
Gson gson = new Gson();
String json = gson.toJson(chatUser);
HttpUtil.getCall("/pushMessage",json).enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
}
@Override
public void onResponse(Call call, Response response) throws IOException {
}
});
}
}
ServiceConnection mServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
msgService = ((DemoIntentService.MyGeTui) iBinder).get();
msgService.setOnProgressListener(new DemoIntentService.OnProgressListener() {
@Override
public void onProgress(String progress) {
// mProgressBar.setProgress(progress);
android.os.Message message = android.os.Message.obtain();
message.obj = progress;
mHandler.sendMessage(message);
}
});
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
};
private Handler mHandler = new Handler(new Handler.Callback() {
@Override
public boolean handleMessage(android.os.Message message) {
Message msg = new Message((String) message.obj, Message.TYPE_RECEIVED);
msgList.add(msg);
//當有新訊息時,呼叫介面卡notifyItemInserted通知列表有新的資料插入,重新整理RecyclerView
msgAdapter.notifyItemInserted(msgList.size() - 1);
//將RecyclerView定位到最後一行,保證可以看到最新訊息
msgRecyclerView.scrollToPosition(msgList.size() - 1);
return true;
}
});
}
【聊天介面的圖片使用的是【.9.png】圖片】