基于百度云推送的实时通信客户端实现(三)

昨天已经说到了聊天列表的实现,今天来说说聊天界面的实现

在聊天界面会有两种布局,一种是

用户发送的消息的布局

另外一种是

用户收到的消息的布局

所以在这个时候Adapter的布局就需要对应两种界面,代码很简单

 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="fill_parent"
 4     android:layout_height="wrap_content"
 5     android:layout_marginLeft="10dp"
 6     android:background="#eeeeee"
 7     android:gravity="right"
 8     android:orientation="horizontal" >
 9 
10     <LinearLayout
11         android:layout_width="180dp"
12         android:layout_height="wrap_content"
13         android:background="@drawable/outgoing"
14         android:orientation="vertical" >
15 
16         <LinearLayout
17             android:layout_width="fill_parent"
18             android:layout_height="match_parent"
19             android:orientation="vertical" >
20 
21             <TextView
22                 android:id="@+id/person_name"
23                 android:layout_width="fill_parent"
24                 android:layout_height="0dp"
25                 android:layout_weight="1"
26                 android:textColor="#000000"
27                 android:textSize="16sp" />
28 
29             <TextView
30                 android:id="@+id/time_say"
31                 android:layout_width="fill_parent"
32                 android:layout_height="0dp"
33                 android:layout_weight="1"
34                 android:textColor="#69abcd"
35                 android:textSize="16sp" />
36         </LinearLayout>
37 
38         <TextView
39             android:id="@+id/item_say"
40             android:layout_width="fill_parent"
41             android:layout_height="match_parent"
42             android:textColor="#000000"
43             android:textSize="16sp" />
44     </LinearLayout>
45 
46     <ImageView
47         android:id="@+id/person_icon"
48         android:layout_width="42dp"
49         android:layout_height="42dp"
50         android:layout_gravity="bottom"
51         android:background="@drawable/retouxiang"
52         android:contentDescription="@string/app_name" />
53 
54 </LinearLayout>
list_talk_me_item.xml
 1 <?xml version="1.0" encoding="utf-8"?>
 2 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
 3     android:layout_width="fill_parent"
 4     android:layout_height="wrap_content"
 5     android:layout_marginLeft="10dp"
 6     android:background="#eeeeee"
 7     android:orientation="horizontal" >
 8 
 9     <ImageView
10         android:id="@+id/person_icon"
11         android:layout_width="42dp"
12         android:layout_height="42dp"
13         android:layout_gravity="bottom"
14         android:background="@drawable/retouxiang"
15         android:contentDescription="@string/app_name" />
16 
17     <LinearLayout
18         android:layout_width="180dp"
19         android:layout_height="wrap_content"
20         android:background="@drawable/incoming"
21         android:orientation="vertical" >
22 
23         <LinearLayout
24             android:layout_width="fill_parent"
25             android:layout_height="match_parent"
26             android:orientation="vertical" >
27 
28             <TextView
29                 android:id="@+id/person_name"
30                 android:layout_width="fill_parent"
31                 android:layout_height="0dp"
32                 android:layout_weight="1"
33                 android:textColor="#000000"
34                 android:textSize="16sp" />
35 
36             <TextView
37                 android:id="@+id/time_say"
38                 android:layout_width="fill_parent"
39                 android:layout_height="0dp"
40                 android:layout_weight="1"
41                 android:textColor="#69abcd"
42                 android:textSize="16sp" />
43         </LinearLayout>
44 
45         <TextView
46             android:id="@+id/item_say"
47             android:layout_width="fill_parent"
48             android:layout_height="match_parent"
49             android:textColor="#000000"
50             android:textSize="16sp" />
51     </LinearLayout>
52 
53 </LinearLayout>
list_talk_he_item.xml

其实两个布局基本上是一样的,只是ImagineView的位置在左侧或者在右侧的区别,另外,在这里的背景图片使用的是.9.png的格式,为了能够有更好的拉伸效果,不至于在拉伸以后失真

