当前位置:  编程技术>移动开发
本页文章导读:
    ▪三. spring版 timer HelloWorld        3. spring版 timer HelloWorld 1. 由于这回需要使用Spring的jar包,所以需要修改pom文件,添加如下依赖:<!-- Spring framework --> <dependency> <groupId>org.springframework</groupId> <artifactId.........
    ▪ 解析搜狗音乐的音乐上载地址        解析搜狗音乐的音乐下载地址 // // SougouMusicParser.h // // Created by scott.8an@gmail.com on 12-3-13. // Copyright (c) 2012年 littleworn llc. All rights reserved. // #import <Foundation/Foundation.h> #import "ASIHTTPRequest.h".........
    ▪ 展示PopupWindow       显示PopupWindow         PopupWindow可以实现浮层效果,而且可以自定义显示位置,出现和退出时的动画,比如新浪微博顶部栏的微博分组就是用PopupWindow实现的。        一、实例化PopupWindo.........

[1]三. spring版 timer HelloWorld
    来源: 互联网  发布时间: 2014-02-18
3. spring版 timer HelloWorld
1. 由于这回需要使用Spring的jar包,所以需要修改pom文件,添加如下依赖:

<!-- Spring framework -->

<dependency>

	<groupId>org.springframework</groupId>

	<artifactId>spring</artifactId>

	<version>2.5.6</version>

</dependency>


注:如果使用3.0版本就不是只改个版本号的问题了,因为spring3.0已经分包了。

2. 编写Timer类代码:

package com.helloworld.common;



public class SayHelloTask{



	public void sayHello() {

		System.out.println("HelloWorld");

	}



}


注意:此domain类完全没有依赖任何接口!!!
3. 编写spring配置文件:这个代码比较多就不全贴上去了
<bean id="sayHelloTask"  />

首先是上面那个bean的声明。
<bean id="schedulerTask" >
		<property name="targetObject" ref="sayHelloTask" />
		<property name="targetMethod" value="sayHello" />
	</bean>
MethodInvokingTimerTaskFactoryBean 取代了JDK中的TimerTask

<bean id="timerTask"
		>
		<property name="timerTask" ref="schedulerTask" />
		<property name="delay" value="2000" />
		<property name="period" value="6000" />
	</bean>

这个取代了JDK中的Timer
<bean >
		<property name="scheduledTimerTasks">
			<list>
				<ref local="timerTask" />
			</list>
		</property>
	</bean>

定义一个TimerFactoryBean来启动Task。
4. 编写测试代码:
public class Test {
	public static void main(String[] args) {
		ApplicationContext context = new ClassPathXmlApplicationContext("Spring-Scheduler.xml");
		
	}
}

OK 一切运行成功。

    
[2] 解析搜狗音乐的音乐上载地址
    来源: 互联网  发布时间: 2014-02-18
解析搜狗音乐的音乐下载地址
//
//  SougouMusicParser.h
//
//  Created by scott.8an@gmail.com on 12-3-13.
//  Copyright (c) 2012年 littleworn llc. All rights reserved.
//

#import <Foundation/Foundation.h>
#import "ASIHTTPRequest.h"
#import "ASINetworkQueue.h"
#import "TFHpple.h"
#import "XPathQuery.h"
#import "TFHppleElement.h"
#import "DataType.h"

//页面地址
#define kRequestURL(/blog_article/s_songName,i_pageNumber/index.html) \
        [NSString stringWithFormat:@"http://mp3.sogou.com/music.so?pf=mp3&query=%@&page=%i&w=02009900&dr=1",s_songName,i_pageNumber]

@interface SogouMusicParser : NSObject

+ (SogouMusicParser*)shareInstance;

/**
 发送成功通知的数组结构:
 [
    {
        "song"="save me",
        "artist"="Queen",
        "size"="4.38M",
        "firstChoose_url"="http://ziyuan1.myi.cn/film/YINYUE/fir/firT1563.mp3",
        "other_link"= [
            "http://mul1.tximg.cn/music/group/bbs/mp3/7/090528/1243462409315.mp3",
            "http://api.ning.com/files/SRIkTa2lzwqL1jt26257Yzj3TCFZ6jAJD2HaYhYB*N469JhRrd01xDttiHqjJD7K9WkWr69u6LnXChFfA2Wid0jWUfiIB33m/f.i.r._.mp3"
        ]
    },...
 ]
 **/
