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.ccxt.whl; import java.io.File; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import org.apache.http.Header; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.client.ClientProtocolException; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.util.EntityUtils; import android.app.ActivityManager; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.preference.PreferenceManager; import android.util.Log; import com.baidu.frontia.Frontia; import com.baidu.frontia.FrontiaApplication; import com.baidu.frontia.api.FrontiaPush; import com.baidu.frontia.api.FrontiaStatistics; import com.baidu.location.BDLocation; import com.baidu.location.BDLocationListener; import com.baidu.location.LocationClient; import com.baidu.location.LocationClientOption; import com.baidu.mapapi.map.OverlayItem; import com.baidu.mapapi.utils.CoordinateConvert; import com.baidu.mobstat.SendStrategyEnum; import com.baidu.platform.comapi.basestruct.GeoPoint; 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.EMMessage.ChatType; import com.easemob.chat.OnMessageNotifyListener; import com.easemob.chat.OnNotificationClickListener; import com.ccxt.whl.activity.ChatActivity; import com.ccxt.whl.activity.MainActivity; import com.ccxt.whl.activity.BaiduMapActivity.MyLocationListenner; import com.ccxt.whl.activity.BaiduMapActivity.NotifyLister; import com.ccxt.whl.db.DbOpenHelper; import com.ccxt.whl.db.UserDao; import com.ccxt.whl.domain.User; import com.ccxt.whl.utils.CommonUtils; import com.ccxt.whl.utils.HttpRestClient; import com.ccxt.whl.utils.JsonToMapList; import com.ccxt.whl.utils.MyLogger; import com.ccxt.whl.utils.PreferenceUtils; import com.easemob.util.EMLog; import com.loopj.android.http.BaseJsonHttpResponseHandler; import com.loopj.android.http.RequestParams; import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache; import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator; import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache; import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache; import com.nostra13.universalimageloader.core.ImageLoader; import com.nostra13.universalimageloader.core.ImageLoaderConfiguration; import com.nostra13.universalimageloader.core.assist.QueueProcessingType; import com.nostra13.universalimageloader.utils.StorageUtils; public class DemoApplication extends FrontiaApplication { public static Context applicationContext; private static DemoApplication instance; // login user name public final String PREF_USERNAME = "username"; public final String PREF_USERNICKNAME = "usernickname"; private String userName = null; private String userNickName = 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 LocationClient mLocClient; public MyLocationListenner myListener = new MyLocationListenner(); public NotifyLister mNotifyer = null; // ?SDK????bd09, bd09llgcj02bd09ll?? // gcj02 //private static final String COOR_TYPE = "gcj02"; private static final String COOR_TYPE = "bd09ll"; private static final String BAIDU_LOCAL_SDK_SERVICE_NAME = "com.baidu.location.service_v2.9"; // ?sdk??2????app? // setScanSpan < 1000 app? // setScanSpan>=1000,??setScanSpan? // ???sdkapp??? // ???? // ??????app?app??? private static final int SCAN_SPAN_TIME = 500; //private static final String PRODUCT_NAME = "com.youku.paike"; // LocationData locData = null; public static BDLocation lastLocation = null; private static MyLogger Log = MyLogger.yLog(); /******************************?end***************************************/ @Override public void onCreate() { super.onCreate(); /**********************2014-08-08*************************/ mLocClient = new LocationClient(this); mLocClient.registerLocationListener(myListener); setLocationOption(); startLocate(); //Frontia? Frontia.init(this.getApplicationContext(), "yHMQouqcDqWPR5uEZ7GbW6w4"); //? FrontiaStatistics stat = Frontia.getStatistics(); stat.setReportId("32f5355664"); stat.setAppDistributionChannel("??"); stat.enableExceptionLog(); stat.start(SendStrategyEnum.SET_TIME_INTERVAL, 0, 10, false); //? initImageLoader(this); FrontiaPush mPush = Frontia.getPush(); boolean isWorking = mPush.isPushWorking(); if (isWorking) { Log.d("mpush is runing --> stop"); mPush.stop(); } /**********************2014-08-08*************************/ 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; } applicationContext = this; instance = this; // ?SDK,?init() Log.d("EMChat Demo initialize EMChat SDK"); EMChat.getInstance().init(applicationContext); // debugmodetrue?sdk?log EMChat.getInstance().setDebugMode(false); // ?EMChatOptions EMChatOptions options = EMChatManager.getInstance().getChatOptions(); // ??????? options.setAcceptInvitationAlways(false); // ???true options.setNotificationEnable(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("userId", message.getFrom()); intent.putExtra("chatType", ChatActivity.CHATTYPE_SINGLE); } else { //?? //message.getTo()?id intent.putExtra("groupId", message.getTo()); intent.putExtra("chatType", ChatActivity.CHATTYPE_GROUP); } return intent; } }); //connectionlistener??? EMChatManager.getInstance().addConnectionListener(new MyConnectionListener()); //?app??????????? // options.setNotifyText(new OnMessageNotifyListener() { // // @Override // public String onNewMessageNotify(EMMessage message) { // //??message????demo???? // return "?" + message.getFrom() + "????"; // } // // @Override // public String onLatestMessageNotify(EMMessage message, int fromUsersNum, int messageNum) { // return fromUsersNum + "???" + messageNum + "??"; // } // }); options.setNotifyText(new OnMessageNotifyListener() { @Override public String onNewMessageNotify(EMMessage message) { UserDao dao = new UserDao(applicationContext); User user = dao.getUser(message.getFrom()); //? if (!CommonUtils.isNullOrEmpty(user.toString())) { if (user.getHeaderurl() != null && user.getNick() != null) { Log.d("application local_user_is-pass"); //continue;// String nick = ""; if (CommonUtils.isNullOrEmpty(user.getNick())) { nick = "?"; } nick = "" + user.getNick(); return nick + "????"; } } /***********??????***********/ String nickname_tmp = ""; String headurl_tmp = ""; //???id? if (CommonUtils.isNullOrEmpty(user.getUsername()) || CommonUtils.isNullOrEmpty(user.getHeaderurl()) || CommonUtils.isNullOrEmpty(user.getNick())) { String httpUrl = Constant.BASE_URL + Constant.USER_URL_C + "user=" + message.getFrom(); // httpRequest HttpGet httpRequest = new HttpGet(httpUrl); try { // ?HttpClient HttpClient httpclient = new DefaultHttpClient(); // HttpClient?HttpResponse HttpResponse httpResponse = httpclient.execute(httpRequest); // ? if (httpResponse.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { // ? String strResult = EntityUtils.toString(httpResponse.getEntity()); if (!CommonUtils.isNullOrEmpty(strResult)) { Map<String, Object> lm = JsonToMapList.getMap(strResult); if (lm.get("status").toString() != null && lm.get("status").toString().equals("yes")) { if (!CommonUtils.isNullOrEmpty(lm.get("result").toString())) { Map<String, Object> result = JsonToMapList .getMap(lm.get("result").toString()); nickname_tmp = result.get("nickname").toString(); headurl_tmp = result.get("headurl").toString(); Log.d("NotifyListener nickname_tmp and headurl_tmp " + nickname_tmp + " " + headurl_tmp); } } } if (!CommonUtils.isNullOrEmpty(nickname_tmp) && !CommonUtils.isNullOrEmpty(headurl_tmp)) { User user_temp = new User(); user_temp.setUsername(message.getFrom()); user_temp.setNick(nickname_tmp); user_temp.setHeaderurl(headurl_tmp); dao.saveContact_m(user_temp); Log.d("NotifyListener saveContact_m have"); } } } catch (ClientProtocolException e) { Log.e("application" + e.getMessage().toString()); } catch (IOException e) { Log.e("application" + e.getMessage().toString()); } catch (Exception e) { Log.e("application" + e.getMessage().toString()); } } return nickname_tmp + "????"; } @Override public String onLatestMessageNotify(EMMessage message, int fromUsersNum, int messageNum) { return fromUsersNum + "???" + messageNum + "??"; } @Override public String onSetNotificationTitle(EMMessage message) { // TODO Auto-generated method stub UserDao dao = new UserDao(applicationContext); User user = dao.getUser(message.getFrom()); //? if (!CommonUtils.isNullOrEmpty(user.toString())) { if (user.getHeaderurl() != null && user.getNick() != null) { Log.d("application local_user_is-pass"); //continue;// String nick = ""; if (CommonUtils.isNullOrEmpty(user.getNick())) { nick = "?"; } nick = "" + user.getNick(); return nick; } } return "??"; } }); //MobclickAgent.onError(applicationContext); } 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) if (getUser() != 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) { } /** * ??huanxin * * @return */ //public String getUserName() { public String getUser() { if (userName == null) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext); userName = preferences.getString(PREF_USERNAME, null); } return userName; } /** * ?huanxin? * * @return */ public String getPassword() { if (password == null) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext); password = preferences.getString(PREF_PWD, null); } return password; } /** * ?? * * @return */ public String getUsernNickName() { if (userNickName == null) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext); userNickName = preferences.getString(PREF_USERNICKNAME, null); } return userNickName; } /** * * * @param user */ public void setUserNickName(String NickName) { if (NickName != null) { SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext); SharedPreferences.Editor editor = preferences.edit(); if (editor.putString(PREF_USERNICKNAME, NickName).commit()) { userNickName = NickName; } } } /** * huanxin?? * * @param user */ // public void setUserName(String username) { public void setUser(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); } 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; } public String getVersionName() { try { PackageManager manager = this.getPackageManager(); PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0); String version = info.versionName; return version; } catch (Exception e) { e.printStackTrace(); } return "0"; } public int getVersionCode()//??(?) { try { PackageManager manager = this.getPackageManager(); PackageInfo info = manager.getPackageInfo(this.getPackageName(), 0); return info.versionCode; } catch (Exception e) { return 0; } /* try { PackageInfo pi=context.getPackageManager().getPackageInfo(context.getPackageName(), 0); return pi.versionCode; } catch (NameNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); return 0; } */ } /** ?ImageLoader */ public static void initImageLoader(Context context) { File cacheDir = StorageUtils.getOwnCacheDirectory(context, Constant.CACHE_DIR_IMAGE);// ?? Log.d("cacheDir" + cacheDir.getPath()); // ?ImageLoader(?,?)?APPLACATION??? ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context) // ? .threadPoolSize(3).threadPriority(Thread.NORM_PRIORITY - 2).memoryCache(new WeakMemoryCache()) .denyCacheImageMultipleSizesInMemory() /****** / .memoryCache(new LruMemoryCache(2 * 1024 * 1024)) .memoryCacheSize(2 * 1024 * 1024) .memoryCacheSizePercentage(13) // default /***end***/ .discCacheFileNameGenerator(new Md5FileNameGenerator()) // ?URI??MD5 .tasksProcessingOrder(QueueProcessingType.LIFO).discCache(new UnlimitedDiscCache(cacheDir))// // .defaultDisplayImageOptions(DisplayImageOptions.createSimple()) .writeDebugLogs() // Remove for release app .build(); // Initialize ImageLoader with configuration. ImageLoader.getInstance().init(config);// ?? } 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() { } } /***************************?**********************************/ // ? private void setLocationOption() { LocationClientOption option = new LocationClientOption(); option.setOpenGps(true);// gps mLocClient.setLocOption(option); // ?? , option.setCoorType(COOR_TYPE); option.setPoiExtraInfo(true); // ????8??,allwifi?????? option.setAddrType("all"); option.setScanSpan(SCAN_SPAN_TIME); option.setPriority(LocationClientOption.NetWorkFirst); // ,?gps option.setPoiNumber(10); option.disableCache(true);// true??false?? //option.setProdName(PRODUCT_NAME); mLocClient.setLocOption(option); } /** * ??? * @return */ public BDLocation getlastloc() { if (lastLocation != null) { return lastLocation; } return null; } /** * ? * @Title: startLocate * @return void * @date 2013-7-2 ?4:32:26 */ public void startLocate() { if (mLocClient.isStarted()) { mLocClient.requestLocation(); } else { mLocClient.start(); } } /** * ?? * @Title: stopLocate * @return void * @date 2013-7-2 ?4:31:12 */ public void stopLocate() { if (mLocClient.isStarted()) { mLocClient.stop(); } } /** * ?? * @Package com.baidu.locTest * @ClassName: LocationListenner * @author * @mail * @date 2013-7-2 ?4:31:49 */ /** * ????? */ public class MyLocationListenner implements BDLocationListener { @Override public void onReceiveLocation(BDLocation location) { if (location == null) { return; } Log.d("map On location change received:" + location); Log.d("map addr:" + location.getAddrStr()); Log.d("map streed:" + location.getStreet()); //sendButton.setEnabled(true); //if (progressDialog != null) { // progressDialog.dismiss(); //} if (lastLocation != null) { if (lastLocation.getLatitude() == location.getLatitude() && lastLocation.getLongitude() == location.getLongitude()) { Log.d("map same location, skip refresh"); stopLocate(); // mMapView.refresh(); //need this refresh? return; } } lastLocation = location; GeoPoint gcj02Point = new GeoPoint((int) (location.getLatitude() * 1e6), (int) (location.getLongitude() * 1e6)); EMLog.d("loc", "GCJ-02 loc:" + gcj02Point); //GeoPoint point = CoordinateConvert.fromGcjToBaidu(gcj02Point); //EMLog.d("loc", "converted BD-09 loc:" + gcj02Point); stopLocate(); } public void onReceivePoi(BDLocation poiLocation) { if (poiLocation == null) { return; } } } /***************************?**********************************/ /*private void get_add_info(final String toChatUsername, final boolean is_fran) { // TODO Auto-generated method stub *//****************************************??******************************************/ /* //final String toChatUsername = intent.getStringExtra("from"); final UserDao userdao = new UserDao(applicationContext); final User local_user = userdao.getUser(toChatUsername); //? if(CommonUtils.isNullOrEmpty(local_user.toString())){ RequestParams params = new RequestParams(); params.add("user", toChatUsername); HttpRestClient.get(Constant.USER_URL_C, params, new BaseJsonHttpResponseHandler(){ @Override public void onSuccess(int statusCode, Header[] headers, String rawJsonResponse, Object response) { // TODO Auto-generated method stub Log.d("rawJsonResponse", rawJsonResponse); if(CommonUtils.isNullOrEmpty(rawJsonResponse)){ nickname = ""; headurl = ""; } Map<String, Object> lm = JsonToMapList.getMap(rawJsonResponse); if(lm.get("status").toString() != null && lm.get("status").toString().equals("yes")){ if(!CommonUtils.isNullOrEmpty(lm.get("result"))){ Map<String, Object> result = JsonToMapList.getMap(lm.get("result").toString()); nickname = result.get("nickname").toString(); headurl = result.get("headurl").toString(); local_user.setUsername(toChatUsername); local_user.setNick(nickname); local_user.setHeaderurl(headurl); if(is_fran){ userdao.saveContact(local_user); }else{ userdao.saveContact_m(local_user); } }else{ nickname = ""; headurl = ""; } }else{ nickname = ""; headurl = ""; } } @Override public void onFailure(int statusCode, Header[] headers, Throwable throwable, String rawJsonData, Object errorResponse) { // TODO Auto-generated method stub nickname = ""; headurl = ""; } @Override protected Object parseResponse(String rawJsonData, boolean isFailure) throws Throwable { // TODO Auto-generated method stub return null; } }); }else{//?? Log.d("local_user", ""+local_user.toString()); nickname = ""; headurl = ""; } *//****************************************??*****************************************//* }*/ }