在这里,同样需要创建一个类MessageEnity来存储消息的内容

 1 package com.demo.Adapter;
 2 
 3 public class MessageEnity {
 4 
 5     @SuppressWarnings("unused")
 6     private static final String TAG = MessageEnity.class.getSimpleName();
 7 
 8     private String fromUser;
 9 
10     private String time;
11 
12     private String context;
13 
14     private String toUser;
15 
16     private int LayoutID;
17 
18     public String getfromUser() {
19         return fromUser;
20     }
21 
22     public void setfroUser(String fromUser) {
23         this.fromUser = fromUser;
24     }
25 
26     public String gettomUser() {
27         return toUser;
28     }
29 
30     public void settoUser(String toUser) {
31         this.toUser = toUser;
32     }
33 
34     public String getTime() {
35         return time;
36     }
37 
38     public void setTime(String date) {
39         this.time = date;
40     }
41 
42     public String getItem() {
43         return context;
44     }
45 
46     public void setItem(String text) {
47         this.context = text;
48     }
49 
50     public int getLayoutID() {
51         return LayoutID;
52     }
53 
54     public void setLayoutID(int LayoutID) {
55         this.LayoutID = LayoutID;
56     }
57 
58     public MessageEnity() {
59     }
60 
61     public MessageEnity(String fromUser, String toUser, String date,
62             String text, int LayoutID) {
63         this.fromUser = fromUser;
64         this.toUser = toUser;
65         this.time = date;
66         this.context = text;
67         this.LayoutID = LayoutID;
68     }
69 
70     public MessageEnity(String message,String toUser, String date, int LayoutID) {
71         String[] messages = message.split("@#@");
72         this.fromUser = messages[0];
73         this.context = messages[1];
74         this.toUser = toUser;
75         this.time = date;
76         this.LayoutID = LayoutID;
77     }
78 }
MessageEnity

在这里的Adapter的代码

  1 package com.demo.Adapter;
  2 
  3 import java.util.List;
  4 
  5 import com.tuisong.R;
  6 
  7 import android.content.Context;
  8 import android.database.DataSetObserver;
  9 import android.view.LayoutInflater;
 10 import android.view.View;
 11 import android.view.ViewGroup;
 12 import android.widget.BaseAdapter;
 13 import android.widget.LinearLayout;
 14 import android.widget.TextView;
 15 
 16 public class NewAdapterView extends BaseAdapter {
 17 
 18     @SuppressWarnings("unused")
 19     private static final String TAG = NewAdapterView.class.getSimpleName();
 20 
 21     private List<MessageEnity> coll;
 22 
 23     private Context context;
 24 
 25     // 构造函数
 26     public NewAdapterView(Context context, List<MessageEnity> list) {
 27         this.context = context;
 28         this.coll = list;
 29     }
 30 
 31     public boolean areAllItemsEnabled() {
 32         return false;
 33     }
 34 
 35     public boolean isEnabled(int arg0) {
 36         return false;
 37     }
 38 
 39     @Override
 40     public int getCount() {
 41         // TODO Auto-generated method stub
 42         return coll.size();
 43     }
 44 
 45     @Override
 46     public Object getItem(int arg0) {
 47         // TODO Auto-generated method stub
 48         return coll.get(arg0);
 49     }
 50 
 51     @Override
 52     public long getItemId(int arg0) {
 53         // TODO Auto-generated method stub
 54         return arg0;
 55     }
 56 
 57     public int getItemViewType(int position) {
 58         return position;
 59     }
 60 
 61     @Override
 62     public View getView(int positon, View convertView, ViewGroup parent) {
 63         // TODO Auto-generated method stub
 64         MessageEnity entity = coll.get(positon);
 65         int itemLayout = entity.getLayoutID();
 66 
 67         LinearLayout layout = new LinearLayout(context);
 68         LayoutInflater inflater = (LayoutInflater) context
 69                 .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
 70         inflater.inflate(itemLayout, layout, true);
 71 
 72         TextView tvName = (TextView) layout.findViewById(R.id.person_name);
 73         tvName.setText(entity.getfromUser());
 74 
 75         TextView tvData = (TextView) layout.findViewById(R.id.time_say);
 76         tvData.setText(entity.getTime());
 77 
 78         TextView tvItem = (TextView) layout.findViewById(R.id.item_say);
 79         tvItem.setText(entity.getItem());
 80 
 81         return layout;
 82     }
 83 
 84     public int getViewTypeCount() {
 85         return coll.size();
 86     }
 87 
 88     public boolean hasStableIds() {
 89         return false;
 90     }
 91 
 92     public boolean isEmpty() {
 93         return false;
 94     }
 95 
 96     public void registerDataSetObserver(DataSetObserver observer) {
 97     }
 98 
 99     public void unregisterDataSetObserver(DataSetObserver observer) {
100     }
101 
102 }
NewAdapterView

