Android中统计分析的SDK ,友盟统计,百度统计,腾讯统计

来源:互联网 发布:杭州java培训哪里好 编辑:程序博客网 时间:2024/04/28 19:35

APP统计分析

用户画像

对程序员来说,用户画像就是用户的属性和行为;通俗地说,用户画像是包括了个人信息、兴趣爱好、日常行为等血肉丰满的客户实体。用户画像是精准营销的产物,企业通过收集用户的行为,然后分析出用户的特征与偏好,进而挖掘潜在的商业价值,实现企业效益的最大化。


用户画像的一个具体应用是电商app的“猜你喜欢”栏目,电商平台通过对用户购买过的商品进行统计,可以分析用户日常生活用的是什么物品;电商平台还可以对用户的搜索行为、浏览行为进行统计,从中分析用户感兴趣的商品,或者说考虑购买的商品。电商平台得到包括日常生活、兴趣爱好、购买意向在内的用户画像后,自然就能有针对性的向用户推荐合适的商品,从而扩大销量、增加营业额。

下图是用户画像的一个具体例子



统计分析的内容

app进行统计分析,主要有两方面的内容:
一、用户行为统计,包括
1、用户打开和关闭页面,以及在页面的停留时长;
2、用户点击行为的分布与频率;
3、用户输入的文字和图片,如搜索时的关键词、二维码的扫描信息、分享的图文内容等等;
4、用户对多媒体信息的接受程序,如听音乐的时长、看视频的时长等等;
二、运行情况分析,包括
1、app的启动时间;
2、app崩溃的日志信息;
3、app杀死进程;


友盟统计

集成步骤

1、在libs目录加入下面sdk包:
umeng-analytics-v6.0.1.jar
utdid4all-1.0.4.jar
2、在AndroidManifest.xml中补充权限定义,以及meta-data参数定义,包括UMENG_APPKEY、UMENG_CHANNEL等等,其中UMENG_APPKEY需要到友盟网站上注册申请;
3、代码里先设置采集参数,然后开始采集行为事件;


MobclickAgent

友盟统计分析主要用到MobclickAgent类。下面是MobclickAgent类与设置有关的方法说明:
setDebugMode : 设置是否开启调试模式。true为开启调试,false为关闭调试。
setSessionContinueMillis : 设置session的持续时间,单位毫秒。
startWithConfigure : 设置友盟的统计分析配置。该方法的参数是UMAnalyticsConfig对象,包含了appkey、渠道号、是否启用崩溃采集等等信息。
openActivityDurationTrack : 设置是否开启默认的Activity页面统计方式。true为开启,false为关闭。
setAutoLocation : 设置是否自动定位。
注意,友盟sdk的发送策略不在代码中设置,要在友盟的后台管理页面中设置。具体步骤为:点击应用名称->设置->发送策略,目前有两种:启动时发送(默认)、按间隔发送。
友盟sdk的老版本还提供了实时发送与仅在wifi下发送两种策略,但在新版本中取消了,原因如下:
1、实时发送会存在大量冗余字段的重复发送的现象,造成终端用户不必要的流量消耗;
2、仅在wifi下发送,数据的延迟会非常严重,造成数据统计结果的失真;


下面是MobclickAgent类与事件有关的方法说明:
onPageStart : 页面启动事件。
onPageEnd : 页面结束事件。
onResume : 恢复统计。
onPause : 暂停统计。
onEvent : 普通事件,一般是点击事件。
onEventValue : 复杂事件,比如说音乐播放事件。
onSocialEvent : 社会化分享事件。
onProfileSignIn : 登录事件。
onProfileSignOff : 注销事件。
onKillProcess : 杀死进程事件。


下面是友盟统计分析的代码例子:

import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;import android.app.Activity;import android.app.AlertDialog;import android.content.Context;import android.content.DialogInterface;import android.content.Intent;import android.os.Bundle;import android.view.KeyEvent;import android.view.View;import com.example.exmanalysis.umeng.analytics.FragmentStack;import com.example.exmanalysis.umeng.analytics.FragmentTabs;import com.example.exmanalysis.umeng.analytics.WebviewAnalytic;import com.umeng.analytics.MobclickAgent;import com.umeng.analytics.MobclickAgent.EScenarioType;import com.umeng.analytics.social.UMPlatformData;import com.umeng.analytics.social.UMPlatformData.GENDER;import com.umeng.analytics.social.UMPlatformData.UMedia;public class UmengActivity extends Activity {    private final static String TAG = "UmengActivity";    private Context mContext;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_umeng);        mContext = this;        MobclickAgent.setDebugMode(true);        // SDK在统计Fragment时,需要关闭Activity自带的页面统计,        // 然后在每个页面中重新集成页面统计的代码(包括调用了 onResume 和 onPause 的Activity)。        MobclickAgent.openActivityDurationTrack(false);        // MobclickAgent.setAutoLocation(true);        // MobclickAgent.setSessionContinueMillis(1000);        // MobclickAgent.startWithConfigure(        // new UMAnalyticsConfig(mContext, "4f83c5d852701564c0000011", "Umeng", EScenarioType.E_UM_NORMAL));        MobclickAgent.setScenarioType(mContext, EScenarioType.E_UM_NORMAL);    }    @Override    public void onResume() {        super.onResume();        MobclickAgent.onPageStart(TAG);        MobclickAgent.onResume(mContext);    }    @Override    public void onPause() {        super.onPause();        MobclickAgent.onPageEnd(TAG);        MobclickAgent.onPause(mContext);    }    public void onButtonClick(View view) {        int id = view.getId();        switch (id) {        case R.id.umeng_example_analytics_event_cc:            List<String> keyPath = new ArrayList<String>();            keyPath.add("one");            keyPath.add("two");            keyPath.add("tree");            MobclickAgent.onEvent(mContext, keyPath, 20, "label");            break;        case R.id.umeng_example_analytics_event:            MobclickAgent.onEvent(mContext, "click");            MobclickAgent.onEvent(mContext, "click", "button");            break;        case R.id.umeng_example_analytics_ekv:            Map<String, String> map_ekv = new HashMap<String, String>();            map_ekv.put("type", "popular");            map_ekv.put("artist", "JJLin");            MobclickAgent.onEvent(mContext, "music", map_ekv);            break;        case R.id.umeng_example_analytics_duration:            Map<String, String> map_value = new HashMap<String, String>();            map_value.put("type", "popular");            map_value.put("artist", "JJLin");            MobclickAgent.onEventValue(this, "music", map_value, 12000);            break;        case R.id.umeng_example_analytics_make_crash:            "123".substring(10);            break;        case R.id.umeng_example_analytics_js_analytic:            startActivity(new Intent(this, WebviewAnalytic.class));            break;        case R.id.umeng_example_analytics_fragment_stack:            startActivity(new Intent(this, FragmentStack.class));            break;        case R.id.umeng_example_analytics_fragment_tabs:            startActivity(new Intent(this, FragmentTabs.class));            break;        case R.id.umeng_example_analytics_social:            UMPlatformData platform = new UMPlatformData(UMedia.SINA_WEIBO, "user_id");            platform.setGender(GENDER.MALE); // optional            platform.setWeiboId("weiboId"); // optional            MobclickAgent.onSocialEvent(this, platform);            break;        case R.id.umeng_example_analytics_signin:            MobclickAgent.onProfileSignIn("example_id");            break;        case R.id.umeng_example_analytics_signoff:            MobclickAgent.onProfileSignOff();            break;        }    }    @Override    public boolean onKeyDown(int keyCode, KeyEvent event) {        if (keyCode == KeyEvent.KEYCODE_BACK) {            Hook();            return true;        }        return super.onKeyDown(keyCode, event);    }    // /对于好多应用,会在程序中杀死 进程,这样会导致我们统计不到此时Activity结束的信息,    // /对于这种情况需要调用 'MobclickAgent.onKillProcess( Context )'    // /方法,保存一些页面调用的数据。正常的应用是不需要调用此方法的。    private void Hook() {        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);        builder.setPositiveButton("退出应用", new DialogInterface.OnClickListener() {            public void onClick(DialogInterface dialog, int whichButton) {                MobclickAgent.onKillProcess(mContext);                int pid = android.os.Process.myPid();                android.os.Process.killProcess(pid);            }        });        builder.setNeutralButton("后退一下", new DialogInterface.OnClickListener() {            public void onClick(DialogInterface dialog, int whichButton) {                finish();            }        });        builder.setNegativeButton("点错了", new DialogInterface.OnClickListener() {            public void onClick(DialogInterface dialog, int whichButton) {            }        });        builder.show();    }}

