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.user; import java.util.Iterator; import java.util.List; import java.util.Map; 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.widget.Toast; import com.baidu.mapapi.SDKInitializer; 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.user.activity.MainActivity; import com.ieeton.user.db.DbOpenHelper; import com.ieeton.user.db.UserDao; import com.ieeton.user.domain.User; import com.ieeton.user.exception.PediatricsApiException; import com.ieeton.user.exception.PediatricsIOException; import com.ieeton.user.exception.PediatricsParseException; import com.ieeton.user.location.IeetonLocation; import com.ieeton.user.models.City; import com.ieeton.user.models.ServerHostData; import com.ieeton.user.models.Settings; import com.ieeton.user.net.NetEngine; import com.ieeton.user.receiver.VoiceCallReceiver; import com.ieeton.user.utils.Constants; import com.ieeton.user.utils.NickNameCache; import com.ieeton.user.utils.Utils; import com.umeng.socialize.bean.SHARE_MEDIA; import com.umeng.socialize.bean.SocializeEntity; import com.umeng.socialize.controller.UMServiceFactory; import com.umeng.socialize.controller.UMSocialService; import com.umeng.socialize.controller.listener.SocializeListeners.SocializeClientListener; public class IeetonApplication extends Application { public static Context applicationContext; private static IeetonApplication 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; public static List<City> mCityList; @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); SDKInitializer.initialize(this); 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(true); boolean[] onoff = Utils.getMessageNotifySetting(applicationContext); // ????true options.setNoticeBySound(onoff[0]); // ?? true options.setNoticedByVibrate(onoff[1]); // ?? true Settings settings = Utils.getSettings(applicationContext); options.setUseSpeaker(settings.getViaLoundSpeaker()); // 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 = NickNameCache.getInstance().get(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) { String formatStr = getResources().getString(R.string.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); new GetDomainUrlsTask().execute(); } public static IeetonApplication 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(); thirdLogOut(); // reset password to null setPassword(null); setContactList(null); // Utils.setMyUid(applicationContext, null); Utils.setMyType(applicationContext, 5); Utils.saveSettings(applicationContext, null); Utils.setNeedBindMobile(applicationContext, false); Intent successIntent = new Intent(Constants.NEED_RELOGIN_ACTION); sendBroadcast(successIntent); } private void thirdLogOut() { String loginType = Utils.getLoginType(applicationContext); if (Constants.LOGIN_MOBILE.equals(loginType)) { return; } SHARE_MEDIA platform = SHARE_MEDIA.QQ; if (Constants.LOGIN_QQ.equals(loginType)) { platform = SHARE_MEDIA.QQ; } else if (Constants.LOGIN_WEIBO.equals(loginType)) { platform = SHARE_MEDIA.SINA; } else if (Constants.LOGIN_WX.equals(loginType)) { platform = SHARE_MEDIA.WEIXIN; } Utils.logd("platform:" + platform); UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login"); mController.deleteOauth(this, platform, new SocializeClientListener() { @Override public void onComplete(int status, SocializeEntity entity) { if (status == 200) { Utils.logd("deleteOauth success"); } else { Utils.logd("deleteOauth failed"); } } @Override public void onStart() { Utils.logd("deleteOauth onStart"); } }); } 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")) { try { Intent intent = new Intent(applicationContext, MainActivity.class); intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.putExtra("conflict", true); startActivity(intent); } catch (SecurityException e) { e.printStackTrace(); } } } @Override public void onConnecting(String progress) { } @Override public void onConnected() { } } private 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) { e.printStackTrace(); mThr = e; return null; } catch (PediatricsParseException e) { e.printStackTrace(); mThr = e; return null; } catch (PediatricsApiException e) { e.printStackTrace(); mThr = e; return null; } JSONObject object = null; try { object = new JSONObject(result); ServerHostData host = new ServerHostData(getApplicationContext(), object); return host; } catch (JSONException e) { e.printStackTrace(); return null; } } @Override protected void onCancelled() { super.onCancelled(); } @Override protected void onPostExecute(ServerHostData result) { if (result == null || result.equals("")) { //IeetonApplication.mServerHostData = null; if (mThr != null) { Utils.handleErrorEvent(mThr, getApplicationContext()); } else { Utils.showToast(getApplicationContext(), R.string.PediatricsParseException, Toast.LENGTH_SHORT); } return; } IeetonApplication.mServerHostData = result; } } }