Java tutorial
/** * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.ieeton.agency; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.RejectedExecutionException; import org.json.JSONException; import org.json.JSONObject; import android.app.ActivityManager; import android.app.Application; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.content.SharedPreferences; import android.content.pm.PackageManager; import android.os.AsyncTask; import android.preference.PreferenceManager; import android.util.Log; import com.easemob.chat.ConnectionListener; import com.easemob.chat.EMChat; import com.easemob.chat.EMChatManager; import com.easemob.chat.EMChatOptions; import com.easemob.chat.EMMessage; import com.easemob.chat.OnMessageNotifyListener; import com.easemob.chat.OnNotificationClickListener; import com.ieeton.agency.activity.MainActivity; import com.ieeton.agency.db.DbOpenHelper; import com.ieeton.agency.db.UserDao; import com.ieeton.agency.domain.User; import com.ieeton.agency.exception.PediatricsApiException; import com.ieeton.agency.exception.PediatricsIOException; import com.ieeton.agency.exception.PediatricsParseException; import com.ieeton.agency.location.IeetonLocation; import com.ieeton.agency.location.IeetonLocationListener; import com.ieeton.agency.models.ServerHostData; import com.ieeton.agency.net.NetEngine; import com.ieeton.agency.receiver.VoiceCallReceiver; import com.ieeton.agency.utils.Constants; import com.ieeton.agency.utils.PreferenceUtils; import com.ieeton.agency.utils.Utils; import com.ieeton.agency.R; public class DemoApplication extends Application { public static String mLoginType = "mobile"; public static Context applicationContext; private static DemoApplication instance; // login user name public final String PREF_USERNAME = "username"; private String userName = null; // login password private static final String PREF_PWD = "pwd"; private String password = null; private Map<String, User> contactList; /** * ?nickname,??userid */ public static String currentUserNick = ""; public static IeetonLocation mIeetonLocation = null; public static ServerHostData mServerHostData = null; private IeetonLocationListener mIeetonLocationListener = new IeetonLocationListener() { @Override public void onLocationStart() { } @Override public void onLocationFinish(IeetonLocation ieetonLocation) { if (ieetonLocation == null) { Log.v("sereinli", "onLocationFinish:null"); return; } mIeetonLocation = ieetonLocation; Log.v("sereinli", "Application lon:" + ieetonLocation.getLongtitude() + " lat:" + ieetonLocation.getLatitude()); Intent successIntent = new Intent(Constants.LOCATION_FINISH_ACTION); sendBroadcast(successIntent); } }; class GetDomainUrlsTask extends AsyncTask<Void, Void, ServerHostData> { private Throwable mThr; @Override protected void onPreExecute() { super.onPreExecute(); } @Override protected ServerHostData doInBackground(Void... arg0) { String result = ""; try { result = NetEngine.getInstance(getApplicationContext()).getDomainUrls(); } catch (PediatricsIOException e) { // TODO Auto-generated catch block e.printStackTrace(); mThr = e; } catch (PediatricsParseException e) { // TODO Auto-generated catch block e.printStackTrace(); mThr = e; } catch (PediatricsApiException e) { // TODO Auto-generated catch block e.printStackTrace(); mThr = e; } JSONObject object = null; try { object = new JSONObject(result); if (!object.getBoolean("error")) { JSONObject json_data = object.optJSONObject("messages").optJSONObject("data"); ServerHostData host = new ServerHostData(json_data); return host; } else { return null; } } catch (JSONException e) { e.printStackTrace(); return null; } } @Override protected void onCancelled() { super.onCancelled(); } @Override protected void onPostExecute(ServerHostData result) { if (result == null || result.equals("")) { mServerHostData = null; return; } mServerHostData = result; } } @Override public void onCreate() { super.onCreate(); Utils.saveIeetonFrom(this); int pid = android.os.Process.myPid(); String processAppName = getAppName(pid); // ?remote serviceif? if (processAppName == null || processAppName.equals("")) { // workaround for baidu location sdk // ?sdk????????application::onCreate // // sdk??? ?pid ?processInfo // processName // application::onCreate service return; } //? //BaiduLocationHelper.startRequestLocation(this, mIeetonLocationListener); //?domain urls try { GetDomainUrlsTask task = new GetDomainUrlsTask(); task.execute(); } catch (RejectedExecutionException e) { e.printStackTrace(); } applicationContext = this; instance = this; // ?SDK,?init() EMChat.getInstance().init(applicationContext); EMChat.getInstance().setDebugMode(false); Log.d("EMChat Demo", "initialize EMChat SDK"); // debugmodetrue?sdk?log // ?EMChatOptions EMChatOptions options = EMChatManager.getInstance().getChatOptions(); // ??app??true options.setUseRoster(true); // ??????? options.setAcceptInvitationAlways(false); // ???true options.setNotifyBySoundAndVibrate( PreferenceUtils.getInstance(applicationContext).getSettingMsgNotification()); // ????true options.setNoticeBySound(PreferenceUtils.getInstance(applicationContext).getSettingMsgSound()); // ?? true options.setNoticedByVibrate(PreferenceUtils.getInstance(applicationContext).getSettingMsgVibrate()); // ?? true options.setUseSpeaker(PreferenceUtils.getInstance(applicationContext).getSettingMsgSpeaker()); // notification?intentintent options.setOnNotificationClickListener(new OnNotificationClickListener() { @Override public Intent onNotificationClick(EMMessage message) { // Intent intent = new Intent(applicationContext, ChatActivity.class); // ChatType chatType = message.getChatType(); // if (chatType == ChatType.Chat) { // ??? // intent.putExtra(ChatActivity.EXTRA_USERID, message.getFrom()); // intent.putExtra("chatType", ChatActivity.CHATTYPE_SINGLE); // } else { // ?? // // message.getTo()?id // intent.putExtra("groupId", message.getTo()); // intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP); // } Intent intent = new Intent(applicationContext, MainActivity.class); return intent; } }); // connectionlistener??? EMChatManager.getInstance().addConnectionListener(new MyConnectionListener()); // ?app??????????? options.setNotifyText(new OnMessageNotifyListener() { @Override public String onNewMessageNotify(EMMessage message) { // ??message????(??qq)demo???? String notify = ""; String passport = message.getFrom(); String nick = Utils.getNickCache(getApplicationContext(), passport); if (nick != null && !"".equals(nick)) { String formatStr = getResources().getString(R.string.new_incoming_messages); notify = nick + String.format(formatStr, "1"); } else { notify = getString(R.string.new_message); } return notify; } @Override public String onLatestMessageNotify(EMMessage message, int fromUsersNum, int messageNum) { //return fromUsersNum + "???" + messageNum + "??"; String formatStr = getResources().getString(R.string.receive_new_messages); String notify = String.format(formatStr, fromUsersNum, messageNum); return notify; } @Override public String onSetNotificationTitle(EMMessage message) { // return getString(R.string.app_name); } @Override public int onSetSmallIcon(EMMessage arg0) { // TODO Auto-generated method stub return 0; } }); //? IntentFilter callFilter = new IntentFilter( EMChatManager.getInstance().getIncomingVoiceCallBroadcastAction()); registerReceiver(new VoiceCallReceiver(), callFilter); } public static DemoApplication getInstance() { return instance; } // List<String> list = new ArrayList<String>(); // list.add("1406713081205"); // options.setReceiveNotNoifyGroup(list); /** * ??user list * * @return */ public Map<String, User> getContactList() { if (getUserName() != null && contactList == null) { UserDao dao = new UserDao(applicationContext); // ??user list,???list contactList = dao.getContactList(); } return contactList; } /** * ?user list * * @param contactList */ public void setContactList(Map<String, User> contactList) { this.contactList = contactList; } public void setStrangerList(Map<String, User> List) { } /** * ???? * * @return */ public String getUserName() { if (userName == null) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext); userName = preferences.getString(PREF_USERNAME, null); } return userName; } /** * ?? * * @return */ public String getPassword() { if (password == null) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext); password = preferences.getString(PREF_PWD, null); } return password; } /** * ?? * * @param user */ public void setUserName(String username) { if (username != null) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext); SharedPreferences.Editor editor = preferences.edit(); if (editor.putString(PREF_USERNAME, username).commit()) { userName = username; } } } /** * ? ?? ?demo?password ? preference sdk * ??? * * @param pwd */ public void setPassword(String pwd) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext); SharedPreferences.Editor editor = preferences.edit(); if (editor.putString(PREF_PWD, pwd).commit()) { password = pwd; } } /** * ,? */ public void logout() { // sdk logout?app? EMChatManager.getInstance().logout(); DbOpenHelper.getInstance(applicationContext).closeDB(); // reset password to null setPassword(null); setContactList(null); Utils.setMyUid(this, ""); Utils.setMyLoginName(this, ""); Utils.setPassport(this, ""); } private String getAppName(int pID) { String processName = null; ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); List l = am.getRunningAppProcesses(); Iterator i = l.iterator(); PackageManager pm = this.getPackageManager(); while (i.hasNext()) { ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next()); try { if (info.pid == pID) { CharSequence c = pm.getApplicationLabel( pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA)); // Log.d("Process", "Id: "+ info.pid +" ProcessName: "+ // info.processName +" Label: "+c.toString()); // processName = c.toString(); processName = info.processName; return processName; } } catch (Exception e) { // Log.d("Process", "Error>> :"+ e.toString()); } } return processName; } class MyConnectionListener implements ConnectionListener { @Override public void onReConnecting() { } @Override public void onReConnected() { } @Override public void onDisConnected(String errorString) { if (errorString != null && errorString.contains("conflict")) { Intent intent = new Intent(applicationContext, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("conflict", true); startActivity(intent); } } @Override public void onConnecting(String progress) { } @Override public void onConnected() { } } }