百度统计

集成步骤

1、在libs目录加入下面sdk包:
libcrash_analysis.so
user_profile_mtj_1.5.jar
2、在AndroidManifest.xml中补充权限定义,以及meta-data参数定义,包括BaiduMobAd_STAT_ID、BaiduMobAd_CHANNEL等等,其中BaiduMobAd_STAT_ID需要到百度网站上注册申请;
3、代码里先设置采集参数,然后开始采集行为事件;


StatService

百度统计分析主要用到StatService类。下面是与设置有关的方法说明:
setDebugOn : 设置是否开启调试模式。true为开启调试,false为关闭调试。
setSessionTimeOut : 设置session的超时时间,单位秒。
setAppKey : 设置appkey。建议在AndroidManifest.xml中填写。
setAppChannel : 设置应用的渠道。
setOn : 打开崩溃错误收集。默认是关闭的
setLogSenderDelayed : 设置启动时日志发送的延时,单位秒。
setSendLogStrategy : 设置日志发送的策略。SendStrategyEnum.APP_START表示应用启动时发送,SendStrategyEnum.ONCE_A_DAY表示每天发送一次,SendStrategyEnum.SET_TIME_INTERVAL表示固定时间间隔发送。


下面是与事件有关的方法说明:
onPageStart : 页面启动事件。
onPageEnd : 页面结束事件。
onResume : 恢复统计。
onPause : 暂停统计。
onEvent : 普通事件,一般是点击事件
onEventDuration : 持续一段时间的事件。
onEventStart : 事件开始。
onEventEnd : 事件结束。


下面是百度统计分析的代码例子:


import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button;import android.widget.TextView;import com.baidu.mobstat.NativeCrashHandler;import com.baidu.mobstat.SendStrategyEnum;import com.baidu.mobstat.StatService;import com.example.exmanalysis.baidu.AnotherDemoActivity1;import com.example.exmanalysis.baidu.Conf;import com.example.exmanalysis.baidu.DemoActivity2;import com.example.exmanalysis.baidu.DemoActivity3;import com.example.exmanalysis.baidu.WebViewActivity;import com.example.exmanalysis.baidu.appfragment.AppFragmentDemoActivity;import com.example.exmanalysis.baidu.supportv4fragment.MainFragmentActivity;public class BaiduActivity extends Activity {    private Button btnPrev;    private Button btnNext;    private Button btnWebview;    private Button btnException;    private Button btnNativeException;    private Button btnSetTV;    private Button btnEvent;    private Button btnEventDuration;    private Button btnEventStart;    private Button btnEventEnd;    private Button btnFragmentPage;    private Button btnAppFragmentPage;    @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.baidu_activity);        boolean isWear = getPackageManager().hasSystemFeature("android.hardware.type.watch");        Log.e("TEST", "isWear: " + isWear);        Log.e("TEAT", "manufacturer: " + Build.MANUFACTURER);        // 设置AppKey        // StatService.setAppKey("a9e2ad84a2"); // appkey必须在mtj网站上注册生成,该设置建议在AndroidManifest.xml中填写,代码设置容易丢失        /*         * 设置渠道的推荐方法。该方法同setAppChannel(String), 如果第三个参数设置为true(防止渠道代码设置会丢失的情况),将会保存该渠道,每次设置都会更新保存的渠道,         * 如果之前的版本使用了该函数设置渠道,而后来的版本需要AndroidManifest.xml设置渠道,那么需要将第二个参数设置为空字符串,并且第三个参数设置为false即可。         * appChannel是应用的发布渠道,不需要在mtj网站上注册,直接填写就可以 该参数也可以设置在AndroidManifest.xml中         */        // StatService.setAppChannel(this, "RepleceWithYourChannel", true);        // 测试时,可以使用1秒钟session过期,这样不断的间隔1S启动退出会产生大量日志。        StatService.setSessionTimeOut(30);        // setOn也可以在AndroidManifest.xml文件中填写,BaiduMobAd_EXCEPTION_LOG,打开崩溃错误收集,默认是关闭的        StatService.setOn(this, StatService.EXCEPTION_LOG);        /*         * 设置启动时日志发送延时的秒数<br/> 单位为秒,大小为0s到30s之间<br/> 注:请在StatService.setSendLogStrategy之前调用,否则设置不起作用         *          * 如果设置的是发送策略是启动时发送,那么这个参数就会在发送前检查您设置的这个参数,表示延迟多少S发送。<br/> 这个参数的设置暂时只支持代码加入,         * 在您的首个启动的Activity中的onCreate函数中使用就可以。<br/>         */        StatService.setLogSenderDelayed(0);        /*         * 用于设置日志发送策略<br /> 嵌入位置:Activity的onCreate()函数中 <br />         *          * 调用方式:StatService.setSendLogStrategy(this,SendStrategyEnum. SET_TIME_INTERVAL, 1, false); 第二个参数可选:         * SendStrategyEnum.APP_START SendStrategyEnum.ONCE_A_DAY SendStrategyEnum.SET_TIME_INTERVAL 第三个参数:         * 这个参数在第二个参数选择SendStrategyEnum.SET_TIME_INTERVAL时生效、 取值。为1-24之间的整数,即1<=rtime_interval<=24,以小时为单位 第四个参数:         * 表示是否仅支持wifi下日志发送,若为true,表示仅在wifi环境下发送日志;若为false,表示可以在任何联网环境下发送日志         */        StatService.setSendLogStrategy(this, SendStrategyEnum.SET_TIME_INTERVAL, 1, false);        // 调试百度统计SDK的Log开关,可以在Eclipse中看到sdk打印的日志,发布时去除调用,或者设置为false        StatService.setDebugOn(true);        String sdkVersion = StatService.getSdkVersion();        TextView sdkVersionTxtv = (TextView) findViewById(R.id.tv_sdk_version);        if (sdkVersion != null) {            sdkVersionTxtv.setText("sdk version is: " + sdkVersion);        }        btnPrev = (Button) findViewById(R.id.layout1_btn1);        btnNext = (Button) findViewById(R.id.layout1_btn2);        btnWebview = (Button) findViewById(R.id.layout1_btn_web_view);        btnException = (Button) findViewById(R.id.layout1_btn_excep);        btnNativeException = (Button) findViewById(R.id.layout1_btn_native_excep);        btnNativeException.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                NativeCrashHandler.doNativeCrash();            }        });        btnSetTV = (Button) findViewById(R.id.layout1_btn_set_TV);        btnSetTV.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                StatService.setForTv(BaiduActivity.this, true);            }        });        btnEvent = (Button) findViewById(R.id.layout1_btn_event);        btnEventDuration = (Button) findViewById(R.id.layout1_btn_event_duration);        btnEventStart = (Button) findViewById(R.id.layout1_btn_event_start);        btnEventEnd = (Button) findViewById(R.id.layout1_btn_event_end);        btnFragmentPage = (Button) findViewById(R.id.layout1_fragment);        btnAppFragmentPage = (Button) findViewById(R.id.layout1_app_fragment);        findViewById(R.id.btn_another_process).setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                Intent intent = new Intent(BaiduActivity.this, AnotherDemoActivity1.class);                startActivity(intent);            }        });        btnPrev.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                Intent intent = new Intent();                intent.setClass(BaiduActivity.this, DemoActivity3.class);                BaiduActivity.this.startActivity(intent);            }        });        btnNext.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                Intent intent = new Intent();                intent.setClass(BaiduActivity.this, DemoActivity2.class);                BaiduActivity.this.startActivity(intent);            }        });        btnWebview.setOnClickListener(new OnClickListener() {            @Override            public void onClick(View v) {                Intent intent = new Intent();                intent.setClass(BaiduActivity.this, WebViewActivity.class);                BaiduActivity.this.startActivity(intent);            }        });        btnException.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                Thread t = new Thread() {                    @Override                    public void run() {                        if (!MyApplication.SHIELD_EXCEPTION) {                            Log.w(Conf.TAG, 10 / 0 + "");                        }                    }                };                t.start();            }        });        btnEvent.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                StatService.onEvent(BaiduActivity.this.getApplicationContext(), "registered id", "pass", 1);            }        });        /**         * 自定义事件的第一种方法,写入某个事件的持续时长         */        btnEventDuration.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                // 事件id("registered id")的事件pass,其时长持续100毫秒                StatService.onEventDuration(BaiduActivity.this, "registered id", "pass", 100);            }        });        /*         * 自定义事件的第二种方法,自己定义该事件的起始时间和结束时间         */        btnEventStart.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                // 事件id("registered id")的事件pass,其时长持续10毫秒                StatService.onEventStart(BaiduActivity.this, "registered id", "pass"); // 必须和onEventEnd共用才行            }        });        /*         * 自定义事件的第二种方法,自己定义该事件的起始时间和结束时间         */        btnEventEnd.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                // 事件id("registered id")的事件pass,其时长持续10毫秒                StatService.onEventEnd(BaiduActivity.this, "registered id", "pass"); // 必须和onEventStart共用才行            }        });        btnFragmentPage.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                Intent in = new Intent();                in.setClass(BaiduActivity.this, MainFragmentActivity.class);                startActivity(in);            }        });        btnAppFragmentPage.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {                    Intent in = new Intent();                    in.setClass(BaiduActivity.this, AppFragmentDemoActivity.class);                    startActivity(in);                }            }        });    }    public void onResume() {        super.onResume();        //页面起始(每个Activity中都需要添加,如果有继承的父Activity中已经添加了该调用,那么子Activity中务必不能添加)        //不能与StatService.onPageStart一级onPageEnd函数交叉使用        StatService.onResume(this);    }    public void onPause() {        super.onPause();        //页面结束(每个Activity中都需要添加,如果有继承的父Activity中已经添加了该调用,那么子Activity中务必不能添加)        //不能与StatService.onPageStart一级onPageEnd函数交叉使用        StatService.onPause(this);    }}