- (void)runToGetSongInfoFromSogouWithKeyword:(NSString*)kw pageNumber:(NSInteger)pgNum;
@end



//
//  SougouMusicParser.m
//
//  Created by scott.8an@gmail.com on 12-3-13.
//  Copyright (c) 2012年 littleworn llc. All rights reserved.
//

#import "SogouMusicParser.h"

NSString *const SogouMusicParseSuccessNotification = @"SogouMusicParseSuccessNotification";
NSString *const SogouMusicParseFailedNotification = @"SogouMusicParseFailedNotification";

static SogouMusicParser *parser_ = nil;

@interface SogouMusicParser (Private)
//获得跳转地址的urls
/**
 [
 "http://mp3.sogou.com/down.so?gid=11950F9C68D7EDE7&globalId=1f940cf0056326c8&query=%CE%D2%C",
 "http://mp3.sogou.com/down.so?gid=11950F9C68D7EDE7&globalId=1f940cf0056326c8&query=%CE%D2%C",
 ...
 ]
 **/
- (NSArray*)getJumpToDownloadPageURLsWithKeyword:(NSString*)kw pageNumber:(int)pgNum;

/**
 返回字典结构:
 {
 "song"="save me",
 "artist"="Queen",
 "size"="4.38M",
 "firstChoose_url"="http://ziyuan1.myi.cn/film/YINYUE/fir/firT1563.mp3",
 "other_link"= [
 "http://mul1.tximg.cn/music/group/bbs/mp3/7/090528/1243462409315.mp3",
 "http://api.ning.com/files/SRIkTa2lzwqL1jt26257Yzj3TCFZ6jAJD2HaYhYB*N469JhRrd01xDttiHqjJD7K9WkWr69u6LnXChFfA2Wid0jWUfiIB33m/f.i.r._.mp3"
 ]
 }
 **/
- (NSDictionary*)getMusicInfoByJumpToUrl:(NSString*)jumpToUrl;
@end


@implementation SogouMusicParser

+ (SogouMusicParser*)shareInstance{
    if (!parser_) {
        parser_ = [[self alloc] init];
    }
    return parser_;
}

- (NSArray*)getJumpToDownloadPageURLsWithKeyword:(NSString*)kw pageNumber:(int)pgNum{
    if (kw && [kw length]) {
        //初始化需要返回的数组
        NSMutableArray *urlsArr = [NSMutableArray arrayWithCapacity:0];
        
        //去掉搜索条件两端空格
        NSString *pureKW = [kw stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
        
        //用 + 号连接需要要搜索的绑定条件
        NSArray *kwArr = [pureKW componentsSeparatedByString:@" "];
        NSMutableString *neededKw = [NSMutableString stringWithCapacity:0];
        if (kwArr && [kwArr count]) {
            for (NSString *str in kwArr) {
                [neededKw appendFormat:@"%@+",str];
            }
            
            //去掉最后一个 + 号
            [neededKw deleteCharactersInRange:NSMakeRange([neededKw length]-1, 1)];
        }else{
            neededKw = (NSMutableString*)kw;
        }
        //对url编码
        NSString *requestURLStr = kRequestURL(/blog_article/neededKw,pgNum/index.html);
        NSString *requestURLStrEnc = [requestURLStr stringByAddingPercentEscapesUsingEncoding:CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000)];
    
        //请求页面地址
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:requestURLStrEnc]];
        [request startSynchronous];
        
        //获得返回数据
        //NSString *responseStr = [request responseString];
        NSData  *responseData = [request responseData];
        //NSLog(@"%@",responseStr);
        
        if (responseData) {
            TFHpple *help = [TFHpple hppleWithHTMLData:responseData];
            if (help) {
                //用xpath解析获得歌曲的跳转地址
                //获得tbody节点
                NSString *xPath = @"//*[@id='songlist']";
                TFHppleElement *tableNode = [help peekAtSearchWithXPathQuery:xPath];
                TFHppleElement *tBodyNode = tableNode.firstChild;
                if (tBodyNode) {
                    NSMutableArray *childrenNodes = (NSMutableArray*)tBodyNode.children;
                    if (childrenNodes && [childrenNodes count]) {
                        //移除第一个node
                        [childrenNodes removeObjectAtIndex:0];
                        for (TFHppleElement *element in childrenNodes) {
                            NSArray *tdNodeArr = element.children;
                            if (tdNodeArr && [tdNodeArr count]) {
                                for (TFHppleElement *tdEle in tdNodeArr) {
                                    TFHppleElement *aNode = tdEle.firstChild;
                                    if (aNode && [[aNode objectForKey:@"action"] isEqualToString:@"down"]) {
                                        /**
                                         window.open('/down.so?gid=1A6F5F0BA3CDD9C8&globalId=137c9db3dc0bf7bf&query=%B2%BB%C3%F0%B5%C4%B0%AE&tgid=629801e642a2eadc&pf=mp3&s=%CC%B7%D3%BD%F7%EB&t=%B2%BB%C3%F0%B5%C4%B0%AE&size=4195343&ac=0&c','
                                         ','width=431,height=495,scrollbars=no');
                                         uigsPB('consume=music_down&music_down=28');return(false);
                                         */
                                        NSString *urlThatMixed = [aNode objectForKey:@"onclick"];
                                        NSArray *urlParts = [urlThatMixed componentsSeparatedByString:@"'"];
                                        //取第二个作为uri
                                        NSString *uri = [urlParts objectAtIndex:1];
                                        
                                        if (uri && [uri length]) {
                                            NSString *url = [NSString stringWithFormat:@"http://mp3.sogou.com%@",uri];
                                            //NSLog(@"组合新的跳转地址:http://mp3.sogou.com%@",uri);
                                            
                                            [urlsArr addObject:url];
                                        }
                                    }
                                }
                            }
                        }
                        if ([urlsArr count]) {
                            return urlsArr;
                        }
                    }
                }
            }
        }else{
            //再次尝试
            [self getJumpToDownloadPageURLsWithKeyword:kw pageNumber:pgNum];
        }
    }
    return nil;
}