然后现在上Activity的代码,其实很简单

  1 package com.baidu.push.example;
  2 
  3 import java.io.IOException;
  4 import java.io.UnsupportedEncodingException;
  5 import java.util.ArrayList;
  6 import java.util.List;
  7 
  8 import org.apache.http.HttpResponse;
  9 import org.apache.http.NameValuePair;
 10 import org.apache.http.client.ClientProtocolException;
 11 import org.apache.http.client.entity.UrlEncodedFormEntity;
 12 import org.apache.http.client.methods.HttpPost;
 13 import org.apache.http.impl.client.DefaultHttpClient;
 14 import org.apache.http.message.BasicNameValuePair;
 15 import org.apache.http.protocol.HTTP;
 16 
 17 import com.demo.Adapter.MessageEnity;
 18 import com.demo.Adapter.NewAdapterView;
 19 import com.tuisong.GetDate;
 20 import com.tuisong.R;
 21 import com.tuisong.Save_Read;
 22 
 23 import com.tuisong.db.DBHelpter;
 24 
 25 import android.app.Activity;
 26 import android.app.ProgressDialog;
 27 import android.content.BroadcastReceiver;
 28 import android.content.Context;
 29 import android.content.Intent;
 30 import android.content.SharedPreferences;
 31 import android.os.Bundle;
 32 import android.os.Handler;
 33 import android.os.Message;
 34 import android.view.View;
 35 import android.view.View.OnClickListener;
 36 import android.view.inputmethod.InputMethodManager;
 37 import android.widget.AdapterView;
 38 import android.widget.Button;
 39 import android.widget.EditText;
 40 import android.widget.LinearLayout;
 41 import android.widget.ListAdapter;
 42 import android.widget.ListView;
 43 import android.widget.RelativeLayout;
 44 import android.widget.Toast;
 45 
 46 public class TalkActivity extends Activity {
 47     @SuppressWarnings("unused")
 48     private static final String TAG = TalkActivity.class.getSimpleName();
 49 
 50     private Button messageSend;
 51 
 52     private EditText messageEdit;
 53 
 54     private static ListView messageList;
 55 
 56     public static DBHelpter help;
 57 
 58     public static String openid;
 59 
 60     public int statuecode = 0;
 61 
 62     public static String userid;
 63 
 64     public List<NameValuePair> param;
 65 
 66     private static List<MessageEnity> list;
 67 
 68     private static NewAdapterView adapter;
 69 
 70     public SharedPreferences sp;
 71     public String responcecode;
 72     public ProgressDialog dialog;
 73     public Handler handler;
 74 
 75     @Override
 76     protected void onCreate(Bundle savedInstanceState) {
 77         super.onCreate(savedInstanceState);
 78         setContentView(R.layout.activity_talk);
 79 
 80         @SuppressWarnings("unused")
 81         
 82 
 83         list = new ArrayList<MessageEnity>();
 84         help = new DBHelpter(this);
 85 
 86         Intent intent = getIntent();
 87         openid = intent.getStringExtra("name");
 88         userid = intent.getStringExtra("userid");
 89         System.out.println("the name is " + openid);
 90         System.out.println("the namee is " + userid);
 91         sp = this.getSharedPreferences("key", 0);
 92         SharedPreferences.Editor edtior = sp.edit();
 93         edtior.putString("SSP", openid);
 94         edtior.commit();
 95         messageList = (ListView) findViewById(R.id.messagelist);
 96         messageSend = (Button) findViewById(R.id.messageSend);
 97         messageEdit = (EditText) findViewById(R.id.messageEdit);
 98 
 99         list = help.findPersonMessage(openid, userid);
100 
101         adapter = new NewAdapterView(TalkActivity.this, list);
102         messageList.setAdapter(adapter);
103 
104         messageSend.setOnClickListener(new OnClickListener() {
105 
106             @Override
107             public void onClick(View arg0) {
108 
109                 
110                 System.out.println("the openid is " + openid
111                         + "  the userid is  " + userid);
112                 final MessageEnity message = new MessageEnity(userid, openid,
113                         GetDate.getDate(), getText(),
114                         R.layout.list_talk_me_item);
115                 list.add(message);
116                 messageList.setAdapter(new NewAdapterView(TalkActivity.this,
117                         list));
118                 param = new ArrayList<NameValuePair>();
119                 param.add(new BasicNameValuePair("fromuser", userid));
120                 param.add(new BasicNameValuePair("touser", openid));
121                 param.add(new BasicNameValuePair("message", getText()));
122                 new Thread() {
123                     @Override
124                     public void run() {
125                         // TODO Auto-generated method stub
126 
127                         SendMessage(getText());
128                         if (responcecode.equals("kf102")) {
129                             Toast.makeText(TalkActivity.this, "errsr",
130                                     Toast.LENGTH_SHORT).show();
131                         } else if (responcecode.equals("kf404")) {
132                             Toast.makeText(TalkActivity.this, "eeeee",
133                                     Toast.LENGTH_SHORT).show();
134                         } else if (responcecode.equals("kf500")) {
135                             Toast.makeText(TalkActivity.this, "servicr error",
136                                     Toast.LENGTH_SHORT).show();
137                         } else {
138                             // 把信息插入数据库
139                             help.Insert(message);
140                         }
141                     }
142                 }.start();
143                 while (responcecode == null) {
144                 }
145                 // handler.sendEmptyMessage(0);
146                 System.out.println("the statue code is " + responcecode);
147 
148                 messageEdit.setText("");
149             }
150         });
151 
152     }
153 
154     @Override
155     protected void onResume() {
156         // TODO Auto-generated method stub
157         super.onResume();
158         sp = this.getSharedPreferences("key", 0);
159         SharedPreferences.Editor edtior = sp.edit();
160         edtior.putString("SSP", openid);
161         edtior.commit();
162         // finish();
163     }
164 
165     @Override
166     protected void onDestroy() {
167         // TODO Auto-generated method stub
168         super.onDestroy();
169         sp = this.getSharedPreferences("key", 0);
170         SharedPreferences.Editor edtior = sp.edit();
171         edtior.putString("SSP", openid);
172         edtior.commit();
173     }
174 
175     
176 
177     private String getText() {
178         return messageEdit.getText().toString();
179     }
180 
181     public void SendMessage(String text) {
182         HttpPost post = new HttpPost(
183                 "http://kefuweixin.chinacloudsites.cn/Message/SendMessage");
184         try {
185             post.setEntity(new UrlEncodedFormEntity(param, HTTP.UTF_8));
186             HttpResponse responce = new DefaultHttpClient().execute(post);
187             responcecode = Save_Read.Change(responce);
188 
189         } catch (UnsupportedEncodingException e) {
190             // TODO Auto-generated catch block
191             e.printStackTrace();
192         } catch (ClientProtocolException e) {
193             // TODO Auto-generated catch block
194             e.printStackTrace();
195         } catch (IOException e) {
196             // TODO Auto-generated catch block
197             e.printStackTrace();
198         }
199 
200     }
201 }
TalkActivity

