1.Spring xml配置 添加的 命名空间的键值对
2.hibernate映射文件点击对应实体生成相应的xml映射文件
3.Alt+shift +z 对代码块快速 try catch或do while
4.快速模板配置 如: struts2的核心配置.....
5. 几个重要的开源软件, httpunit ,httpclient(对于QQ这种提交一个页面跳转好几个页面的怎么登陆)
6. 比如 Apache Jakarta 上很著名的另外两个开源项目 Cactus 和 HTMLUnit 都使用了 HttpClient,
7.个人常用文件上传软件,如手机和电脑的互传.
8.
// File file = new File("E:/itext/b.pdf");
// file.getParentFile().mkdirs();
9. html 转换为PDF
10.jsoup 也有一个高级作用可以直接过滤所有的html标签,只留下txt文本
Elements elements2 = docum.select("#article_content");
String content = elements2.text();
Elements elements2 = docum.select("#article_content");
String content = elements2.outerHtml(); //包含 #article_content在内的div
String content = elements2.html(); //#article_content里面的内容
10.
// 从classpath的根目录中查找a.txt文件
this.getClass().getClassLoader().getResourceAsStream("a.txt");
// 从classpath的根目录中查找a.txt文件
this.getClass().getResourceAsStream("/a.txt");
// 从当前类所在的包中查找a.txt文件
this.getClass().getResourceAsStream("a.txt");
11.动态加载Android布局
View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.tab1,null);
由于这个view 没有父布局,故 参数2为 null;
12. 多线程下载库,httpunit,压缩解压工具
13.图片轮播的小点
ImageView imageView;
ImageView imageviews = new ImageView[advPic.size]; //advPic(ImageView) 是轮播中的图片共4张
for(int i=0;i<4;i++){
imageView = new ImageView(this);
imageView.setLayoutParams(new LayoutParams(20,20)); //设置imageView的宽和高
imageView.setPadding(5,5,5,5); // 设置上下左右的间距
imageviews[i] = imageView;
if(i==0){
imageviews[i].setBackgourndResource(R.drawable.banner_focus);
}
else{
imageviews[i].setBackgourndResource(R.drawable.banner_blur);
}
}
14. 切换轮播是通过 Thread.sleep(3000); 休眠时间设置的
15.this.adapter.notifyDataSetChanged(); //更新listView的
List mcList ;
private MyCollectAdapter adapter;
protected void onCreate(Bundle saveInstanceState){
super.onCreate(saveInstanceState);
setContentView(R.layout.activity_main);
ListViewCollect mListview = (ListViewCollect)findViewById(R.id.list_del);
mcList = new ArrayList();
adapter = new MyColloectAdapter(this.mcList);
mListview.setAdapter(adapter);
setList();
}
public void setList(){
for(int i=0;i<10;i++){
CollectListModel m = new CollectListModel();
mcList.add(m);
}
adapter.notifyDataSetChanged(); //更新listView
}
16.类似QQ谈话面板用的是 ListView Adapter使用的是BaseAdapter
public View getView(int paramInt, View paramView, ViewGroup paramViewGroup)
{
LayoutInflater localLayoutInflater = LayoutInflater.from(this.context);
if (((TextObject)this.lists.get(paramInt)).getFlag() == 0) // public static final int reciveFlag = 0;
this.layout = ((RelativeLayout)localLayoutInflater.inflate(R.layout.left, null));
if (((TextObject)this.lists.get(paramInt)).getFlag() == 1) //Const.java中 public static final int sendFlag = 1;
this.layout = ((RelativeLayout)localLayoutInflater.inflate(R.layout.right, null));
TextView localTextView1 = (TextView)this.layout.findViewById(2131296261);
TextView localTextView2 = (TextView)this.layout.findViewById(2131296259);
localTextView1.setText(((TextObject)this.lists.get(paramInt)).getText().replace("
", "\n"));
localTextView2.setText(((TextObject)this.lists.get(paramInt)).getTime());
return this.layout;
}
布局
接受者 left.xml
"1.0" encoding="utf-8"?>
"fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
"center_horizontal" android:id="@id/time" android:layout_width="fill_parent" android:layout_height="fill_parent" />
"@id/iv" android:padding="10.0dip" android:layout_width="70.0dip" android:layout_height="70.0dip" android:src="@drawable/robot" android:layout_below="@id/time" />
"@id/tv" android:background="@drawable/receive" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginRight="50.0dip" android:layout_toRightOf="@id/iv" android:layout_below="@id/time" />
发送者 right.xml
"1.0" encoding="utf-8"?>
"fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
"center_horizontal" android:id="@id/time" android:layout_width="fill_parent" android:layout_height="fill_parent" />
"@id/iv" android:padding="10.0dip" android:layout_width="70.0dip" android:layout_height="70.0dip" android:src="@drawable/user" android:layout_below="@id/time" android:layout_alignParentRight="true" />
"@id/tv" android:background="@drawable/send" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_marginLeft="50.0dip" android:layout_toLeftOf="@id/iv" android:layout_below="@id/time" />
17.Android 里面比较常用的 获取文件类
一般手机SD卡只有一个 ,现在多数有两个SD卡/mnt/sdcard /mnt/sdcard2
File sdCardDir = Environment.getExternalStorageDirectory();// /mnt/sdcard
Environment.getDataDirectory()
Environment.getRootDirectory()
Environment.getDownloadCacheDirectory()
18. 获取手机ROM容量和 手机SD卡的容量
File sdCardDir = new File("/mnt/sdcard2");// /mnt/sdcard
StatFs statFs = new StatFs(sdCardDir.getPath());
long blockCount = statFs.getBlockCount();
long blockSize = statFs.getBlockSize();
long availableBlocks = statFs.getAvailableBlocks();
总容量 String totalSize = Formatter.formatFileSize(getApplicationContext(), blockCount*blockSize);
可用容量String availableSize = Formatter.formatFileSize(getApplicationContext(), blockSize*availableBlocks);
//------------
File path = Environment.getDataDirectory();
StatFs statFs = new StatFs(path.getPath());
long blockCount = statFs.getBlockCount();
long blockSize = statFs.getBlockSize();
long availableBlocks = statFs.getAvailableBlocks();
String totalSize = Formatter.formatFileSize(getApplicationContext(), blockCount*blockSize);
String availableSize = Formatter.formatFileSize(getApplicationContext(), blockSize*availableBlocks);
return "手机Rom总容量:"+totalSize+"\n手机Rom可用容量:"+availableSize;
19.在使用 android:layout_weight="1.0" 尤其是LinearLayout android:orientation="horizontal"水平方向时候
其里面的 控件 可以设置 android:layout_width="0.0dip" 为 0 ,由 android:layout_weight="1.0"控制
"@+id/send"
android:background="@drawable/edittext_active"
android:layout_width="0.0dip"
android:layout_height="wrap_content"
android:layout_weight="1.0"
/>
20. 布局 android:layout_weight="1.0" 设置时候,发现,如果只有一方设置,另一方没有设置的情况下
在另一方占 一定位置,剩下的全部 留给被设置的 一方
21.
图灵机器人
package com.example.robot.Utils;
import android.os.AsyncTask;
import com.example.robot.Interface.HttpGetUrlDataListener;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
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;
public class HttpGetRequest extends AsyncTask
{
private String content;
private HttpEntity entity;
private HttpClient httpCilent;
private HttpGet httpGet;
private HttpGetUrlDataListener httpGetUrlDataListener;
private HttpResponse httpResponse;
private String url = "http://www.tuling123.com/openapi/api?key=c3dbedaa570141b3b0ef68c4e7fdf8ce&info=";
public HttpGetRequest(String paramString, HttpGetUrlDataListener paramHttpGetUrlDataListener)
{
this.content = paramString;
this.httpGetUrlDataListener = paramHttpGetUrlDataListener;
}
protected String doInBackground(String[] paramArrayOfString)
{
String str = null;
try
{
this.httpCilent = new DefaultHttpClient();
this.httpGet = new HttpGet(this.url + this.content);
this.httpResponse = this.httpCilent.execute(this.httpGet);
this.entity = this.httpResponse.getEntity();
BufferedReader localBufferedReader = new BufferedReader(new InputStreamReader(this.entity.getContent()));
StringBuffer localStringBuffer = new StringBuffer();
str = localBufferedReader.readLine();
if (str == null)
return localStringBuffer.toString();
label145: localStringBuffer.append(str);
}
catch (ClientProtocolException localClientProtocolException)
{
localClientProtocolException.printStackTrace();
return str;
}
catch (IOException localIOException)
{
localIOException.printStackTrace();
break label145:
}
}
protected void onPostExecute(String paramString)
{
this.httpGetUrlDataListener.getUrlData(paramString);
super.onPostExecute(paramString);
}
}
22.
"@+id/vPager"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
//里面是四个 欢迎的圆点
android:id="@+id/ll"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="5.0dp" //通过margin 使圆点向上移动了
android:orientation="horizontal" >
23.
解释 android:layout_gravity 和 android:gravity区别
LinearLayout有"两个"
24.
例子1:
requestWindowFeature(Window.FEATRUE_NO_TITLE); //等价于满屏(没有图标和标题)
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
例子2:
requestWindowFeature(Window.FEATURE_LEFT_ICON); //等价于满屏(没有图标和标题)
setContentView(R.layout.main);
getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,R.drawable.ic_launcher); //设置 左边图标的 图片
例子3:
requestWindowFeature(Window.FEATURE_RIGHT_ICON);
setContentView(R.layout.main);
getWindow().setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON,R.drawable.ic_launcher); //设置 right 图标的 图片
25.
Android好看的按钮制作,可以使用图片(默认,单击,聚焦,样式都不同),方法: 在res/drawable/下面 放置一个xml文件
名字随意
但是需要使用selector 标签
"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android">
- "true"
android:drawable="@drawable/dark_dot" />
- "@drawable/white_dot" />
"1.0" encoding="utf-8"?>
"http://schemas.android.com/apk/res/android">
- "true" //点击状态
android:drawable="@drawable/pressed" />
- "true" //获得焦点状态
android:drawable="@drawable/focused" />
- "@drawable/focused" /> //默认状态
26.button.layout(l, t, r, b); 可以直接给某个空间布局位置
27. Pending 直到,即将发生的,待定的
PendingIntent
28.
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case 10086:
Uri result = data.getData();
String contactId = result.getLastPathSegment(); //得到uri中的最后一个占位符 如 localhost/dedecms/java/1
通过startActivityForResult获取 联系人的方法
public void getList(View view){
//获取联系人列表
Intent intent = new Intent();
intent.setAction(Intent.ACTION_PICK);
intent.setData(ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(intent, 10086); //10086 是请求码
}
29.
ArrayList和 数组的互转
ArrayList list = new ArrayList();
String[] strs = new String[list.size];
list.toArray(strs);
String []strs = {"a","b","c"};
List list = Arrays.asList(strs);
30.BitmapFactory 工具类可以直接把R.drawable里面图片转换为bitmap
也可以把assets里面图片转为bitmap类型
31.
SMS发短信实例:
public void send(View view){
String message = editText.getText().toString();
//scAddress 服务中心的地址 null(默认为SMSC 3) destinationPort消息的目标端口号
//sentIntent 短息发送成功或失败 后才 调用此Activity ,ResultCode是 Activity.RESULT_OK表示成功,(RESULT_ERROR_GENERIC_FAILURE,RESULT_ERROR_RADIO_OFF,RESULT_ERROR_NULL_PDU)之一表示错误
//deliveryIntent 短息接收成功 后才调用此Activity
Intent send = new Intent();
send.setClass(MainActivity.this, ShowActivity.class);
PendingIntent sentIntent = PendingIntent.getActivity(MainActivity.this, 1, send, PendingIntent.FLAG_UPDATE_CURRENT);
Intent receiver = new Intent();
receiver.setClass(MainActivity.this, ShowActivity2.class);
PendingIntent deliveryIntent = PendingIntent.getActivity(getApplicationContext(), 2, receiver, PendingIntent.FLAG_UPDATE_CURRENT);
smsManager.sendTextMessage("10086", null, message, sentIntent, deliveryIntent);
}
注意权限需要:
"android.permission.SEND_SMS"/>
"android.permission.READ_PHONE_STATE"/>
32.
无需权限,感觉Android5.0 改了很多,关闭应用,这个全局定时器也无效了;
public class MainActivity extends Activity {
//全局定时器
AlarmManager alarmManager = null;
PendingIntent pendingIntent = null;
// PendingIntent 可以脱离应用程序而存在,系统级别的
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setClass(this, Result.class);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
public void start(View view ){
//开启全局定时器
alarmManager.setRepeating(AlarmManager.RTC, 0, 5000, pendingIntent);
}
public void end(View view ){
alarmManager.cancel(pendingIntent);
}
33.PackageManager manager = getPackageManager();
这个类很好,可以获取 手机已经安装的应用的图标等等信息
String packageName = "com.gs.file";
List pinfo = packageManager.getInstalledPackages(0);
for(int i=0;iget(i);
String label = packageManager.getApplicationLabel(p.applicationInfo).toString(); //应用程序的名字
if(packageName.equals(label)){
Intent intent = new Intent();
intent = packageManager.getLaunchIntentForPackage(packageName);
startActivity(intent);
}
}
获取某个应用的Intent
Intent intent = manager.getLaunchIntentForPackage(pName);
34.JavaScript解析Json
服务器端的 return "redirect:result";(重定向) 或 return "list";(请求转发) HttpClient都会自动处理
public static void main(String[] args) throws Exception, IOException {
HttpClient client = new DefaultHttpClient();
//方式1============ > start
// HttpGet get = new HttpGet("http://localhost:8080/Upload/list");
// HttpResponse response = client.execute(get);
//方式1============ > end 此种方式会自动处理 重定向信息
HttpPost post = new HttpPost("http://localhost:8080/Upload/list");
HttpResponse response = client.execute(post);
int responseCode = response.getStatusLine().getStatusCode();
System.out.println("responseCode:"+responseCode);
System.out.println(EntityUtils.toString(response.getEntity()));
if(responseCode==301||responseCode==302){
System.out.println("重定向了");
Header headers[] = response.getHeaders("Location");
String location = headers[0].getValue();
System.out.println(location);
}
}
61. 使用HttpClient完成更高级的功能
有时候提交到大网站,发现参数特别多
方法:
1.先Get获取 到cookie
2.然后再次提交 设置cookie为 Response获取到的,并且修改部分字段setHeader();
62.
@Test
// 设置已获取的cookie,查看需要登录后才能查看的页面
public void testGetinfoByLoginCookie() throws Exception, IOException {
DefaultHttpClient httpclient = new DefaultHttpClient();
CookieStore cookieStore = new BasicCookieStore();
BasicClientCookie cookie1 = new BasicClientCookie("ThinkID","5s4tmqem08gh091v3egoa7sqf7");
cookie1.setDomain(".lashou.com");
BasicClientCookie cookie2 = new BasicClientCookie("city_b","2419");
cookie2.setDomain("lashou.com");
BasicClientCookie cookie3 = new BasicClientCookie("client_key","1425104707wd157b4b24ff70adcb875a");
cookie3.setDomain("lashou.com");
BasicClientCookie cookie4 = new BasicClientCookie("login_name2","testuser007");
cookie4.setDomain("lashou.com");
BasicClientCookie cookie5 = new BasicClientCookie("pwd2","4c88a4062736c26572d3ec382868fa2b");
cookie5.setDomain("lashou.com");
cookieStore.addCookie(cookie1);
cookieStore.addCookie(cookie2);
cookieStore.addCookie(cookie3);
cookieStore.addCookie(cookie4);
cookieStore.addCookie(cookie5);
List cookies = new ArrayList();
httpclient.setCookieStore(cookieStore);
List cookieList = httpclient.getCookieStore().getCookies();
for(int i=0;iout.println("cookie"+i+":"+cookieList.get(i));
}
// 设置已登录的cookie
String memberpage = "http://www.lashou.com/account/orders/";
HttpGet httpget = new HttpGet(memberpage);
HttpResponse response = httpclient.execute(httpget); // 必须是同一个HttpClient!
HttpEntity entity = response.getEntity();
entity = response.getEntity();
String html = EntityUtils.toString(entity, "GBK");
httpget.releaseConnection();
System.out.println(html);
}
63.
简单使用
package com.gs.test;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import com.gargoylesoftware.htmlunit.BrowserVersion;
import com.gargoylesoftware.htmlunit.HttpMethod;
import com.gargoylesoftware.htmlunit.WebClient;
import com.gargoylesoftware.htmlunit.WebRequest;
import com.gargoylesoftware.htmlunit.html.HtmlPage;
import com.gargoylesoftware.htmlunit.util.Cookie;
import com.gargoylesoftware.htmlunit.util.NameValuePair;
public class Test {
public static void main(String[] args) throws Exception, IOException {
WebClient wc = new WebClient(BrowserVersion.INTERNET_EXPLORER_11);
wc.getOptions().setUseInsecureSSL(true);
wc.getOptions().setCssEnabled(false);
wc.getOptions().setJavaScriptEnabled(true);
// 3 启动客户端重定向
wc.getOptions().setRedirectEnabled(true);
wc.getOptions().setThrowExceptionOnScriptError(false);
wc.getOptions().setTimeout(10000);
wc.getOptions().setDoNotTrackEnabled(false); //设置不跟踪
//----------------------------
//设置Cookies : 可以用于认证数据
wc.getCookieManager().setCookiesEnabled(true);
Cookie cookie = new Cookie("baidu.com","key","value");
wc.getCookieManager().addCookie(cookie);
//----------------------------
WebRequest request = new WebRequest(new URL("http://www.baidu.com"));
// request.setHttpMethod(HttpMethod.GET);
request.setHttpMethod(HttpMethod.POST);
List list = new ArrayList();
list.add(new NameValuePair("username", "wangli"));
request.setRequestParameters(list);
HtmlPage htmlPage = wc.getPage(request);
System.out.println(htmlPage.asXml());
//----------------------------
//获取cookie
Set ResponseCookies = wc.getCookieManager().getCookies();
for(Cookie c:ResponseCookies){
System.out.println("获取的Cookie是------>"+c.getName()+":"+c.getValue());
}
//----------------------------
/*
*
WebResponse response = htmlPage.getWebResponse();
response.cleanUp(); // 关闭响应流
*/
}
}
64.
bottom_bar.xml
"http://schemas.android.com/apk/res/android"
android:id="@+id/bottom"
android:layout_width="fill_parent"
android:layout_height="55dp"
android:layout_alignParentBottom="true"
android:background="@drawable/bottom_bar"
>
"fill_parent"
android:layout_height="wrap_content"
android:textColor="#fff"
android:text="使用include layout 可以使其显示在 主布局的底部"/>
MainActivity:
"http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
"@+id/id_content"
android:layout_width="match_parent"
android:layout_height="0dp"
android:layout_weight="1" >
"@layout/bottom_bar"/>
65. 布局
"fill_parent"
android:layout_height="55dp">
"@+id/tab_weixin"
android:layout_width="0dp"
android:layout_height="fill_parent"
android:layout_weight="1"
android:descendantFocusability="beforeDescendants" //=====================
android:gravity="center"
android:orientation="vertical">
"@+id/weixin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#0000"
android:clickable="false"
android:src="@drawable/tab_weixin_pressed"/>
"wrap_content"
android:layout_height="wrap_content"
android:text="微信"/>
beforeDescendants:viewgroup会优先其子类控件而获取到焦点
afterDescendants:viewgroup只有当其子类控件不需要获取焦点时才获取焦点
blocksDescendants:viewgroup会覆盖子类控件而直接获得焦点
66.
WebView 的使用
// 监听 所有点击的链接,如果拦截到我们需要的,就跳转到相对应的页面。
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
System.out.println("----------------------shouldOverrideUrlLoading 。。 url:" + url);
if (url != null && url.contains("/m/phoneRegiste.do")) {
Intent intent = new Intent(PublicWebView.this, RegisterByPhone.class);
PublicWebView.this.startActivity(intent);
finish();
return true;
}
return super.shouldOverrideUrlLoading(view, url);
}
67.
mWebView.setWebChromeClient(new WebChromeClient(){
public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
//偷懒直接接收JS中传过来的msg
if(message.length() > 15){
mLoginBackJson = message;
Log.i(TAG, "mLoginBackJson = " + mLoginBackJson);
if(parseJson(mLoginBackJson)){//解析传回的json文件,成功的话,进行一次业务的访问
new MyTask().execute(ConfigUrl.ALL_CONTENT_VIEW);
}
//return true;
}
//保存一下cookie,后面httpclient使用
CookieManager cookieManager = CookieManager.getInstance();
CookieStr = cookieManager.getCookie(COOKIE_URL);
return super.onJsAlert(view, url, message, result);
}
});
}
68.
WebView 处理ajax请求
You can use the JavascriptInterface to intercept the AJAX calls along with JQuery methods ajaxStart and ajaxComplete in following way:
// our JavascriptInterface
public class AjaxHandler {
private static final String TAG = "AjaxHandler";
private final Context context;
public AjaxHandler(Context context) {
this.context = context;
}
public void ajaxBegin() {
Log.w(TAG, "AJAX Begin");
Toast.makeText(context, "AJAX Begin", Toast.LENGTH_SHORT).show();
}
public void ajaxDone() {
Log.w(TAG, "AJAX Done");
Toast.makeText(context, "AJAX Done", Toast.LENGTH_SHORT).show();
}
}
And here is how the AjaxHandler is used in Activity:
public class MainActivity extends Activity {
private static final String TAG = "MainActivity";
private WebView webView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// get web view
webView = (WebView) findViewById(R.id.web);
// configure web view
final WebSettings webSettings = webView.getSettings();
webSettings.setBuiltInZoomControls(true);
webSettings.setJavaScriptEnabled(true);
webView.loadUrl("http://foo.com");
// add javascript interface
webView.addJavascriptInterface(new AjaxHandler(this), "ajaxHandler");
// override onPageFinished method of WebViewClient to handle AJAX calls
webView.setWebViewClient(new WebViewClient() {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
view.loadUrl("javascript:$(document).ajaxStart(function (event, request, settings) { " +
"ajaxHandler.ajaxBegin(); " + // Event called when an AJAX call begins
"});");
view.loadUrl("javascript:$(document).ajaxComplete(function (event, request, settings) { " +
"ajaxHandler.ajaxDone(); " + // Event called when an AJAX call ends
"});");
});
}
}
69.
把 httpClient的Cookie共享给 WebView
DefaultHttpClient httpclient=....;
String toUrl="https://cap.cityu.edu.hk/studentlan/details.aspx.....";
List cookies = httpclient.getCookieStore().getCookies();
if (! cookies.isEmpty()){
CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
//sync all the cookies in the httpclient with the webview by generating cookie string
for (Cookie cookie : cookies){
String cookieString = cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain();
cookieManager.setCookie(toUrl, cookieString);
CookieSyncManager.getInstance().sync();
}
}
把WebView的Cookie共享给HttpClient
70.
首先android5.0 实现了WebView与 框架的自动cookie同步,无需额外操作
Set-Cookie Header
Set-Cookie响应头的格式如下所示:
Set-Cookie: =[; =]...
[; expires=][; domain=]
[; path=][; secure][; httponly]
// cookieManager.setCookie(url,cookie);
cookieManager.setCookie(cookie.getDomain(), cookie.getName() + "=" + cookie.getValue() + "; domain=" + cookie.getDomain() + "; path=" + cookie.getPath());
CookieSyncManager.getInstance().sync();
71.
键盘事件
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
//按钮按下逻辑
break;
case MotionEvent.ACTION_UP:
//按钮弹起逻辑
break;
}
Fragment 里面没有此方法
// 如果希望浏览的网页后退而不是退出浏览器,需要WebView覆盖URL加载,让它自动生成历史访问记录,那样就可以通过前进或后退访问已访问过的站点。
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// TODO Auto-generated method stub
if(keyCode==KeyEvent.KEYCODE_BACK)
{
if(webView.canGoBack())
{
webView.goBack();//返回上一页面
return true;
}
else
{
System.exit(0);//退出程序
}
}
return super.onKeyDown(keyCode, event);
}
72.
百度登陆url
https://passport.baidu.com/v2/?login&fr=old
登陆成功url
https://passport.baidu.com/center?_t=1442818676
73.
混合模式
更高级的做法是
先通过流获取到整个网页,然后 loadUrl(); 通过java的replace("","");替换 需要登陆的字符串
74.
Session捕获 技巧(通用版 )
Session什么时候失效?
1. 服务器会把长时间没有活动的Session从服务器内存中清除,此时Session便失效。Tomcat中Session的默认失效时间为20分钟。
2. 调用Session的invalidate方法。
public class Tab1 extends Fragment{
private WebView webView;
private String loginOKurl = "https://passport.baidu.com/center?_t=1442818676";
private String cookieJsession;
//JavaScript对象
class WebObject {
Context mcontext ;
public WebObject(Context context){
this.mcontext = context; //这个Context 不是必须的,仅仅是我们Toast等控件需要用这个对象
}
@JavascriptInterface
public void showSession(){
//在android API Level 17及以上的版本中,就会出现js调用不了android的代码,这是版本兼容的问题
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.setAcceptCookie(true);
cookieJsession = cookieManager.getCookie(loginOKurl); //登录成功url
Toast.makeText(getActivity(),"cookie是:"+cookieJsession, Toast.LENGTH_LONG).show();
}
@JavascriptInterface
public void skip(){
Intent intent = new Intent();
intent.setClass(mcontext, SessionShareActivity.class);
mcontext.startActivity(intent);
}
}
class MyWebViewClient extends WebViewClient{
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// view.loadUrl(url);
WebObject webObject = new WebObject(getActivity());
webObject.showSession(); //获取到Session后
Intent intent = new Intent();
intent.putExtra("Jsession", cookieJsession);
intent.setClass(getActivity(), SessionShareActivity.class);
startActivity(intent);
return true;
}
//当load有ssl层的https页面时,如https://money.183.com.cn/,如果这个网站的安全证书在Android无法得到认证,WebView就会变成一个空白页
//处理ssl请求(https,需要证书的请求)
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler,
SslError error) {
//handler.cancel(); 默认的处理方式,WebView变成空白页
handler.proceed(); //接受证书
//handleMessage(Message msg); 其他处理
}
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.tab1, container,false);
webView = (WebView) view.findViewById(R.id.webView);
webView.setWebViewClient(new MyWebViewClient());
webView.getSettings().setJavaScriptEnabled(true); //注意一定要设置这个哦,否则不会执行js
//设置WebView的缩放功能点
webView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
webView.setHorizontalScrollBarEnabled(false); //没有水平滚动条
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true); //缩放控制条
webView.setInitialScale(70);
webView.setHorizontalScrollbarOverlay(true);
//
// String data = "欢迎登陆南工
实验系统 ";
// webView.loadDataWithBaseURL(null, data, "text/html", "utf-8", null);// webView.loadData(data, "text/html", "UTF-8"); //这种方式是Android的bug
return view;
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
webView.addJavascriptInterface(new WebObject(getActivity()), "ss");
// webView.loadUrl("file:///android_asset/www/index.html");
webView.loadUrl("https://passport.baidu.com/v2/?login&fr=old");
super.onActivityCreated(savedInstanceState);
}
}
75.
ScrollView中只能放一个控件,一般都放LinearLayout,orientation属性值为vertica
76.
经常需要用ListView或者其它显示大量Items的控件实时跟踪或者查看信息,并且希望最新的条目可以自动滚动到可视范围内。通过设置控件transcriptMode属性可以将Android平台的控件(支持ScrollBar)自动滑动到最底部。
源代码:
ListView 默认是会滚动的,故 无需设置
"@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:stackFromBottom="true"
android:transcriptMode="alwaysScroll" />
77.
一般来说在工作线程中执行耗时任务,当任务完成时,会返回UI线程,一般是更新UI。这时有两种方法可以达到目的。
一种是handler.sendMessage。发一个消息,再根据消息,执行相关任务代码。
另一种是handler.post(r)。r是要执行的任务代码。意思就是说r的代码实际是在UI线程执行的。可以写更新UI的代码。(工作线程是不能更新UI的)
78.
布局高级技术
1.
View layout = getLayoutInflater().inflate(R.layout.menu_layout,null);
int width = getWindowManager().getDefaultDisplay().getWidth();
int height = getWindowManager().getDefaultDisplay().getHeight();
PopupWindow popwindow = new PopupWindow(layout,width,height);
popwindow.showAtLocation(layout,Gravity.BOTTOM,0,0); //显示
popwindow.dismiss();//关闭选项菜单
79.
ormlite没有hibernate智能,更新表字段 不会更新数据库字段,数据库的更新只会根据版本号改变才会重新调用那个方法
80.
根据class 属性得到节点
HtmlElement resultData = page.getBody();
List columns = resultData.getElementsByAttribute("tr", "class", "content");
//保存网页
//rootPage.save(new File("src"));
webClient.setAjaxController(new NicelyResynchronizingAjaxController());;//很重要,设置支持AJAX
模拟按钮 执行JavaScript 设置可以使用jQuery
StringBuilder js = new StringBuilder();
js.append("$('#u').value='").append(WeiboAccount.USERNAME).append("';");
js.append("$('#p').value='").append(WeiboAccount.PASSWORD).append("';");
js.append("document.write('Success')");
HtmlPage htmlPage = (HtmlPage) page;
ScriptResult scriptResult = htmlPage.executeJavaScript(js.toString());
HtmlPage downLoadPage = (HtmlPage) scriptResult.getNewPage();
//点击Excel图标,开始下载
ScriptResult downLoadResult = downLoadPage.executeJavaScript("javascript:exportData('/ddp’,'BULKEXCEL');");
//下载Excel文件
InputStream is = downLoadResult.getNewPage().getWebResponse().getContentAsStream();
OutputStream fos = new FileOutputStream("d://test.xls");
byte[] buffer=new byte[1024*30];
int len=-1;
while((len=is.read(buffer))>0){
fos.write(buffer, 0, len);
}
fos.close();
fos.close();
System.out.println("Success!");
81.
Httpunit 执行表单点击
WebClient webClient = new WebClient();
HtmlPage page = webClient.getPage(url);
HtmlForm form = page.getForms().get(2);
HtmlSubmitInput button = form.getInputByValue(">");
HtmlPage page2 = button.click();
String originalHtml = page2.refresh().getWebResponse().getContentAsString();
Httpunit 执行Ajax请求
82.alternative adj. 替代的; 另类的; 备选的; 其他的; n. 可供选择的事物;
//this would cause all ajax calls to be synchronous.
webClient.setAjaxController(new NicelyResynchronizingAjaxController());;//很重要,设置支持AJAX
// Alternatively, did you try in your solution to call to "webClient.waitForBackgroundJavaScript(10000)" after tou got the page?
//Something like this:
HtmlPage page2 = button.click();
webClient.waitForBackgroundJavaScript(10000)
String originalHtml = page2.asXml();
return originalHtml;
例子1:
ScriptResult scriptResult = page.executeJavaScript("$('#cur a[txt=2]').click();");
HtmlPage htmlPage = (HtmlPage) scriptResult.getNewPage();
System.out.println(htmlPage.asText());
例子2:
版本1:
public class YoutubeBot {
private static final String YOUTUBE = "http://www.youtube.com";
public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
WebClient webClient = new WebClient();
webClient.setThrowExceptionOnScriptError(false);
// This is equivalent to typing youtube.com to the adress bar of browser
HtmlPage currentPage = webClient.getPage("http://www.youtube.com/results?search_type=videos&search_query=official+music+video&search_sort=video_date_uploaded&suggested_categories=10%2C24&uni=3");
// Get form where submit button is located
HtmlForm searchForm = (HtmlForm) currentPage.getElementById("masthead-search");
// Get the input field.
HtmlTextInput searchInput = (HtmlTextInput) currentPage.getElementById("masthead-search-term");
// Insert the search term.
searchInput.setText("java");
// Workaround: create a 'fake' button and add it to the form.
HtmlButton submitButton = (HtmlButton) currentPage.createElement("button");
submitButton.setAttribute("type", "submit");
searchForm.appendChild(submitButton);
//Workaround: use the reference to the button to submit the form.
HtmlPage newPage = submitButton.click();
//Find all links on page with given class
final List listLinks = (List) currentPage.getByXPath("//a[@class='ux-thumb-wrap result-item-thumb']");
//Print all links to console
for (int i=0; iout.println(YOUTUBE + listLinks.get(i).getAttribute("href"));
}
}
HtmlAnchor 控件用于控制 元素。在 HTML 中, 元素用于创建超链接。超链接可链接到书签或其他网页
版本2:
public class YoutubeBot {
private static final String YOUTUBE = "http://www.youtube.com";
@SuppressWarnings("unchecked")
public static void main(String[] args) throws FailingHttpStatusCodeException, MalformedURLException, IOException {
WebClient webClient = new WebClient();
webClient.setThrowExceptionOnScriptError(false);
// This is equivalent to typing youtube.com to the adress bar of browser
HtmlPage currentPage = webClient.getPage(YOUTUBE);
// Get form where submit button is located
HtmlForm searchForm = (HtmlForm) currentPage.getElementById("masthead-search");
// Get the input field
HtmlTextInput searchInput = (HtmlTextInput) currentPage.getElementById("masthead-search-term");
// Insert the search term
searchInput.setText("java");
// Workaround: create a 'fake' button and add it to the form
HtmlButton submitButton = (HtmlButton) currentPage.createElement("button");
submitButton.setAttribute("type", "submit");
searchForm.appendChild(submitButton);
// Workaround: use the reference to the button to submit the form.
currentPage = submitButton.click();
// Get the div containing the filters
HtmlElement filterDiv = currentPage.getElementById("search-lego-refinements");
// Select the first link from the filter block (Upload date)
HtmlAnchor sortByDateLink = ((List) filterDiv.getByXPath("//ul/li/a")).get(0);
// Click the 'Upload date' link
currentPage = sortByDateLink.click();
System.out.println(currentPage.asText());
}
}
//使用代理
// WebClient webClient=new WebClient(BrowserVersion.FIREFOX_10,"http://myproxyserver",8000);
WebClient webClient2=new WebClient(BrowserVersion.INTERNET_EXPLORER_10);
注意:
// 模拟浏览器打开一个目标网址
final HtmlPage page = webClient.getPage(url);
// 该方法在getPage()方法之后调用才能生效
webClient.waitForBackgroundJavaScript(1000*3);
webClient.setJavaScriptTimeout(0);
"logging" type="button" tabindex="5" value="登 录" accesskey="l">
HtmlButtonInput btn = loginForm.getInputByValue("登 录");//注意 登录中间有括号的情况 (注意这里写成HtmlSubmitInput就会报转换异常了)
HtmlPasswordInput password = loginForm.getInputByName("password");//不能写成 HtmlTextInput
这里类型 都是根据 "submit" type="text" type="password"
一些技巧:
(1) 等待js执行完毕
*
//try 20 times to wait .5 second each for filling the page.
for (int i = 0; i < 20; i++) {
if (condition_to_happen_after_js_execution) {
break;
}
synchronized (page) {
page.wait(500);
}
}
*/
(2)
ScriptResult scriptResult = page.executeJavaScript("$('#cur a[txt=2]').click();");
HtmlPage htmlPage = (HtmlPage) scriptResult.getNewPage();
System.out.println(htmlPage.asText());
(3) 通过class元素得到 DOM对象
/*
*
List columns = resultData.getElementsByAttribute("tr", "class", "content");
// List ahref = resultData.getElementsByAttribute("a", "txt", "2");
List ahref = resultData.getElementsByAttribute("a", "class", "j_th_tit");
// HtmlPage page2 = ahref.get(0).click();
for(HtmlElement element:ahref){
System.out.println(element.asText());
}
*/
(4).
HtmlPage currentPage = webClient.getPage("http://www.google.com/");
HtmlImage imgElement = (HtmlImage)currentPage.getHtmlElementById("logo");
System.out.println(imgElement.getAttribute("src"));
(5).
HttpUnit登录功能
HtmlInput username = page.getHtmlElementById("username"); //注意是 page.getHtmlElementById() 不是 page.getElementById();哦
HtmlInput password = page.getHtmlElementById("password");
HtmlInput btn = page.getFirstByXPath(".//*[@id='vForm']/div[3]/ul/li[6]/div[2]/input");
username.setAttribute("value", "wangli");
password.setAttribute("value", "1234");
HtmlPage result = btn.click();
(6).
例子:采集Demo
public class Demo {
public static void main(String[] args) {
LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log","org.apache.commons.logging.impl.NoOpLog");
java.util.logging.Logger.getLogger("net.sourceforge.htmlunit").setLevel(java.util.logging.Level.OFF);
try {
WebClient webClient = new WebClient(BrowserVersion.CHROME);
webClient.getOptions().setThrowExceptionOnScriptError(false);//当JS执行出错的时候是否抛出异常
webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
webClient.getOptions().setTimeout(30000);//设置“浏览器”的请求超时时间
webClient.getOptions().setJavaScriptEnabled(true);
webClient.getOptions().setCssEnabled(false);
webClient.getCookieManager().setCookiesEnabled(true);
webClient.waitForBackgroundJavaScript(30000);//设置JS后台等待执行时间
// this would cause all ajax calls to be synchronous.
webClient.setAjaxController(new NicelyResynchronizingAjaxController());;//很重要,设置支持AJAX
//去哪网
// String url = "http://flight.qunar.com/site/oneway_list.htm?searchDepartureAirport=%E4%B8%8A%E6%B5%B7&searchArrivalAirport=%E9%87%8D%E5%BA%86&searchDepartureTime=2015-09-26&searchArrivalTime=2015-09-28&nextNDays=0&startSearch=true&ex_track=ap_20100201";
String url = "http://xinjinqiao.tprtc.com/admin/main/flrpro.do#";
// String url = "http://tieba.baidu.com/f?ie=utf-8&kw=java&fr=search";
HtmlPage page = webClient.getPage(url);
List hrefs = page.getByXPath("//span[@id=\"cur\"]/a");
// HtmlAnchor pre = (HtmlAnchor) hrefs.get(0); //上一页
// HtmlAnchor next = (HtmlAnchor) hrefs.get(1); //下一页
int currentPage = 1;
print(page,currentPage);
} catch (Exception e) {
// TODO: handle exception
}
}
public static void print(HtmlPage page,int flag){
try {
System.out.println("----------->第"+flag+"页");
System.out.println(page.asText());
HtmlAnchor href = page.getAnchorByText("下一页");
page = href.click(); // 不断更改引用
if(flag == 2 ){
return ;
}
flag ++; //这个 和if判断一定要在自己调用自己之前执行哦
print(page,flag); //调用自己
} catch (Exception e) {
e.printStackTrace();
}
}
}
HTMLUnit 和 HttpUnit 别弄混了
经典语句:
HtmlAnchor submit = page.getFirstByXPath("//form[@id='user-login']/a[1]");
HtmlInput login_name = (HtmlInput) page.getByXPath("//*[@id='loginName']").get(0);
HtmlInput login_pass = (HtmlInput) page.getByXPath("//*[@id='loginPass']").get(0);
HtmlInput loginInput = page.getHtmlElementById("loginName");
HtmlInput passwordInput = page.getHtmlElementById("loginPass");
例子:================================
HtmlForm loginForm = htmlPage.getForms().get(0);
HtmlTextInput username = loginForm.getInputByName("username");
HtmlPasswordInput password = loginForm.getInputByName("password");
HtmlSubmitInput btn = loginForm.getInputByValue("登 录");//注意 登录中间有括号的情况
// username.setValueAttribute("Working_Harder");
// password.setValueAttribute("burning1223");
username.setValueAttribute("wangli");
password.setValueAttribute("wangli");
HtmlPage result = btn.click();
System.out.println(result.asText());
其他参数 HTMLUnit会替我们处理
成功登陆百度云 的例子:
public class Baidu {
public static void main(String[] args) {
// LogFactory.getFactory().setAttribute("org.apache.commons.logging.Log","org.apache.commons.logging.impl.NoOpLog");
// java.util.logging.Logger.getLogger("net.sourceforge.htmlunit").setLevel(java.util.logging.Level.OFF);
//
try {
WebClient wc = new WebClient(BrowserVersion.FIREFOX_38);
wc.getOptions().setJavaScriptEnabled(true);
wc.getOptions().setCssEnabled(false);
wc.getOptions().setThrowExceptionOnScriptError(false);
wc.getOptions().setThrowExceptionOnFailingStatusCode(false);
wc.getCookieManager().setCookiesEnabled(true);
wc.waitForBackgroundJavaScript(3000);//设置JS后台等待执行时间
String url = "http://pan.baidu.com/";
HtmlPage htmlPage = wc.getPage(url);
wc.waitForBackgroundJavaScript(1000); //这个放在 wc.getPage(url);后面
HtmlForm loginForm = htmlPage.getForms().get(0);
HtmlTextInput username = loginForm.getInputByName("userName");
HtmlPasswordInput password = loginForm.getInputByName("password");
HtmlSubmitInput btn = loginForm.getInputByValue("登录");//注意 登录中间有括号的情况
username.setValueAttribute("burning你的心3");
password.setValueAttribute("454070wap.1223");
HtmlPage result = btn.click();
System.out.println(result.asText());
} catch (Exception e) {
e.printStackTrace();
}
}
}
83.
SpannableString spanStr = new SpannableString("欢迎使用我的博客下载器");
//各种span 类型
ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE);
//说明: 参数1,3 表示对 下标1~3(不包括3)应用样式 ,Spannable.SPAN_EXCLUSIVE_INCLUSIVE这个参数 指定,如果对已经应用了样式的 字符串,再输入(插入)Str,
// 原 字符串 的前面或后面是否应用样式 ------->
spanStr.setSpan(span, 1, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
editText.setText(spanStr);
84.
SpannableString spanStr = new SpannableString("欢迎使用我的博客下载器");
ForegroundColorSpan span = new ForegroundColorSpan(Color.BLUE); //字体颜色
UnderlineSpan underlineSpan = new UnderlineSpan(); //下划线
StrikethroughSpan strikethroughSpan = new StrikethroughSpan();//删除线
StyleSpan styleSpan = new StyleSpan(Typeface.BOLD_ITALIC); // StyleSpan(粗体和斜体 )
BackgroundColorSpan backgroundColorSpan = new BackgroundColorSpan(Color.YELLOW); //背景色
AbsoluteSizeSpan sizeSpan = new AbsoluteSizeSpan(16); //字体大小
Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); //means to provide you with the default height or width of that drawable.
ImageSpan imageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
spanStr.setSpan(imageSpan, 1, 3, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);
editText.setText(spanStr);
85.
Android中visibility属性VISIBLE、INVISIBLE、GONE的区别
可见(visible)
XML文件:android:visibility="visible"
Java代码:view.setVisibility(View.VISIBLE);
不可见(invisible)
XML文件:android:visibility="invisible"
Java代码:view.setVisibility(View.INVISIBLE);
隐藏(GONE)
XML文件:android:visibility="gone"
Java代码:view.setVisibility(View.GONE);
VISIBLE:设置控件可见
INVISIBLE:设置控件不可见
GONE:设置控件隐藏
而INVISIBLE和GONE的主要区别是:
当控件visibility属性为INVISIBLE时,界面保留了view控件所占有的空间;
而控件属性为GONE时,界面则不保留view控件所占有的空间。
86.
File file = File.createTempFile("capture",".jpg",new File("/sdcard"));
fos = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.PNG,90,fos);
fos.flush();
87.
SlideMenu (android-support-v4.jar自带 )侧滑菜单,引用lib则需要 删除自带工程的
88. 彻底删除mysql
C:\program\
C:\Documents and Settings\All users\MySQL\MySQL Server 5.1\data\mysql
89.