- (NSDictionary*)getMusicInfoByJumpToUrl:(NSString*)jumpToUrl{
    if (jumpToUrl && [jumpToUrl length]) {
        //获得下载页面,不需要编码,因为获得的数据已经是编码过了的
        ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:jumpToUrl]];
        [request startSynchronous];
        
        //获得返回界面
        NSString *responseStr = [request responseString];
        NSData *responseData = [request responseData];
      // NSLog(@"返回下载界面的网页信息:%@",responseStr);
        
        if (responseData) {
            NSMutableDictionary *dictionary = [NSMutableDictionary dictionaryWithCapacity:0];
            
            //解析页面
            TFHpple *help = [TFHpple hppleWithHTMLData:responseData];
            
            /**
             1.查找歌曲的下载地址
             **/
            
            //href="/blog_article/.. .mp3"
            NSString *pattern = @"href=/index.html"..+.mp3\"";
            NSRegularExpression *exp = [NSRegularExpression regularExpressionWithPattern:pattern
                                                                                 options:NSRegularExpressionCaseInsensitive
                                                                                   error:nil];
            NSArray *metchedArr = [exp matchesInString:responseStr options:NSMatchingReportProgress range:NSMakeRange(0, [responseStr length])];
        
            if (metchedArr && [metchedArr count]) {
                //用数组保存其他连接
                NSMutableArray *otherLinksArr = [NSMutableArray arrayWithCapacity:0];
                for (NSTextCheckingResult *result in metchedArr) {
                    NSRange range = result.range;
                    NSString *urlWithHREF = [responseStr substringWithRange:range];
                    if (urlWithHREF && [urlWithHREF length]) {
                        NSArray *urlParts = [urlWithHREF componentsSeparatedByString:@"\""];
                        if (urlParts && [urlParts count]>2) {
                            NSString *musicURL = [urlParts objectAtIndex:1];
                            
                            //把第一个获得的地址存到首选里去
                            NSString *songURL = [dictionary objectForKey:@"firstChoose_url"];
                            if (!songURL || [songURL length]<1) {
                                [dictionary setObject:musicURL forKey:@"firstChoose_url"];
                            }else{
                                //去重
                                if (![musicURL isEqualToString:songURL]) {
                                    //用数组保存其他链接
                                    [otherLinksArr addObject:musicURL];
                                }
                            }
                        }
                    }
                }
                
                //保存其他链接到字典
                [dictionary setObject:otherLinksArr forKey:@"other_link"];
            }
            
            //如果下载地址解析失败,一下内容都没有必要存在
            NSString *firstChoose_url = [dictionary objectForKey:@"firstChoose_url"];
            if (firstChoose_url && [firstChoose_url length]) {
                /**
                 2.查找歌曲的名称
                 **/
                NSString *xPath = @"//*[@info1\"]";
                TFHppleElement *info1Node = [help peekAtSearchWithXPathQuery:xPath];
                TFHppleElement *aNode = info1Node.firstChild;
                NSString *songName = [aNode objectForKey:@"title"];
                if (songName && [songName length]) {
                    [dictionary setObject:songName forKey:@"song"];
                }else{
                    [dictionary setObject:@"Unknown" forKey:@"song"];
                }
                
                
                /**
                 3.查找艺术家
                 **/
                NSArray *info1Children = info1Node.children;
                if (info1Children && [info1Children count]) {
                    BOOL isArtistTag = NO;
                    for (TFHppleElement *node in info1Children) {
                        if ([node.tagName isEqualToString:@"a"] && isArtistTag) {
                            NSString *artist = [node objectForKey:@"title"];
                            if (artist && [artist length]) {
                                [dictionary setObject:artist forKey:@"artist"];
                                isArtistTag =NO;
                            }
                        }
                        isArtistTag = YES;
                    }
                }
                NSString *hasArtist = [dictionary objectForKey:@"artist"];
                if (!hasArtist || [hasArtist length]<1) {
                    [dictionary setObject:@"Unknown" forKey:@"artist"];
                }
                
                /**
                 4.查找歌曲的大小
                 **/
                xPath = @"//*[@info2\"]";
                TFHppleElement *info2Node = [help peekAtSearchWithXPathQuery:xPath];
                NSArray *children = info2Node.children;
                if (children && [children count]) {
                    for (TFHppleElement *node in children) {
                        if ([node.tagName isEqualToString:@"strong"]) {
                            NSString *sizeDesc = node.content;
                            if (sizeDesc && [sizeDesc length]) {
                                [dictionary setObject:sizeDesc forKey:@"size"];
                            }
                        }
                    }
                }
                NSString *hasSize = [dictionary objectForKey:@"size"];
                if (!hasSize || [hasSize length]<1) {
                    [dictionary setObject:@"Unknown" forKey:@"size"];
                }
                
                //NSLog(@"***************歌曲信息:%@",dictionary);
                
                //返回字典
                return dictionary;
            }
            return nil;
        }else{
            //重新请求,直到获取成功
            [self getMusicInfoByJumpToUrl:jumpToUrl];
        }
    }
    return nil;
}