在这里主要还是监听各个状态,表示当前活动Activity的状态

另外还有最重要的东西了,在后台监听推送消息的service

 1 package com.baidu.push.example;
 2 
 3 import android.app.AlertDialog;
 4 import android.app.Notification;
 5 import android.app.NotificationManager;
 6 import android.app.PendingIntent;
 7 import android.content.BroadcastReceiver;
 8 import android.content.Context;
 9 import android.content.Intent;
10 import android.content.SharedPreferences;
11 import android.util.Log;
12 
13 import com.baidu.android.pushservice.PushConstants;
14 import com.demo.Adapter.MessageEnity;
15 import com.tuisong.GetDate;
16 import com.tuisong.R;
17 import com.tuisong.db.DBHelpter;
18 
19 /**
20  * Push消息处理receiver
21  */
22 public class PushMessageReceiver extends BroadcastReceiver {
23     /** TAG to Log */
24     public static final String TAG = PushMessageReceiver.class.getSimpleName();
25     public DBHelpter help;
26     public static final int LYDH = R.layout.list_talk_he_item;
27 
28     public static int NOTIFICATION_ID = 21321;
29     AlertDialog.Builder builder;
30     String content;
31     Context context;
32     public SharedPreferences sp;
33 
34     /**
35      * @param context
36      *            Context
37      * @param intent
38      *            接收的intent
39      */
40     @Override
41     public void onReceive(final Context context, Intent intent) {
42         this.context = context;
43         sp = context.getSharedPreferences("key", 0);
44         help = new DBHelpter(context);
45 
46         if (intent.getAction().equals(PushConstants.ACTION_MESSAGE)) {
47             // 获取消息内容
48             String message = intent.getExtras().getString(
49                     PushConstants.EXTRA_PUSH_MESSAGE_STRING);
50             System.out.println("message is in servce " + message);
51             String toUser = sp.getString("toUser", null);
52             System.out.println("the user id is " + toUser);
53             MessageEnity entity = new MessageEnity(message, toUser,
54                     GetDate.getDate(), LYDH);
55             content = entity.getItem();
56             System.out.println(entity.toString());
57             help.Insert(entity);
58 
59             // 消息的用户自定义内容读取方式
60             Log.i(TAG, "onMessage: " + message);
61 
62             // 自定义内容的json串
63             Log.d(TAG,
64                     "EXTRA_EXTRA = "
65                             + intent.getStringExtra(PushConstants.EXTRA_EXTRA));
66             System.out.println("the string is " + sp.getString("SSP", null));
67             
68             
69 
70         } else if (intent.getAction().equals(PushConstants.ACTION_RECEIVE)) {
71             // 处理绑定等方法的返回数据
72             // PushManager.startWork()的返回值通过PushConstants.METHOD_BIND得到
73 
74             // 获取方法
75             final String method = intent
76                     .getStringExtra(PushConstants.EXTRA_METHOD);
77             // 方法返回错误码。若绑定返回错误(非0),则应用将不能正常接收消息。
78             // 绑定失败的原因有多种,如网络原因,或access token过期。
79             // 请不要在出错时进行简单的startWork调用,这有可能导致死循环。
80             // 可以通过限制重试次数,或者在其他时机重新调用来解决。
81             int errorCode = intent.getIntExtra(PushConstants.EXTRA_ERROR_CODE,
82                     PushConstants.ERROR_SUCCESS);
83             String content = "";
84             if (intent.getByteArrayExtra(PushConstants.EXTRA_CONTENT) != null) {
85                 // 返回内容
86                 content = new String(
87                         intent.getByteArrayExtra(PushConstants.EXTRA_CONTENT));
88             }
89 
90             // 用户在此自定义处理消息,以下代码为demo界面展示用
91             Log.d(TAG, "onMessage: method : " + method);
92             Log.d(TAG, "onMessage: result : " + errorCode);
93             Log.d(TAG, "onMessage: content : " + content);
94 
95         }
96     }
97 
98     
99 }
PushMessageReceiver

