com.grass.caishi.cc.MyApplication.java Source code

Java tutorial

Introduction

Here is the source code for com.grass.caishi.cc.MyApplication.java

Source

/**
 * 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.grass.caishi.cc;

import java.io.File;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.http.Header;
import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.preference.PreferenceManager;

import com.grass.caishi.cc.activity.main.MainActivity;
import com.grass.caishi.cc.db.UserDao;
import com.grass.caishi.cc.utils.CommonUtils;
import com.grass.caishi.cc.utils.HttpRestClient;
import com.grass.caishi.cc.utils.ImageUtils;
import com.grass.caishi.cc.utils.JsonToMapList;
import com.grass.caishi.cc.utils.PreferenceUtils;
import com.baidu.location.service.LocationService;
import com.baidu.mapapi.SDKInitializer;
import com.easemob.EMCallBack;
import com.easemob.chat.ConnectionListener;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.TextMessageBody;
import com.easemob.util.DeviceUuidFactory;
import com.grass.caishi.cc.domain.User;
import com.loopj.android.http.RequestParams;
import com.loopj.android.http.TextHttpResponseHandler;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
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;
import com.tencent.bugly.crashreport.CrashReport;
import com.umeng.socialize.Config;
import com.umeng.socialize.PlatformConfig;

public class MyApplication extends Application {

    public static Context applicationContext;
    private static MyApplication instance;
    // login user name
    public final String PREF_USERNAME = "username";
    public final String PREF_USERNICKNAME = "usernick";
    public String userName;
    public String userNickName;

    public ArrayList<String> images = new ArrayList<String>();
    public List<Bitmap> list_bit = new ArrayList<Bitmap>();
    public LocationService locationService;
    /**
     * ?nickname,??userid
     */
    // public static String currentUserNick = "";
    public static DemoHXSDKHelper hxSDKHelper = new DemoHXSDKHelper();

    /****************************** ? ***************************************/
    // public static BDLocation lastLocation = null;
    // public LocationClient mLocationClient;
    // public MyLocationListener mMyLocationListener;

    /****************************** ?end ***************************************/

    @Override
    public void onCreate() {
        super.onCreate();
        EMChat.getInstance().setAutoLogin(true);
        applicationContext = this;
        instance = this;

        // setLocationOption();
        // startLocate();
        // Frontia?

        // ?

        PlatformConfig.setWeixin("wx46ee00afcc13fe34", "fb4d4de7222843909154667a92fb9563");
        PlatformConfig.setQQZone("1105049139", "fOqStICu14TpFDiv");
        Config.OpenEditor = true;
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
        // ?remote serviceif?
        if (processAppName == null || processAppName.equals("") || processAppName.equals("null")) {
            // workaround for baidu location sdk
            // ?sdk????????application::onCreate
            // 
            // sdk??? ?pid ?processInfo
            // processName
            // application::onCreate service 
            return;
        }
        CrashReport.initCrashReport(applicationContext, "900009775", false);
        if (!CommonUtils.isNullOrEmpty(getUserID())) {
            CrashReport.setUserId(getUserID()); // ??ID9527
        }
        locationService = new LocationService(getApplicationContext());
        SDKInitializer.initialize(getApplicationContext());
        initImageLoader(this);
        images.clear();
        list_bit.clear();
        /**
         * this function will initialize the HuanXin SDK
         * 
         * @return boolean true if caller can continue to call HuanXin related APIs after calling onInit, otherwise false.
         * 
         *         ?SDK true??falsefalse????
         * 
         *         for example: ?
         * 
         *         public class DemoHXSDKHelper extends HXSDKHelper
         * 
         *         HXHelper = new DemoHXSDKHelper(); if(HXHelper.onInit(context)){ // do HuanXin related work }
         */

        if (hxSDKHelper.onInit(applicationContext)) {
            // do HuanXin related work
        }

    }

    public static MyApplication getInstance() {
        return instance;
    }

    public String getDrivedId() {
        DeviceUuidFactory Deviceid = new DeviceUuidFactory(applicationContext);
        return Deviceid.getDeviceUuid().toString();
    }

    public void setMatchImages(String path) {
        images.add(path);
        list_bit.add(ImageUtils.revitionImageSize(path));
    }

    public void clearMatchImage() {
        images.clear();
        list_bit.clear();
    }

    public ArrayList<String> getMatchImages() {
        return images;
    }

    public void removeMatchImage(int num) {
        if (num > -1 && num < images.size()) {
            images.remove(num);
            list_bit.remove(num);
        }
    }

    public Bitmap getMatchImageBitmap(int num) {
        return list_bit.get(num);
    }

    /**
     * ??user list
     * 
     * @return
     */
    public Map<String, User> getContactList(boolean refresh) {
        return hxSDKHelper.getContactList(refresh);
    }

    /**
     * ??user list
     * 
     * @return
     */
    public Map<String, User> refreshContactList() {
        return hxSDKHelper.getContactList(true);
    }

    /**
     * ?user list
     * 
     * @param contactList
     */
    public void setContactList(Map<String, User> contactList) {
        hxSDKHelper.setContactList(contactList);
    }

    /**
     * ?user list
     * 
     * @param contactList
     */
    public void setContactUser(User user) {
        hxSDKHelper.setContactUser(user);
    }

    public void addContactList(Map<String, User> contactList) {
        hxSDKHelper.addContactList(contactList);
    }

    /**
     * ????
     * 
     * @return
     */
    public String getUserName() {
        return hxSDKHelper.getHXId();
    }

    /**
     * ??
     * 
     * @return
     */
    public String getPassword() {
        return hxSDKHelper.getPassword();
    }

    /**
     * ??
     * 
     * @param user
     */
    public void setUserName(String username) {
        hxSDKHelper.setHXId(username);
    }

    /**
     * ? ?? ?demo?password ? preference sdk ???
     * 
     * @param pwd
     */
    public void setPassword(String pwd) {
        hxSDKHelper.setPassword(pwd);
    }

    /**
     * ,?
     */
    public void logout(final EMCallBack emCallBack) {
        // sdk logout?app?
        hxSDKHelper.logout(emCallBack);
    }

    /**
     * ??huanxin 
     * 
     * @return
     */
    // public String getUserName() {
    public String getUser() {
        if (userName == null) {
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
            userName = preferences.getString(PREF_USERNAME, null);
        }
        return userName;
    }

    /**
     * ??
     * 
     * @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) {
            CrashReport.setUserId(username);
            SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(applicationContext);
            SharedPreferences.Editor editor = preferences.edit();
            if (editor.putString(PREF_USERNAME, username).commit()) {
                userName = username;
            }
        }
    }

    /**
     * ,?
     */
    public void logout(final boolean isGCM, final EMCallBack emCallBack) {
        // sdk logout?app?
        logout(isGCM, emCallBack);
        // hxSDKHelper.logout(callback);
        // EMChatManager.getInstance().logout();
        // DbOpenHelper.getInstance(applicationContext).closeDB();
        // PreferenceUtils.getInstance(getApplicationContext()).clearUserInfo();
        // // 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_LOAND_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);// ??

        ImageLoaderConfiguration.Builder config = new ImageLoaderConfiguration.Builder(context);
        config.threadPriority(Thread.NORM_PRIORITY - 2);
        config.denyCacheImageMultipleSizesInMemory();
        config.diskCacheFileNameGenerator(new Md5FileNameGenerator());
        config.diskCacheSize(50 * 1024 * 1024); // 50 MiB
        config.tasksProcessingOrder(QueueProcessingType.LIFO);
        // config.diskCache(DefaultConfigurationFactory.createDiskCache(applicationContext, cacheDir, 0, 0));
        // config.writeDebugLogs(); // Remove for release app

        // Initialize ImageLoader with configuration.
        ImageLoader.getInstance().init(config.build());
    }

    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() {
    // mLocationClient = new LocationClient(this.getBaseContext());
    // mMyLocationListener = new MyLocationListener();
    // mLocationClient.registerLocationListener(mMyLocationListener);
    //
    // InitLocation();
    //
    // }

    // private void InitLocation() {
    // LocationClientOption option = new LocationClientOption();
    // option.setLocationMode(LocationMode.Battery_Saving);// ??
    // option.setCoorType("bd09ll");// ??gcj02
    // option.setScanSpan(5000);// ??5000ms
    // option.setIsNeedAddress(true);
    // mLocationClient.setLocOption(option);
    // }

    /**
     * ??
     */
    // public class MyLocationListener implements BDLocationListener {
    //
    // @Override
    // public void onReceiveLocation(BDLocation location) {
    // // Receive Location
    // if (location == null)
    // return;
    // 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;
    // }
    // } else {
    // lastLocation = location;
    // }
    // PreferenceUtils.getInstance(getApplicationContext()).setSettingUserWhere(lastLocation.getAddrStr());
    //
    // GeoPoint gcj02Point = new GeoPoint((int) (location.getLatitude() * 1e6),
    // (int) (location.getLongitude() * 1e6));
    //
    // if (!CommonUtils.isNullOrEmpty(location.getAddrStr())) {
    // stopLocate();
    // }
    // }
    //
    // }

    public int getVoteNum() {
        return PreferenceUtils.getInstance(applicationContext).getSettingUserVote();
    }

    public void setMatchVote_Do(RequestParams params) {
        HttpRestClient.post(Constant.SEND_MATCH_VOTE_ADD_DO, params, new TextHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                // TODO Auto-generated method stub
                System.out.println(responseString);
                Map<String, Object> m = JsonToMapList.getMap(responseString);
                if (m != null && m.get("ok").toString().equals("1")) {
                    // ?? 
                    int vote = PreferenceUtils.getInstance(applicationContext).getSettingUserVote();
                    PreferenceUtils.getInstance(applicationContext).setSettingUserVote(vote - 1);
                    if (m.get("data") != null && !CommonUtils.isNullOrEmpty(m.get("data"))) {
                        Map<String, Object> da = JsonToMapList.getMap(m.get("data").toString());
                        if (!CommonUtils.isNullOrEmpty(da.get("vote_num"))) {
                            int vote_num = Integer.valueOf(da.get("vote_num").toString());
                            PreferenceUtils.getInstance(applicationContext).setSettingUserVote(vote_num);
                        }

                        if (CommonUtils.isNullOrEmpty(da.get("toUserName"))) {
                            return;
                        }
                        String userName = da.get("toUserName").toString();
                        sendVoteMessage(userName, da.get("user").toString(), da.get("info").toString());
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // TODO Auto-generated method stub

            }
        });
    }

    public void setMatchZan_Do(RequestParams params) {
        HttpRestClient.post(Constant.SEND_MATCH_ZAN_ADD_DO, params, new TextHttpResponseHandler() {
            @Override
            public void onSuccess(int statusCode, Header[] headers, String responseString) {
                // TODO Auto-generated method stub
                Map<String, Object> m = JsonToMapList.getMap(responseString);
                if (m != null && m.get("ok").toString().equals("1")) {
                    if (m.get("data") != null && !CommonUtils.isNullOrEmpty(m.get("data"))) {
                        Map<String, Object> da = JsonToMapList.getMap(m.get("data").toString());
                        if (CommonUtils.isNullOrEmpty(da.get("toUserName"))) {
                            return;
                        }
                        String userName = da.get("toUserName").toString();
                        sendVoteMessage(userName, da.get("user").toString(), da.get("info").toString());
                    }
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                // TODO Auto-generated method stub

            }
        });
    }

    public void sendVoteMessage(String userName, String user_info, String msg) {
        if (userName.equals(getUserName())) {
            return;
        }
        if (user_info != null) {
            Map<String, Object> m = JsonToMapList.getMap(user_info);
            if (m == null || CommonUtils.isNullOrEmpty(m.get("user_name"))) {
                return;
            }
            String username = m.get("user_name").toString();
            UserDao dao = new UserDao(applicationContext);
            User user = dao.getUser(username, false);
            if (user == null) {
                user = new User();
            }
            user.setUsername(username);
            user.setUser_id(Integer.valueOf(m.get("user_id").toString()));
            user.setNick(m.get("user_nick").toString());
            user.setLogo(m.get("user_logo").toString());
            user.setIs_friend(false);
            dao.saveContact(user);
        }

        // EMConversation conversation =
        // EMChatManager.getInstance().getConversation(userName);
        EMMessage message = EMMessage.createSendMessage(EMMessage.Type.TXT);
        TextMessageBody txtBody = new TextMessageBody("");
        // ?body
        message.addBody(txtBody);
        message.setAttribute("vote", "vote");
        message.setAttribute("info", msg);
        message.setAttribute("bool", true);
        message.setAttribute("nick", PreferenceUtils.getInstance(applicationContext).getSettingUserNick());
        message.setAttribute("uid", PreferenceUtils.getInstance(applicationContext).getSettingUserID());
        message.setAttribute("logo", PreferenceUtils.getInstance(applicationContext).getSettingUserLogo());
        // ???,username?groupid
        message.setReceipt(userName);
        // messgageconversation
        // conversation.addMessage(message);
        EMChatManager.getInstance().sendMessage(message, new EMCallBack() {
            @Override
            public void onSuccess() {
                // TODO Auto-generated method stub

            }

            @Override
            public void onProgress(int arg0, String arg1) {
                // TODO Auto-generated method stub

            }

            @Override
            public void onError(int arg0, String arg1) {
                // TODO Auto-generated method stub

            }
        });
    }

    /**
     * ???
     * 
     * @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 (mLocationClient.isStarted()) {
    // mLocationClient.requestLocation();
    // } else {
    // mLocationClient.start();
    // }
    // }

    /**
     * ??
     * 
     * @Title: stopLocate
     * @return void
     * @date 2013-7-2 ?4:31:12
     */
    // public void stopLocate() {
    // if (mLocationClient.isStarted()) {
    // mLocationClient.stop();
    // }
    // }

    public String getUserID() {
        return PreferenceUtils.getInstance(getApplicationContext()).getSettingUserID();
    }

}