- (void)runToGetSongInfoFromSogouWithKeyword:(NSString*)kw pageNumber:(NSInteger)pgNum{
    if (kw && [kw length]) {
        NSMutableArray *songsInfoArr = [NSMutableArray arrayWithCapacity:0];
        
        NSArray *songsURLsArr = [self getJumpToDownloadPageURLsWithKeyword:kw pageNumber:pgNum];
        
        //如果第一次请求失败,再次请求
        if (!songsInfoArr || [songsInfoArr count]<1) {
            songsURLsArr = [self getJumpToDownloadPageURLsWithKeyword:kw pageNumber:pgNum];
        }
        //如果第二次请求失败,再次请求
        if (!songsInfoArr || [songsInfoArr count]<1) {
            songsURLsArr = [self getJumpToDownloadPageURLsWithKeyword:kw pageNumber:pgNum];
        }
        
        if (songsURLsArr && [songsURLsArr count]) {
            for (NSString *url in songsURLsArr) {
                NSDictionary *songInfo = [self getMusicInfoByJumpToUrl:url];
                if (songInfo && [songInfo count]) {
                    [songsInfoArr addObject:songInfo];
                }
            }
        }
        
        if ([songsInfoArr count]) {
            [[NSNotificationCenter defaultCenter] postNotificationName:SogouMusicParseSuccessNotification
                                                                object:nil userInfo:[NSDictionary dictionaryWithObject:songsInfoArr forKey:@"songsInfo"]];
        }else{
            [[NSNotificationCenter defaultCenter] postNotificationName:SogouMusicParseFailedNotification
                                                                object:nil userInfo:[NSDictionary dictionaryWithObject:@"This page does not exist" 
                                                                                                                forKey:@"msg"]];
        }
    }else{
        [[NSNotificationCenter defaultCenter] postNotificationName:SogouMusicParseFailedNotification
                                                            object:nil userInfo:[NSDictionary dictionaryWithObject:@"Check what you've been input" 
                                                                                                            forKey:@"msg"]];
    }
}
@end


    
[3] 展示PopupWindow
    来源: 互联网  发布时间: 2014-02-18