这个方法是百度官方实现好的,在这里只需要更具自己的需要来进行修改就好,在我的demo中使用的是百度云推送中的消息的方法,它还提供了通知的富媒体的方法,大家可以根据自己的需要选用

在这里上一下我的Mainfest文件吧

  1 <?xml version="1.0" encoding="utf-8"?>
  2 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
  3     package="haha.haha"
  4     android:versionCode="1"
  5     android:versionName="1.0" >
  6 
  7     <uses-sdk
  8         android:minSdkVersion="7"
  9         android:targetSdkVersion="15" />
 10     <!-- Push service 运行需要的权限 -->
 11     <uses-permission android:name="android.permission.INTERNET" />
 12     <uses-permission android:name="android.permission.READ_PHONE_STATE" />
 13     <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
 14     <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
 15     <uses-permission android:name="android.permission.WRITE_SETTINGS" />
 16     <uses-permission android:name="android.permission.VIBRATE" />
 17 
 18     <!-- for log. -->
 19     <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
 20     <uses-permission android:name="android.permission.ACCESS_DOWNLOAD_MANAGER" />
 21     <uses-permission android:name="android.permission.DOWNLOAD_WITHOUT_NOTIFICATION" />
 22     <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
 23     <uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
 24     <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
 25     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
 26 
 27     <application
 28         android:hardwareAccelerated="true"
 29         android:icon="@drawable/ic_launcher"
 30         android:label="@string/app_name" >
 31         <activity
 32             android:name="com.baidu.push.example.PushDemoActivity"
 33             android:configChanges="orientation|keyboardHidden"
 34             android:label="@string/app_name"
 35             android:launchMode="singleTask" >
 36             <intent-filter>
 37                 <action android:name="android.intent.action.MAIN" />
 38 
 39                 <category android:name="android.intent.category.LAUNCHER" />
 40             </intent-filter>
 41         </activity>
 42         <activity
 43             android:name="com.baidu.push.example.LoginActivity"
 44             android:configChanges="orientation|keyboardHidden"
 45             android:label="@string/login" >
 46         </activity>
 47         <activity
 48             android:name="com.baidu.push.example.CustomActivity"
 49             android:configChanges="orientation|keyboardHidden"
 50             android:label="Push_notification_test" >
 51         </activity>
 52 
 53         <!-- push service rich media display -->
 54         <activity
 55             android:name="com.baidu.android.pushservice.richmedia.MediaViewActivity"
 56             android:configChanges="orientation|keyboardHidden"
 57             android:label="MediaViewActivity" >
 58         </activity>
 59         <activity
 60             android:name="com.baidu.android.pushservice.richmedia.MediaListActivity"
 61             android:configChanges="orientation|keyboardHidden"
 62             android:label="MediaListActivity"
 63             android:launchMode="singleTask" >
 64         </activity>
 65 
 66         <!-- push service client -->
 67         <receiver android:name="com.baidu.push.example.PushMessageReceiver" >
 68             <intent-filter>
 69 
 70                 <!-- 接收push消息 -->
 71                 <action android:name="com.baidu.android.pushservice.action.MESSAGE" />
 72                 <!-- 接收bind,unbind,fetch,delete等反馈消息 -->
 73                 <action android:name="com.baidu.android.pushservice.action.RECEIVE" />
 74                 <action android:name="com.baidu.android.pushservice.action.notification.CLICK" />
 75             </intent-filter>
 76         </receiver>
 77 
 78         <!-- push service -->
 79         <receiver
 80             android:name="com.baidu.android.pushservice.PushServiceReceiver"
 81             android:process=":bdservice_v1" >
 82             <intent-filter>
 83                 <action android:name="android.intent.action.BOOT_COMPLETED" />
 84                 <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
 85                 <action android:name="com.baidu.android.pushservice.action.notification.SHOW" />
 86                 <action android:name="com.baidu.android.pushservice.action.media.CLICK" />
 87             </intent-filter>
 88         </receiver>
 89         <receiver
 90             android:name="com.baidu.android.pushservice.RegistrationReceiver"
 91             android:process=":bdservice_v1" >
 92             <intent-filter>
 93                 <action android:name="com.baidu.android.pushservice.action.METHOD" />
 94                 <action android:name="com.baidu.android.pushservice.action.BIND_SYNC" />
 95             </intent-filter>
 96             <intent-filter>
 97                 <action android:name="android.intent.action.PACKAGE_REMOVED" />
 98 
 99                 <data android:scheme="package" />