腾讯统计

集成步骤

1、在libs目录加入下面sdk包:
libMtaNativeCrash.so
mid-sdk-2.3.jar
mta-android-stat-sdk-2.2.0_20160504.jar
2、在AndroidManifest.xml中补充权限定义,以及meta-data参数定义,包括TA_APPKEY、InstallChannel等等,其中TA_APPKEY需要到腾讯网站上注册申请;
3、代码里先设置采集参数,然后开始采集行为事件;


StatConfig

腾讯统计分析的参数设置用的是StatConfig类,主要方法说明如下:
setDebugEnable : 设置是否开启调试模式。true为开启调试,false为关闭调试。
setSessionTimoutMillis : 设置session的超时时间,单位秒。
setAppKey : 设置appkey。建议在AndroidManifest.xml中填写。
setInstallChannel : 设置安装的渠道。
setAutoExceptionCaught : 设置是否自动采集崩溃信息(即app未处理的异常)。true表示自动采集,false表示不采集。
setStatSendStrategy : 设置日志发送的策略。StatReportStrategy.PERIOD表示按时间间隔发送,StatReportStrategy.INSTANT实时发送即每个行为都立即发送,StatReportStrategy.ONLY_WIFI表示只在wifi网络下发送,StatReportStrategy.BATCH表示批量发送即达到缓存临界值时触发,StatReportStrategy.APP_LAUNCH表示应用启动时发送。
setEnableSmartReporting : 设置是否允许在WIFI网络下实时上报。
setSendPeriodMinutes : 设置日志发送的时间间隔。单位分钟,该方法在StatReportStrategy.PERIOD时启用。
setMaxStoreEventCount : 设置缓存中的事件最大数目。该方法在StatReportStrategy.BATCH时启用。


