Categories
Android

吐槽一下新浪微博 Android SDK V2.4.0

吐槽一下新浪微博 Android SDK V2.4.0

周末逛逛github,发现新浪更新了SDK,说是重大版本变更,瞄了一下,大概是文档更规范、代码重构之类的。老版本SDK代码全开放,但 2.3之后,封闭了部分代码。不管如何,我还是直奔观看 AsyncWeiboRunner.request 这个方法究竟改变了没有,结果还是失望了。

我建议微博 Android SDK 的开发人员,好好的阅读AQuery,Volley,android-async-http 这几个异步网络请求库,通过回调方式处理请求结果。新浪也是有回调结果,但要自己加 Handler 更新UI,官方的Demo在回调直接更新UI,其实就是在 http 请求线程里操作的,很容易给新手误导。

很多软件的开发都是如此,开始使用现成的,后面发现使用越来越不爽,不能满足自己的需求,决定重新搞。所以,Weibo for Android 计划使用 Volley作为http 处理库,自己写封装接口。我封装了一个GsonRequest,测试发现老是返回403,抓包才知道参数没有上传。使用 http get 传参数需要注意,重写getParams无效。见:

http://stackoverflow.com/questions/18484647/volley-does-not-call-getparams-for-my-custom-request

getParams() is not called on the GET method, so it seems you’ll have to add it to the URL before you send the request

Categories
Android

写脚本群发薪水清单邮件通知

一到发薪水日,我们的人事忙得不可开交,给每位员工发送上月的薪水清单邮件,一个个从Excel表格复制粘贴到邮件,忙到晚上10点才结束,整得人精疲力尽。HR让我帮她解决这个难题,她说她用foxmail,网上搜索,应该有一些工具可以完成。但我对foxmail,outlook又不是很熟悉,想想还是使用自己擅长的脚本写。脚本这东西,长时间不练习,就生疏了,整整花了早上2小时,刚好200行代码:)为了学习python,这次硬着头皮用python写,在 windows xp, windows 8 , mac OS X 10.8.4 测试通过。

send_salary_mail.py:

# -*- coding: utf-8 -*-
#!/usr/bin/env python2.7

'''
 Copyright 2013 IBOXPAY Inc
 Description: this script help HR send mail to all staffs.
 Dependency: xlrd, Install:
 wget --no-check-certificate https://pypi.python.org/packages/source/x/xlrd/xlrd-0.9.2.tar.gz
 tar xvf xlrd-0.9.2.tar.gz
 cd xlrd-0.9.2
 sudo python setup.py install

 Written by Lytsing Huang 2013-09-12
 refer: http://code.activestate.com/recipes/578150-sending-non-ascii-emails-from-python-3/
'''

import sys
import smtplib
from email.header import Header
from email.mime.text import MIMEText
from email.utils import formataddr
from datetime import datetime
import xlrd

reload(sys)
sys.setdefaultencoding('utf-8')

mail_host = 'mail.xxx.com' #发送邮件的smtp地址
mail_user = 'xxx@xxx.com' # 发送通知邮件的用户名
mail_pass = 'xxx' # 用户的密码

sender_name = 'xxx'
sender_addr = 'xxx@xxx.com'
subject = '2013年8月XXX公司薪水发放通知单' # ***邮件标题*** 每月需要手动修改年月
title = subject

html_template = """
<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
</head>
<body>
<h2 align="center">%s</h2>
<table border="1", cellpadding="2" cellspacing="0">
    <thead>
        <tr>
            <th>姓名</th>
            <th>基本工资</th>
            <th>岗位津贴</th>
            <th>交通补贴</th>
            <th>补助天数</th>
            <th>补助</th>
            <th>绩效工资</th>
            <th>其他</th>
            <th>应发合计</th>
            <th>公司承担社保
            <th>公司承担住房公积金</th>
            <th>代扣社保</th>
            <th>代扣住房公积金</th>
            <th>病假天数</th>
            <th>病假</th>
            <th>事假天数</th>
            <th>事假</th>
            <th>个税</th>
            <th>其他扣款</th>
            <th>实发工资<th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
            <td> %s </td>
        </tr>
    </tbody>
</table>

<pre>
 说明:
 1、以上薪水将会转入您提供给公司的银行账户中,如银行账户有更改请及时通知人力资源部。
 2、员工薪水信息属公司机密,请妥善保管,泄漏者将按公司有关制度处理。
 3、如对薪水支付数额有异议的,请于一周内以邮件的形式向人力资源部提出。

 人力资源部
 %s

  ----------------------------------------------

              %s    人事
</pre>
</body>
</html>
"""