100             </intent-filter>
101         </receiver>
102 
103         <service
104             android:name="com.baidu.android.pushservice.PushService"
105             android:exported="true"
106             android:process=":bdservice_v1" />
107 
108         <meta-data
109             android:name="api_key"
110             android:value="oa1jNy3gxNu8Rq0EtXSGdIU2" />
111         <!-- push service end -->
112         <activity
113             android:name="com.baidu.push.example.Web_view"
114             android:label="@string/title_activity_web_view" >
115         </activity>
116     </application>
117 
118 </manifest>
Mainfest.xml

如果照着写到这里,会发现,没有动态更新,只能每次重新加载,这个问题困扰了我好几天,在这里我才用了使用广播的方法来处理,在service中接收到消息之后,发送广播通过定义不同的action来决定把广播发送给就拿一个Activity是否使用状态栏通知

我在PushMessageReceiver添加了如下的代码

 1 Intent intent1 = new Intent();
 2             Intent intent2 = new Intent();
 3             Intent intent3 = new Intent();
 4             intent1.setAction("android.myservice");
 5             intent2.setAction("com.talkmessage");
 6             intent3.setAction("com.newmessage");
 7             if (sp.getString("SSP", null).equals("0")) {
 8                 System.out.println("TAG!");
 9                 // context.sendBroadcast(intent1);
10                 showNotification();
11             } else if (sp.getString("SSP", null).equals("1")) {
12                 System.out.println("TAG@");
13                 context.sendBroadcast(intent1);
14             } else if (sp.getString("SSP", null).equals(entity.getfromUser())) {
15                 System.out.println("TAG#");
16                 context.sendBroadcast(intent2);
17             } else {
18                 System.out.println("TAG$");
19                 // context.sendBroadcast(intent3);
20                 showNotification();
21             }
 1 private void showNotification() {
 2 
 3         NotificationManager notificationManager = (NotificationManager) context
 4                 .getSystemService(android.content.Context.NOTIFICATION_SERVICE);
 5         Notification notification = new Notification(R.drawable.ic_launcher,
 6                 "来新消息了", System.currentTimeMillis());
 7         notification.flags = Notification.FLAG_AUTO_CANCEL;
 8         notification.defaults |= Notification.DEFAULT_VIBRATE;
 9         notification.defaults |= Notification.DEFAULT_LIGHTS;
10         long[] vibrate = { 0, 100, 200, 300 };
11         notification.vibrate = vibrate;
12         PendingIntent contentIntent = PendingIntent.getActivity(context, 0,
13                 new Intent(context, PushDemoActivity.class), 0);
14         notification.setLatestEventInfo(context, "您有新消息", null, contentIntent);
15         notificationManager.notify(NOTIFICATION_ID, notification);
16     }

同时,在两个ACtivity中注册了BroadcastReceiver、

 1 public static class MyReceiver extends BroadcastReceiver {
 2 
 3         @Override
 4         public void onReceive(Context context, Intent intent) {
 5 
 6             String action = intent.getAction();
 7 
 8             if (action.equals("android.myservice")) {
 9                 talk = new ArrayList<TalkListInfo>();
10 
11                 talk = help.findList(userid);
12 
13                 if (talk != null) {
14                     for (TalkListInfo t : talk) {
15 
16                         map.put("name", t.getName());
17                         map.put("time", t.getDate());
18                         map.put("content", t.getItem());
19                     }
20                     adapter = new ListAdapter(context, talk);
21                     list.setAdapter(adapter);
22                 }
23             } else if (action.equals("com.newmessage")) {
24 
25             }
26         }
27 
28     }

同时,在activity的重新唤醒等各个状态中添加了重新构造Adapter是Demo能够真正做到实时更新

最后 我贴上我的代码的完整版本的下载地址吧

http://download.csdn.net/detail/u011321878/7006113

原文地址:https://www.cnblogs.com/cwr941012/p/3586551.html