显示PopupWindow
        PopupWindow可以实现浮层效果,而且可以自定义显示位置,出现和退出时的动画,比如新浪微博顶部栏的微博分组就是用PopupWindow实现的。

        一、实例化PopupWindow,这里用R.layout.group_list填充mPopupWindow,并指定宽高。
mPopupLayout = getLayoutInflater().inflate(R.layout.group_list, null);
mPopupWindow = new PopupWindow(mPopupLayout, width, height, true);

        二、指定PopupWindow的显示位置
//mAncorView是页面中的某个View,默认是将mPopupWindow与mAncorView的左下角对齐,如果空间不够显示,则将将mPopupWindow与mAncorView的左上角对齐。offsetX和offsetY是mPopupWindow位置的相对偏移,很容易理解。
		mPopupWindow.showAsDropDown(mAncorView, offsetX, offsetY);


也可使用下面方法
//下面的方法是用屏幕上的绝对坐标显示,mPopupWindow
//我们往往不知道mPopupWindow要显示的精确位置,通常先计算页面上某个元素mView的位置,在进行偏移
		
//得到mView在屏幕中的坐标
int [] pos = new int[2];
mView.getLocationOnScreen(pos);
offsetY = pos[1] + mView.getHeight();
offsetX = 0;
		
//显示mPopupWindow
mPopupWindow.showAtLocation(mView, Gravity.TOP|Gravity.CENTER_HORIZONTAL, offsetX, offsetY);//这里的第一个参数没搞明白什么用,android官方文档说是为了获取token


        三、为PopupWindow指定动画
先定义动画
PopupWindow出现时的动画,popup_enter.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale android:fromXScale="0.6" android:toXScale="1.0"
        android:fromYScale="0.6" android:toYScale="1.0" android:pivotX="50%"
        android:pivotY="50%" android:duration="1000" />

    <alpha android:interpolator="@android:anim/decelerate_interpolator"
        android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="1000" />
</set>


PopupWindow消失时的动画,popup_exit.xml
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android">
    <scale
        android:fromXScale="1.0"
        android:toXScale="0.5"
        android:fromYScale="1.0"
        android:toYScale="0.5"
        android:pivotX="50%"
        android:pivotY="50%"
        android:duration="500" />

    <alpha
        android:interpolator="@android:anim/accelerate_interpolator"
        android:fromAlpha="1.0"
        android:toAlpha="0.0"
        android:duration="500" />
</set>


再设定动画的style
<style name="PopupAnimation" parent="android:Animation">
    <item name="android:windowEnterAnimation">@anim/popup_enter</item>
    <item name="android:windowExitAnimation">@anim/popup_exit</item>
</style>


最后通过Java代码设置动画
mPopupWindow.setAnimationStyle(R.style.PopupAnimation);

    
最新技术文章:
▪Android开发之登录验证实例教程
▪Android开发之注册登录方法示例
▪Android获取手机SIM卡运营商信息的方法
▪Android实现将已发送的短信写入短信数据库的...
▪Android发送短信功能代码
▪Android根据电话号码获得联系人头像实例代码
▪Android中GPS定位的用法实例
▪Android实现退出时关闭所有Activity的方法
▪Android实现文件的分割和组装
▪Android录音应用实例教程
▪Android双击返回键退出程序的实现方法
▪Android实现侦听电池状态显示、电量及充电动...
▪Android获取当前已连接的wifi信号强度的方法
▪Android实现动态显示或隐藏密码输入框的内容
互联网 iis7站长之家
▪Android Touch事件分发过程详解
▪Android中实现为TextView添加多个可点击的文本
▪Android程序设计之AIDL实例详解
▪Android显式启动与隐式启动Activity的区别介绍
▪Android按钮单击事件的四种常用写法总结
▪Android消息处理机制Looper和Handler详解
▪Android实现Back功能代码片段总结
▪Android实用的代码片段 常用代码总结
▪Android实现弹出键盘的方法
▪Android中通过view方式获取当前Activity的屏幕截...
▪Android提高之自定义Menu(TabMenu)实现方法
▪Android提高之多方向抽屉实现方法
▪Android提高之MediaPlayer播放网络音频的实现方法...
▪Android提高之MediaPlayer播放网络视频的实现方法...
▪Android提高之手游转电视游戏的模拟操控
 


站内导航:


特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

©2012-2021,,E-mail:www_#163.com(请将#改为@)

浙ICP备11055608号-3