def write_mail_content(header_title, name, base_salary, post_allowance,
        transport_subsidies, grants_days, allowance, pay_for_performance,
                    other, total, company_pension_commitment, company_housing_fund_commitment,
                    withholding_social_security, withholding_housing_fund, sick_days,
                    sick_leave, leave_days, leave, personal_income_tax, other_withholding,
                    real_wages, today, sender):

    content = html_template % (header_title, name, base_salary, post_allowance,
            transport_subsidies, grants_days, allowance, pay_for_performance,
            other, total, company_pension_commitment, company_housing_fund_commitment,
            withholding_social_security, withholding_housing_fund, sick_days,
            sick_leave, leave_days, leave, personal_income_tax, other_withholding,
            real_wages, today, sender)

    return content

def send_mail(msg, sender, recipient):
    try:
        s = smtplib.SMTP()
        s.connect(mail_host)
        s.ehlo()
        s.starttls()
        s.login(mail_user,mail_pass)
        s.sendmail(sender, recipient, msg.as_string())
        s.close()
        return True
    except Exception, e: print str(e)
    return False

def write_mail(sender, recipient, sub, content):
    name = Header(sender, 'utf-8').encode()
    msg = MIMEText(content, _subtype = 'html', _charset='utf-8')
    msg['Subject'] = Header(sub, 'utf-8')
    msg['From'] = formataddr((name, sender_addr))
    msg['To'] = recipient
    return msg

def main():

    if  len(sys.argv) < 2:
        print '错误,没有指定参数'
        print '用法:python send_salary_mail.py xxx.xls'
        sys.exit()

    bk = xlrd.open_workbook(sys.argv[1])
    #bk.sheets()返回一个列表
    sh = bk.sheets()[0]  #读取第一张sheet
    #下面是按行读取excel表格内容
    for row in range(3, sh.nrows):
        name = sh.row(row)[2].value # 姓名
        recipient_addr = sh.row(row)[3].value # Email
        base_salary = sh.row(row)[7].value # 基本工资
        post_allowance = sh.row(row)[8].value # 岗位津贴
        transport_subsidies = sh.row(row)[9].value # 交通补贴
        grants_days = sh.row(row)[10].value # 补助天数
        allowance = sh.row(row)[11].value # 补助
        pay_for_performance = sh.row(row)[12].value # 绩效工资
        other = sh.row(row)[13].value # 其他
        total = sh.row(row)[14].value # 应发合计
        company_pension_commitment = sh.row(row)[15].value # 公司承担社保
        company_housing_fund_commitment = sh.row(row)[16].value # 公司承担住房公积金
        withholding_social_security = sh.row(row)[17].value # 代扣社保
        withholding_housing_fund = sh.row(row)[18].value # 代扣住房公积金
        sick_days = sh.row(row)[19].value # 病假天数
        sick_leave = sh.row(row)[20].value # 病假
        leave_days = sh.row(row)[21].value # 事假天数
        leave = sh.row(row)[22].value # 事假
        personal_income_tax = sh.row(row)[24].value # 个税
        other_withholding = sh.row(row)[25].value # 其他扣款
        real_wages = sh.row(row)[26].value # 实发工资
        today = datetime.now().strftime('%Y/%m/%d')

        content = write_mail_content(title, name, base_salary, post_allowance,
                transport_subsidies, grants_days, allowance, pay_for_performance,
                other, total, company_pension_commitment, company_housing_fund_commitment,
                withholding_social_security, withholding_housing_fund, sick_days,
                sick_leave, leave_days, leave, personal_income_tax, other_withholding,
                real_wages, today, sender_name)

        msg = write_mail(sender_name, recipient_addr, subject, content)
        if send_mail(msg, sender_addr, recipient_addr):
            print ' 姓名:' + name + ' 发送成功.'
        else:
            print ' 姓名:' + name + ' 发送失败.'

    print 'Send all finished! please check out the failed records.'

if __name__ == '__main__':
    main()

工资表测试样例:点这下载

有需要的朋友可以参考下。

Categories
Android Server

Android、iOS http请求加上User-agent

最近在排查一些问题,发现很难下手,nginx 的log如下:

182.37.109.153 - - [25/Aug/2013:00:02:52 +0800] "-" 400 0 "-" "-" "-"
182.37.109.153 - - [25/Aug/2013:00:02:52 +0800] "-" 400 0 "-" "-" "-"
182.37.109.153 - - [25/Aug/2013:00:02:52 +0800] "-" 400 0 "-" "-" "-"
171.36.8.66 - - [25/Aug/2013:09:40:07 +0800] "POST /xxxxx.htm HTTP/1.1" 200 251 "-" "-" "-"

不知道哪个请求是Android,哪个是iOS的。Square的Jack在演讲中提到过,他们最开始做后台系统,基于twitter有过的经验,第一个系统不是实现后台交易功能,而是控制台,先做好监控用户的每个交易行为,使得可控。

iOS 如果使用 ASIHTTPRequest 库,ASIHTTPRequest.m 里的代码如下:

[self setDefaultUserAgentString:[NSString stringWithFormat:@”%@ %@ (%@; %@ %@; %@)”, appName, appVersion, deviceName, OSName, OSVersion, locale]];
得到默认的 User-agent: “miniCashbox 2.0.6 (iPhone; iPhone OS 6.1.3; zh_CN)”

Android可以使用系统提供的,需要设置
HttpProtocolParams.setUserAgent(params, System.getProperty(“http.agent”));
结果为:User-agent: “Dalvik/1.6.0 (Linux; U; Android 4.1.2; Nexus S Build/JZO54K)”

根据实际需要,以上的 User-agent 还不足够满足需要,比如想要知道是哪个用户发送的请求,但不可能把用户id显示出来,那么就需要显示设备的唯一标识 Device Id。系统设计时,用户与终端设备信息的关系是: user has_many devices。从常用的QQ、微信在移动终端登录体验过程中,我们可以感受到的。给客户端做消息push推送,更需要如此做。

参考: http://cdrussell.blogspot.com/2012/09/programmatically-get-user-agent-string.html

Categories
Android

新浪微博Android客户端实战 – 使用ActionBarSherlock与MenuDrawer

很久没有为 Android for WordPress 项目贡献代码了,最近他们把代码放在 github 上,pull requests 方便了许多。之前我都是在trac上给他们提交patch, 新建一个ticket 贴上 svn diff 的结果,苦不堪言,最后只好放弃。在google play 上更新了客户端,界面比以前有很大的进步,可圈可点。因此,我决定参考wordpress, 使用上 ActionBarSherlock 与 MenuDrawer, 替换 android-action 组件。为什么一开始使用 android-action?因为 actionbar 的颜色我喜欢,而且组件使用简单。学习 ActionBarSherlock 是有些成本的,编译 sample 示例,边看效果边看代码。

主要修改点:

1. 将 android.app.Activity 替换为 SherlockActivity

// file: BaseActivity.java
import com.actionbarsherlock.app.SherlockActivity;

public class BaseActivity extends SherlockActivity {
// activity implementation
}

2. getMenuInflater 修改为 getSupportMenuInflater,注意,要把android 自带导入的Menu包删掉,导入ActionBarSherlock的包,不然会提示无法 Override onCreateOptionsMenu。

3. 把项目中 libs/android-support-v4.jar 干掉,这个会与abs的冲突。eclipse 报错:

Found 2 versions of android-support-v4.jar in the dependency list, but not all the versions are identical (check is based on SHA-1 only at this time).
All versions of the libraries must be the same at this time.
Jar mismatch! Fix your dependencies

4. abs 进度条尺寸很大,需要改小一点的,参考: Android: Changing the Default Indeterminate Progress Size in ActionBarSherlock

ActionBarSherlock 修改记录: https://github.com/lytsing/weibo/commit/3d6f203a390460b4cdd1c8f8543c523ad55f0ccb

使用 MenuDrawer

MenuDrawer 跟 abs 可以很好的结合使用,照着 android-menudrawer-abs-sample 写。修改记录:https://github.com/lytsing/weibo/commit/15e61dc2fbb556b68db21d2fe8a4d0e2aadc4938 图标,背景颜色,后期再需要调整。

Categories
Android

Google I/O 2013 – Volley: Easy, Fast Networking for Android

我把这视频高清版本从youtube下载优放在优酷上,地址: http://v.youku.com/v_show/id_XNTU4ODgzNjg4.html ppt下载: Volley

以前反编译过android market,发现里面有用到volley,起这么个名字不知道啥用的,现在才知道主讲者Ficus Kirkpatrick 就是负责开发Google play 的。

看完视频,发现 Jeff Sharkey 就利用它写了简单的Flickr 客户端 , 这速度快得没的说。在前面写的新浪微博客户,Timeline 图片异步下载,使用的是AQuery.image, 但效果还是差一点,于是也考虑试试 volley,代码提交记录见 https://github.com/lytsing/weibo/commit/7c84aea7ae27e6fa7da7aa4e477e41e07c1d79ac 。图片加载性能改善很多,谁用谁知道 🙂

有人问:

Network loaded images in a list view? Solved by several different Android libraries, 3 years ago 😉

https://github.com/koush/UrlImageViewHelper/
https://github.com/nostra13/Android-Universal-Image-Loader
https://code.google.com/p/android-query/wiki/ImageLoading

Ficus 回答说:

Volley does a lot more than that, and does better at the images problem than any of them.

volley 没有提供jar包,需要自己手动编译,使用方法:

git clone https://android.googlesource.com/platform/frameworks/volley
cd volley
android update project -p .
ant jar

拷贝 bin/volley 到 libs 文件夹下面。注意,这个库要求最低SDK版本为Froyo,即至少要设置android:minSdkVersion为8以上。

Pages: 1 2 3 4 5 6 7 8 9 10 11 12 Next