StatService

腾讯统计分析的事件跟踪用的是StatService类,主要方法说明如下:
startStatService : 开始统计服务。如果集成统计服务的是普通app,则无需调用该方法;如果提供出来的是第三方sdk,由于jar包不包含AndroidManifest.xml,因此必须在代码中调用该方法,才能启用统计服务。
onResume : 恢复统计。
onPause : 暂停统计。
addActionListener : 监听前后台状态。该方法的参数为StatActionListener对象,对象内部需实现两个方法,分别是前台运行onBecameForeground、后台运行onBecameBackground。
trackCustomEvent : 跟踪自定义事件。
trackCustomBeginEvent : 跟踪自定义事件开始。
trackCustomEndEvent : 跟踪自定义事件结束。
trackCustomKVEvent : 跟踪自定义的key-value事件。
trackCustomBeginKVEvent : 跟踪自定义的key-value事件开始。
trackCustomEndKVEvent : 跟踪自定义的key-value事件结束。
reportError : 上报错误信息。
reportException : 上报异常信息。


import java.util.HashMap;import java.util.Map;import java.util.Properties;import android.app.Activity;import android.app.ActivityManager;import android.content.Context;import android.os.Bundle;import android.os.Environment;import android.os.MemoryFile;import android.util.Log;import android.view.View;import android.widget.Button;import com.tencent.stat.StatAppMonitor;import com.tencent.stat.StatConfig;import com.tencent.stat.StatNativeCrashReport;import com.tencent.stat.StatService;import com.tencent.stat.StatServiceImpl;public class TencentActivity extends Activity {    private final static String TAG = "TencentActivity";private Context ctx = null;private Button btn_customevent_args_count = null;private Button btn_customevent_kv_count = null;private Button btn_customevent_args_duration_begin = null;private Button btn_customevent_args_duration_end = null;private Button btn_customevent_kv_duration_begin = null;private Button btn_customevent_kv_duration_end = null;private Button btn_report_error = null;private Button btn_report_exception = null;private Button btn_catch_unhandled_exception = null;private Button btn_init_nativeCrash = null;private Button btn_catch_native_crash = null;private Button btn_monitor_events = null;public void onActivityOpen() { // 你的函数Properties prop = new Properties();prop.setProperty("aty", "抢票活动"); // 活动页面prop.setProperty("gid", "潜在付费用户"); // 用户组名称prop.setProperty("attr", "1"); // 用户属性(年龄、性别等)prop.setProperty("act_type", "1"); // 行为类型(最近30天启动过、最近30天使用时长超过、最近30天是否有过升级行为等)prop.setProperty("act_val", "10"); // 行为取值StatService.trackCustomKVEvent(this, "mta_tag_activity_open", prop);}public void onActivityClick2() { // 你的函数Properties prop = new Properties();prop.setProperty("aty", "抢票活动"); // 活动页面prop.setProperty("btn", "报名"); // 按钮prop.setProperty("gid", "潜在付费用户"); // 用户组名称prop.setProperty("attr ", "1"); // 用户属性(年龄、性别等)prop.setProperty("act_type ", "1"); // 行为类型(最近30天启动过、最近30天使用时长超过、最近30天是否有过升级行为等)prop.setProperty("act_val ", "10"); // 行为取值StatService.trackCustomKVEvent(this, "mta_tag_activity_click", prop);}public void onUserPay() { // 你的函数Properties prop = new Properties();prop.setProperty("scene", "通关"); // 付费场景prop.setProperty("amount", "350"); // 付费金额prop.setProperty("way", "手机支付"); // 付费方式(可选择上报)StatService.trackCustomKVEvent(null, "mta_tag_user_pay", prop);}MemoryFile memoryFile = null;private View.OnClickListener l = new View.OnClickListener() {@Overridepublic void onClick(View v) {Log.d(TAG, "ctx==" + ctx);int id = v.getId();switch (id) {case R.id.btn_customevent_args_count:StatService.trackCustomEvent(ctx, "trackCustomEvent", "args");StatService.trackCustomEvent(ctx, "id1", "args");StatService.trackCustomEvent(ctx, "id2", "");StatService.trackCustomEvent(ctx, "trackCustomEvent", null);StatServiceImpl.trackBackground(getApplicationContext(), 10, null);break;case R.id.btn_customevent_kv_count:Properties prop = new Properties();prop.setProperty("key", "value");prop.setProperty("key2", "value2");StatService.trackCustomKVEvent(ctx, "trackCustomKVEvent", prop);prop = new Properties();prop.setProperty("a", "b");StatService.trackCustomKVEvent(ctx, "4", prop);StatService.trackCustomKVEvent(ctx, "trackCustomKVEvent", prop);prop = new Properties();prop.setProperty("num", "3434");StatService.trackCustomKVEvent(ctx, "trackCustomKVEvent", prop);break;case R.id.btn_customevent_args_duration_begin:StatService.trackCustomBeginEvent(ctx, "trackCustomEvent", "loadConfigFile");break;case R.id.btn_customevent_args_duration_end:StatService.trackCustomEndEvent(ctx, "trackCustomEvent", "loadConfigFile");break;case R.id.btn_customevent_kv_duration_begin:Properties properties = new Properties();properties.setProperty("load", "config");StatService.trackCustomBeginKVEvent(ctx, "trackCustomEvent", properties);break;case R.id.btn_customevent_kv_duration_end:properties = new Properties();properties.setProperty("load", "config");StatService.trackCustomEndKVEvent(ctx, "trackCustomEvent", properties);break;case R.id.btn_report_error:StatService.reportError(ctx, "I hate error.");StatService.commitEvents(getApplicationContext(), -1);break;case R.id.btn_report_exception:try {String myNull = null;int length = myNull.length();} catch (NullPointerException ex) {StatService.reportException(ctx, ex);}break;case R.id.btn_monitor_events:// 新建监控接口对象StatAppMonitor monitor = new StatAppMonitor("ping:www.qq.com");// 接口开始执行String ip = "www.qq.com";Runtime run = Runtime.getRuntime();java.lang.Process proc = null;try {String str = "ping -c 3 -i 0.2 -W 1 " + ip;long starttime = System.currentTimeMillis();proc = run.exec(str);int retCode = proc.waitFor();long difftime = System.currentTimeMillis() - starttime;// 设置接口耗时monitor.setMillisecondsConsume(difftime);// 设置接口返回码monitor.setReturnCode(retCode);// 设置请求包大小,若有的话monitor.setReqSize(1000);// 设置响应包大小,若有的话monitor.setRespSize(2000);// 设置抽样率,默认为1,表示100%。如果是50%,则填2(100/50),如果是25%,则填4(100/25),以此类推。// monitor.setSampling(2);if (retCode == 0) {Log.d(TAG, "ping连接成功");// 标记为成功monitor.setResultType(StatAppMonitor.SUCCESS_RESULT_TYPE);} else {Log.d(TAG, "ping测试失败");// 标记为逻辑失败,可能由网络未连接等原因引起的,但对于业务来说不是致命的,是可容忍的monitor.setResultType(StatAppMonitor.LOGIC_FAILURE_RESULT_TYPE);}} catch (Exception e) {Log.d(TAG, e.getMessage());// 接口调用出现异常,致命的,标识为失败monitor.setResultType(StatAppMonitor.FAILURE_RESULT_TYPE);} finally {proc.destroy();}// 上报接口监控的信息StatService.reportAppMonitorStat(ctx, monitor);Map<String, Integer> map = new HashMap<String, Integer>();map.put("www.qq.com", 80);map.put("pingma.qq.com", 80);StatService.testSpeed(ctx, map);break;case R.id.btn_catch_unhandled_exception:int i = 1 / 0;break;case R.id.btn_init_nativeCrash:String tombfilepath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/my";StatConfig.initNativeCrashReport(ctx, null);break;case R.id.btn_catch_native_crash:StatNativeCrashReport.doNativeCrashTest();break;default:break;}}};String getCurProcessName(Context context) {int pid = android.os.Process.myPid();ActivityManager mActivityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);for (ActivityManager.RunningAppProcessInfo appProcess : mActivityManager.getRunningAppProcesses()) {if (appProcess.pid == pid) {return appProcess.processName;}}return null;}@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_tencent);ctx = this;// 高级功能:在线配置更新// String onOrOff = StatConfig.getCustomProperty("switch", "off");// Log.d(TAG, "switch" + onOrOff);// if(onOrOff.equalsIgnoreCase("on")){// // 打开某项功能// }else{// // 禁用某项功能// }// String appid = "互联的appid";// String appkey = "Aqc" + appid;// StatConfig.setAutoExceptionCaught(false); // 禁止捕获app未处理的异常// StatConfig.setEnableSmartReporting(true); // 禁止WIFI网络实时上报// StatConfig.setSendPeriodMinutes(24 * 60); // PERIOD间隔周期,24小时// StatConfig.setStatSendStrategy(StatReportStrategy.PERIOD); //// PERIOD上报策略// try {// StatService.startStatService(this, appkey,// com.tencent.stat.common.StatConstants.VERSION);// } catch (MtaSDkException e) {// Log.e("DEBUG", "MTA init Failed.");// }initActivity();}private void initActivity() {setTitle("常用统计分析");btn_customevent_args_count = (Button) findViewById(R.id.btn_customevent_args_count);btn_customevent_kv_count = (Button) findViewById(R.id.btn_customevent_kv_count);btn_customevent_args_duration_begin = (Button) findViewById(R.id.btn_customevent_args_duration_begin);btn_customevent_args_duration_end = (Button) findViewById(R.id.btn_customevent_args_duration_end);btn_customevent_kv_duration_begin = (Button) findViewById(R.id.btn_customevent_kv_duration_begin);btn_customevent_kv_duration_end = (Button) findViewById(R.id.btn_customevent_kv_duration_end);btn_report_error = (Button) findViewById(R.id.btn_report_error);btn_report_exception = (Button) findViewById(R.id.btn_report_exception);btn_catch_unhandled_exception = (Button) findViewById(R.id.btn_catch_unhandled_exception);btn_catch_native_crash = (Button) findViewById(R.id.btn_catch_native_crash);btn_init_nativeCrash = (Button) findViewById(R.id.btn_init_nativeCrash);btn_monitor_events = (Button) findViewById(R.id.btn_monitor_events);btn_customevent_args_count.setOnClickListener(l);btn_customevent_kv_count.setOnClickListener(l);btn_customevent_args_duration_begin.setOnClickListener(l);btn_customevent_args_duration_end.setOnClickListener(l);btn_customevent_kv_duration_begin.setOnClickListener(l);btn_customevent_kv_duration_end.setOnClickListener(l);btn_report_error.setOnClickListener(l);btn_report_exception.setOnClickListener(l);btn_catch_unhandled_exception.setOnClickListener(l);btn_init_nativeCrash.setOnClickListener(l);btn_catch_native_crash.setOnClickListener(l);btn_monitor_events.setOnClickListener(l);}@Overrideprotected void onResume() {super.onResume();StatService.onResume(this);}@Overrideprotected void onPause() {super.onPause();StatService.onPause(this);}}



0 0
原创粉丝点击