ava中的阻塞队列

来源:互联网 发布:火爆天王 知轩藏书 编辑:程序博客网 时间:2024/05/30 04:41
A <phone:PhoneApplicationPage
    x:Class="Demo.Others.FastResume"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">


    <Grid x:Name="LayoutRoot" Background="Transparent">
        <StackPanel
            <TextBlock TextWrapping="Wrap">
                <Run>1、什么是快速恢复应用:当你点击 tile 启动了 app 后,再回到开始屏幕,再点击 tile 可以直接恢复应用而不是重新启动应用(wp8 新特性)</Run>
                <LineBreak />
                <Run>2、如何实现快速恢复应用:在 manifest 中的 DefaultTask 节点中增加 ActivationPolicy="Resume"</Run>
            </TextBlock>
                
        </StackPanel>
    </Grid
</phone:PhoneApplicationPage>

7、App.xaml.cs 的说明

http://www.lqkqyy.com/yxb/1246.html
http://www.lqkqyy.com/yxb/1245.html
http://www.lqkqyy.com/yxb/1244.html
http://www.lqkqyy.com/yxb/1243.html
http://www.njpfyy.com/npxzz/5415.html
http://www.njpfyy.com/npxzz/5416.html
http://www.njpfyy.com/npxyf/5417.html
http://www.njpfyy.com/npxzz/5418.html
http://www.njpfyy.com/npxzl/5419.html
http://www.pf025.com/bzdh/hbjhblxxpfb/yxb/1904.html
http://www.pf025.com/bzdh/hbjhblxxpfb/yxb/1905.html
http://www.pf025.com/bzdh/hbjhblxxpfb/yxb/1906.html
http://www.pf025.com/bzdh/hbjhblxxpfb/yxb/1907.html
http://www.pf025.com/bzdh/hbjhblxxpfb/yxb/1908.html
http://www.pxsrxx.com/npxzz/5586.html
http://www.pxsrxx.com/npxzz/5587.html
http://www.pxsrxx.com/npxzz/5588.html
http://www.pxsrxx.com/npxzz/5589.html
http://www.pxsrxx.com/npxzz/5590.html

Others/AppXamlCs.xaml
<phone:PhoneApplicationPage
    x:Class="Demo.Others.AppXamlCs"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">
    
    <Grid Background="Transparent">
        <StackPanel>
            <TextBlock x:Name="lblMsg" TextWrapping="Wrap">
                <Run>关于 App.xaml.cs 的说明,参见它的注释就好,写得很清楚了


</Run>
                <LineBreak />
                <Run>注意:导航过程中发生异常会通过 RootFrame_NavigationFailed 捕获,其他未处理异常会通过 Application_UnhandledException 捕获</Run>
            </TextBlock>
    
        </StackPanel>
    </Grid>
    http://www.lqkqyy.com/yxb/1246.html
http://www.lqkqyy.com/yxb/1245.html
http://www.lqkqyy.com/yxb/1244.html
http://www.lqkqyy.com/yxb/1243.html
http://www.njpfyy.com/npxzz/5415.html
http://www.njpfyy.com/npxzz/5416.html
http://www.njpfyy.com/npxyf/5417.html
http://www.njpfyy.com/npxzz/5418.html
http://www.njpfyy.com/npxzl/5419.html
http://www.pf025.com/bzdh/hbjhblxxpfb/yxb/1904.html
http://www.pf025.com/bzdh/hbjhblxxpfb/yxb/1905.html
http://www.pf025.com/bzdh/hbjhblxxpfb/yxb/1906.html
http://www.pf025.com/bzdh/hbjhblxxpfb/yxb/1907.html
http://www.pf025.com/bzdh/hbjhblxxpfb/yxb/1908.html
http://www.pxsrxx.com/npxzz/5586.html
http://www.pxsrxx.com/npxzz/5587.html
http://www.pxsrxx.com/npxzz/5588.html
http://www.pxsrxx.com/npxzz/5589.html
http://www.pxsrxx.com/npxzz/5590.html


</phone:PhoneApplicationPage>   //  输出日志信息   
    printk("word_init_exit_success\n");   
}      
//  注册初始化Linux驱动的函数   
module_init( word_count_init);   
//  注册卸载Linux驱动的函数   
module_exit( word_count_exit);   
       
MODULE_AUTHOR("lining");   
MODULE_DESCRIPTION("statistics of word count.");   
MODULE_ALIAS("word count module.");   
MODULE_LICENSE("GPL");
1.Started POST "/posts" for 106.3.102.43 at 2012-10-29 21:16:26 +0800 
02.Processing by PostsController#create as HTML 
03. Parameters: {"utf8"=>"?", "authenticity_token"=>"QG8aU6/VW5ZMagzyGhjdbm7fSzr4MB5CKdJeGBIeOa4=", "post"=>{"category_id"=>"1", "title"=>"666666666666", "url"=>"6666666", "picture"=>#<ActionDispatch::Http::UploadedFile:0x000000032fb838 @original_filename=".gitconfig", @content_type="application/octet-stream", @headers="Content-Disposition: form-data; name=\"post[picture]\"; filename=\".gitconfig\"\r\nContent-Type: application/octet-stream\r\n", @tempfile=#<File:/tmp/RackMultipart20121029-2609-1lrmc9o>>, "content"=>"6666", "tags_attributes"=>{"0"=> {"title"=>""}}}, "commit"=>"Create Post"} 
04.Redirected to 42.121.5.68/posts 
/ 向指定的地址发送邮件
            bool success = await Launcher.LaunchUriAsync(new Uri("mailto:aaa@xxx.com"));
        }
        private async void btnMarketplaceDetail_Click(object sender, RoutedEventArgs e)
        {
            // 打开指定 app 在商店中的详细页
            bool success = await Launcher.LaunchUriAsync(new Uri("zune:navigate?appid=02adaaff-ad55-42b4-9ca1-fd4d1dadd32a"));
        }
    
        private async void btnMarketplaceReview_Click(object sender, RoutedEventArgs e)
        {
            // 在商店中评论指定的 app
            bool success = await Launcher.LaunchUriAsync(new Uri("zune:reviewapp?appid=02adaaff-ad55-42b4-9ca1-fd4d1dadd32a"));
        }
    
        private async void btnMarketplaceSearch_Click(object sender, RoutedEventArgs e)
        {
            // 在商店中搜索 app(支持按关键字和发行商搜索)
            bool success = await Launcher.LaunchUriAsync(new Uri("zune:search?keyword=&publisher=webabcd&contenttype=app"));
        }
    Element e = (Element) nl.item(i);
            // adding each child node to HashMap key => value
            map.put(KEY_ID, parser.getValue(e, KEY_ID));
            map.put(KEY_NAME, parser.getValue(e, KEY_NAME));
            map.put(KEY_COST, "Rs." + parser.getValue(e, KEY_COST));
            map.put(KEY_DESC, parser.getValue(e, KEY_DESC));
    
            // adding HashList to ArrayList
            menuItems.add(map);
        }
    
        // Adding menuItems to ListView
        ListAdapter adapter = new SimpleAdapter(this, menuItems,
                R.layout.list_item,
                new String[] { KEY_NAME, KEY_DESC, KEY_COST }, new int[] {
                        R.id.name, R.id.desciption, R.id.cost });
    
        setListAdapter(adapter);
    
        // selecting single ListView item
        ListView lv = getListView();
    
        lv.setOnItemClickListener(new OnItemClickListener() {
    
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // getting values from selected ListItem
05.Completed 302 Found in 36ms (ActiveRecord: 30.1ms) 
01.Started POST "/posts" for 123.114.36.100 at 2012-10-30 08:58:13 +0800 
02.Processing by PostsController#create as HTML 
03. Parameters: {"utf8"=>"?", "authenticity_token"=>"rRnhcDWYDn+OntxxC2LmIEHpSpjWI5glrs6JlprG1Ho=", "post"=>{"category_id"=>"1", "title"=>"博 客尝试最新法宝", "url"=>"post7", "picture"=>#<ActionDispatch::Http::UploadedFile:0x000000030df9a0 @original_fil
ename="新浪微博数据挖掘方案.pdf", @content_type="binary/octet- stream", @headers="Content-Disposition: form-data; name=\"post[picture]\"; filename=\"\xE6\x96\xB0\xE6\xB5\xAA\xE5\xBE\xAE\xE5\x8D\x9A\xE6\x95\xB0\xE6\x8D\xAE\xE6 \x8C\x96\xE6\x8E\x98\xE6\x96\xB9\xE6\xA1\x88.pdf\"\r\nContent-Type: binary/octet- stream\r\n", @tempfile=#<File:/tmp/RackMultipart20121030-16129-15agvlb>>, "content"=>"博客尝>试最新法宝", "tags_attributes"=> {"0"=>{"title"=>"博客尝试最新法宝"}}}, "commit"=>"Create Post"} 
04.Completed 500 Internal Server Error in 45ms 
05. 
06.Encoding::UndefinedConversionError ("\xE2" from ASCII-8BIT to UTF-8): 
07. app/controllers/posts_controller.rb:60:in `write' 
08. app/controllers/posts_controller.rb:60:in `block (2 levels) in create' 
09. app/controllers/posts_controller.rb:59:in `open' 
10. app/controllers/posts_controller.rb:59:in `block in create' 
11. app/controllers/posts_controller.rb:56:in `create'
  private async void btnEmailAccount_Click(object sender, RoutedEventArgs e)
        {
            // 跳转到“电子邮件+账户设置”页
            bool success = await Launcher.LaunchUriAsync(new Uri("ms-settings-emailandaccounts:"));
        }
    
        private async void btnLockScreen_Click(object sender, RoutedEventArgs e)
        {
            // 跳转到“锁屏设置”页
            bool success = await Launcher.LaunchUriAsync(new Uri("ms-settings-lock:"));
        }
    
        private async void btnCallTo_Click(object sender, RoutedEventArgs e)
        {
            // 拨打指定的电话号码
            bool success = await Launcher.LaunchUriAsync(new Uri("tel:1391234567"));
            // bool success = await Launcher.LaunchUriAsync(new Uri("callto:1391234567"));
        }
    
        private async void btnHttp_Click(object sender, RoutedEventArgs e)
        {
            // 用浏览器打开一个指定的 http 链接
            bool success = await Launcher.LaunchUriAsync(new Uri("http://webabcd.cnblogs.com/"));
        }
    
        private async void btnMailTo_Click(object sender, RoutedEventArgs e)
        {
private String email;  
          
    //创建日期  
    private Date createDate;  
          
    //接收界面中的选中标记的集合  
    private String[] selectFlag;  
          
    public String getContactTel() {  
        return contactTel;  
    }  
      
    public void setContactTel(String contactTel) {  
        this.contactTel = contactTel;  
    }  
        // 跳转到“飞行模式设置”页
            bool success = await Launcher.LaunchUriAsync(new Uri("ms-settings-airplanemode:"));
        }
    
        private async void btnBluetooth_Click(object sender, RoutedEventArgs e)
        {
            // 跳转到“蓝牙设置”页
            bool success = await Launcher.LaunchUriAsync(new Uri("ms-settings-bluetooth:"));
        }
    
        private async void btnCellular_Click(object sender, RoutedEventArgs e)
        {
            // 跳转到“手机网络设置”页
            bool success = await Launcher.LaunchUriAsync(new Uri("ms-settings-cellular:"));
        }
    
        private async void btnWiFi_Click(object sender, RoutedEventArgs e)
        {
            // 跳转到“WiFi设置”页
            bool success = await Launcher.LaunchUriAsync(new Uri("ms-settings-wifi:"));
        }
    
        private async void btnLocation_Click(object sender, RoutedEventArgs e)
        {
            // 跳转到“定位设置”页
            bool success = await Launcher.LaunchUriAsync(new Uri("ms-settings-location:"));
        }
    public Date getCreateDate() {  
        return createDate;  
    }  
      
    public void setCreateDate(Date createDate) {  
        this.createDate = createDate;  
    }  
      
ploaded_io = params[:post][:picture] 
        if uploaded_io != nil and uploaded_io.content_type.match('image') 
     
          File.open(Rails.root.join('public','uploads',uploaded_io.original_filename),'w') do 


|f| 
/*
 * 演示系统的内置协议(uri 关联)
 * 
 * 
 * 注:系统保留的文件类型和保留的协议类型详见如下链接
 * http://msdn.microsoft.com/zh-cn/library/windowsphone/develop/jj207065
 */
    
using System;
using System.Windows;
using Microsoft.Phone.Controls;
using Windows.System;
    
namespace Demo.Others
{
    public partial class ReservedProtocol : PhoneApplicationPage
    {
        public ReservedProtocol()
        {
            InitializeComponent();
        }
    
        private async void btnAirplane
     
            f.write(uploaded_io.read) 
          end 
     
        else
end
uploaded_io = params[:post][:picture] 
        if uploaded_io != nil and uploaded_io.content_type.match('image') 
     
          File.open(Rails.root.join('public','uploads',uploaded_io.original_filename),'wb') do 


|f| 
     
            f.write(uploaded_io.read) 
          end 
     
        else
end
<div class="field"> 
  <%= f.label :picture %><br/> 
  <%= f.file_field :picture %> 
</div>
 public void setUserId(String userId) {  
        this.userId = userId;  
    }  
      
    public String getUserName() {  
        return userName;  
    }  
public class AndroidXMLParsingActivity extends ListActivity {
    
    // All static variables
    static final String URL = "10.0.2.2/biyeshejidata/menu.xml";
    // XML node keys
    static final String KEY_ITEM = "item"; // parent node
    static final String KEY_ID = "id";
    static final String KEY_NAME = "name";
    static final String KEY_COST = "cost";
    static final String KEY_DESC = "description";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    
        ArrayList<HashMap<String, String>> menuItems = new ArrayList<HashMap<String, String>>();
    
        XMLParser parser = new XMLParser();
        String xml = parser.getXmlFromUrl(URL); // getting XML
        Document doc = parser.getDomElement(xml); // getting DOM element
    
        NodeList nl = doc.getElementsByTagName(KEY_ITEM);
        // looping through all item nodes <item>  
    public void setUserName(String userName) {  
        this.userName = userName;  
    }  
      
    public String[] getSelectFlag() {  
        return selectFlag;  
    }  
      
    public void setSelectFlag(String[] selectFlag) {  
        this.selectFlag = selectFlag;  
    }  
}
     type="com.tgb.drp.web.actions.UserAction"
            name="userForm"
            scope="request"
            parameter="command"
    >  
        <forward name="list_success" path="/user/user_list.jsp"/>  
        <forward name="del_success" path="/user/user_maint.do" redirect="true"/>  
        <forward name="add_success" path="/user/user_maint.do" redirect="true"/>  
        <forward name="modify_success" path="/user/user_maint.do" redirect="true"/>  
        <forward name="find_success" path="/user/user_modify.jsp"/>  
               
    </action>  
<action path="/user/show_add"
        forward="/user/user_input.jsp"
></action>  
session[:user_id] = @current_user.id 
User.find(session[:user_id])
2.2.session id
sessionid是一个32字节的md5哈希值。
sessionid由随机字符串的哈希值组成。随机字符串包括当前时间,0-1之间的随机数,ruby解释器的进程id(也是一个随机数字),一个常量字符串。当目前为止,暴利攻击rails的sessionid是不可行的。MD5是不可逆的,但是可以碰撞,因此创建一个相同哈希值的字符串只是存在理论的可能性。
2.3session劫持
        private void LicenseInformationDemo()
        {
            // 当前 app 的许可证信息
            LicenseInformation licenseInformation = CurrentApp.LicenseInformation;
    
            // 许可证ok则为true,否则无许可证或许可证过期则为false
            // licenseInformation.IsActive;  
    
            // 是否是试用许可证
            // licenseInformation.IsTrial;
    
            // 许可证的到期时间
            // licenseInformation.ExpirationDate;
    
            // 许可证状态发生变化时所触发的事件
            // licenseInformation.LicenseChanged;
    
            // 获取此 app 相关的 ProductLicenses 集合
            // licenseInformation.ProductLicenses;
    
    
            // ProductLicense - 产品许可证
            //     ProductId - 产品 ID
            //     IsActive - 此产品许可证ok则为true,否则无此产品许可证或此产品许可证过期则为false
            //     IsConsumable - 产品类型是否是消费型
            //     ExpirationDate - 此产品许可证的到期时间


偷了一个用户的sessionid之后,一个攻击者就可以用受害者的名义访问web应用。
很多web应用都有验证系统:用户提供登陆账号和登录密码,web应用验证这些信息,验证通过之后,将用户的id保存到session中。在这之后,这个session就是有效的了。每次请求都会加载用户,通过session中的用户id识别用户,不需要再次验证。在cookie的sessionid用来识别session。
因此,cookie为web应用提供了临时的验证功能。每个从某个人哪里获取cookie的用户,可以以那个人的名义使用web应用,可能会产生严重的后果。下面是一些劫持session的方法,已经相应的对策。
客户端可以看到在session中存储的所有内容,因为是明文存储(事实上是base64编码,但是没有加密)。当然,你不会在里面存储任何秘密。为了防止session哈希值被篡改,从session中用服务端的密钥计算的一个数字会被插入到cookie的最后面。
这就意味着这种储存方式依赖于这个密钥(和这个数字算法,默认是SHA512,还没有被破解)。因此不使用不重要的密钥,例如字典中的一个单词,或者是短于30个字符。把这个密钥放在你的environment.rb中。
config.action_dispatch.session = { 
  :key    => '_app_session', 
  :secret => '0x0dkfj3927dkc7djdh36rkckdfzsg...'
}
因为CookieStore的继承类加密session哈希值,因此客户端是看不到的。
2.6.重复CookieStore session的攻击
你需要注意的另一种攻击是,在使用CookieStore的时候,受到的重复攻击。
攻击的过程是这样的:
一个用户收到信用卡信息,金额存储在session中(这不是一个好主意,我们只是来证明)。
这个用户买了一些东西。
2.7.固定session
】package com.tgb.drp.web.forms;  
      
import java.util.Date;  
      
import org.apache.struts.action.ActionForm;  
      
/** 
 * 用户管理ActionForm 
 * 
 */
public class UserActionForm extends ActionForm {  
          
    //用户代码  
    private String userId;  
          
    //用户名称  
    private String userName;  
          
    //密码  
    private String password;  
下面就是一个例子。
<a href="www.harmless.com/" onclick=" 
  var f = document.createElement('form'); 
  f.style.display = 'none'; 
  this.parentNode.appendChild(f); 
  f.method = 'POST'; 
  f.action = 'www.example.com/account/destroy'; 
  f.submit(); 
       
    /** Getting node value
      * @param elem element
      */
     public final String getElementValue( Node elem ) {
         Node child;
         if( elem != null){
             if (elem.hasChildNodes()){
                 for( child = elem.getFirstChild(); child != null; child = child.getNextSibling() ){
                     if( child.getNodeType() == Node.TEXT_NODE  ){
                         return child.getNodeValue();
                     }
                 }
             }
         }
         return "";
     }
     /**
      * Getting node value
      * @param Element node
      * @param key string
      * */
     public String getValue(Element item, String str) {        
            NodeList n = item.getElementsByTagName(str);        
            return this.getElementValue(n.item(0));
        }
}
  return false;">To the harmless survey</a>
在a标签中内嵌了一个form,发送post请求,对数据造成破坏。
攻击代码也可以放在img的mouse事件中。
<img src="www.harmless.com/img" width="400" height="400" onmouseover="..." />
一个应对csrf的办法就是在非get请求中加入token验证,在rails中已经内置了这种方法,只需要在applicationcontroller中加入下面一行代码。默认是已经加好的。
protect_from_forgery :secret => "123456789012345678901234567890..."
4.跳转和文件
在web应用中,还有一些安全漏洞是与跳转和文件相关
public ActionForward find(ActionMapping mapping, ActionForm form,  
            HttpServletRequest request, HttpServletResponse response)  
            throws Exception {  
        //获取从页面表单中提交过来的值  
        UserActionForm uaf = (UserActionForm)form;  
              
        String userId = uaf.getUserId();  
              
        //调用业务逻辑操作  
        User user = UserManager.getInstance().findUserById(userId);  
              
        //将user对象从Action传递到JSP页面  
        request.setAttribute("user", user);  
              
        return mapping.findForward("find_success");  
    }  
          
}
package com.tgb.drp.web.actions;  
      
import java.util.Date;  
import java.util.List;  
      
import javax.servlet.http.HttpServletRequest;  
import javax.servlet.http.HttpServletResponse;  
      
import org.apache.commons.beanutils.BeanUtils;  
import org.apache.struts.action.ActionForm;  
import org.apache.struts.action.ActionForward;  
import org.apache.struts.action.ActionMapping;  
import org.apache.struts.actions.DispatchAction;  
      
import com.tgb.drp.manager.UserManager;  
import com.tgb.drp.model.User;  
import com.tgb.drp.web.forms.UserActionForm;  
      
public class UserAction extends DispatchAction {  
// ListingInformation - 此 app 在 Windows 商店中的相关信息
            //     AgeRating - app 的年龄分级            
            //     CurrentMarket - app 的当前商店,如:en-us
            //     Name - app 在当前商店中的名称
            //     FormattedPrice - app 在当前商店中的价格
            //     Description - app 在当前商店中的程序说明
            //     ProductListings - app 在当前商店中的 ProductListing 集合
    
    
            // ProductListing - app 的产品信息
            //     ProductId - 产品 ID
            //     Name - 产品名称
            //     FormattedPrice - 产品当前市场的格式化后的价格
            //     ImageUri - 产品关联的图片的 uri
            //     Description - 产品说明
            //     Keywords - 搜索关键字
            //     ProductType - 产品类型
            //         Unknown - 未知
            //         Durable - 耐用型:用户购买后由用户永远所有的产品)
            //         Consumable - 消费型:可以购买、使用(消耗)和再度购买的产品
            //     Tag - 自定义标记字符串
ody>  
    <a href="user/user_maint.do" title="请点击访问用户管理系统">用户管理系统</a>  
</body>
  @Override
    protected ActionForward unspecified(ActionMapping mapping, ActionForm form,  
            HttpServletRequest request, HttpServletResponse response)  
            throws Exception {  
        //调用业务逻辑操作  
        List userList = UserManager.getInstance().findAllUserList();  
        request.setAttribute("userlist", userList);  
              
        return mapping.findForward("list_success");  
    }  
      
    /** 
     * 用户删除 
     * @param mapping 
     * @param form 
     * @param request 
     * @param response 
     * @return 
     * @throws Exception 
 
calls  
if ("execute".equals(name) || "perform".equals(name)){  
    String message =  
        messages.getMessage("dispatch.recursive", mapping.getPath());  
      
    log.error(message);  
    throw new ServletException(message);  
}
所以在给parameter设置值时,不能为execute或perform。
在DispatchAction的 dispatchMethod中,有如下代码:
if (name == null) {  
    return this.unspecified(mapping, form, request, response);  
}
即如果parameter值为空,则执行unspecifi
        HttpServletRequest request, HttpServletResponse response)  
            throws Exception {  
        //获取从页面表单中提交过来的值  
        UserActionForm uaf = (UserActionForm)form;  
              
        //取得需要删除的userId的集合  
        String[] userIdList = uaf.getSelectFlag();  
      
        //调用业务逻辑操作  
        UserManager.getInstance().deleteUsers(userIdList);  
        return mapping.findForward("del_success");  
    }  
          
    /** 
     * 用户添加 
     * @param mapping 
     * @param form 
     * @param request 
     * @param response 
     * @return 
     * @throws Exception 
     */
   
    /**
     * Getting XML DOM element
     * @param XML string
     * */
    public Document getDomElement(String xml){
        Document doc = null;
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        try {
    
            DocumentBuilder db = dbf.newDocumentBuilder();
    
            InputSource is = new InputSource();
                is.setCharacterStream(new StringReader(xml));
                doc = db.parse(is); 
    
            } catch (ParserConfigurationException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (SAXException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            } catch (IOException e) {
                Log.e("Error: ", e.getMessage());
                return null;
            }
    
            return doc;
    public ActionForward modify(ActionMapping mapping, ActionForm form,  
            HttpServletRequest request, HttpServletResponse response)  
            throws Exception {  
        //获取从页面表单中提交过来的值  
        UserActionForm uaf = (UserActionForm)form;  
        User user = new User();  
        BeanUtils.copyProperties(user, uaf);  
              
        //调用业务逻辑操作  
        UserManager.getInstance().modifyUser(user);  
        return mapping.findForward("modify_success");  
    }  
          
    /** 
     * 根据ID查询用户 
     *  
     * @param mapping 
     * @param form 
     * @param request 
     * @param response 
     * @return 
     * @throws Exception 
       HttpServletRequest request, HttpServletResponse response)  
            throws Exception {  
              
        //获取从页面表单中提交过来的值  
        UserActionForm uaf = (UserActionForm)form;  
        User user = new User();  
        BeanUtils.copyProperties(user, uaf);  
        user.setCreateDate(new Date());  
              
        //调用业务逻辑操作  
        UserManager.getInstance().addUser(user);  
        return mapping.findForward("add_success");  }  
      
    /** 
     * 修改用户 
     * @param mapping 
     * @param form 
     * @param request 
     * @param response 
     * @return 
     * @throws Exception 
     */
由于授权问题,在较新的Linux发行版本中都不再包含Oracle Java,取而代之的是OpenJDK。Ubuntu 也是如此。
OpenJDK能满足大部分的应用程序运行条件,但PyCharm无法在OpenJDK条件下运行,因此需要安装 Oracle公司的JDK。
首先到JetBrain官网选择对应操作系统的最新版PyCharm下载。如果使用虚拟机,可以先在主机中用 迅雷下载,然后传输到虚拟机中使用。下载后的文件应该是.tar.gz格式,在Ubuntu中解压到自己选择的 路径后即可使用。
运行方式为在命令行中进入应用根目录,执行:
$ ./bin/pycharm.sh
因为我的是新做的虚拟机,命令行提示JDK错误。
安装JDK
在Ubuntu中安装JDK有不同方法,这里提供一种个人觉得最简单的方法,使用apt安装。
因为版权问题,在Ubuntu的APT仓库中不提供Oracle Java下载,执行以下命令查看:
$ apt-cache search oracle-java
搜索不到任何包,再次查看:
$ apt-cache search java7
default-jdk - Standard Java or Java compatible Development Kit
default-jre - Standard Java or Java compatible Runtime
default-jre-headless - Standard Java or Java compatible Runtime (headless)
openjdk-7-jdk - OpenJDK Development Kit (JDK)
openjdk-7-jre - OpenJDK Java runtime, using Hotspot JIT
openjdk-7-jre-headless - OpenJDK Java runtime, using Hotspot JIT (headless)
只可以搜索到OpenJDK的相关包。
因为授权问题,Oracle JDK不包含在官方的PPA列表中,但感谢那些自由软件的贡献者,他们制作了 一个PPA可以从Oracle官方下载最新版JDK到本地,自动安装和升级。注意的是这个PPA是一个alpha版本 ,作者不承诺任何保障,使用者自己承担风险。(PPA:Personal Package Archive)
执行以下命令添加PPA,然后更新APT。
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update
更新完成后再搜索一下JDK包:
$ sudo apt-cache search oracle-java
oracle-jdk7-installer - Oracle JDK7 Installer meta package
oracle-java7-installer - Oracle Java(TM) Development Kit (JDK) 7
oracle-java6-installer - Oracle Java(TM) Development Kit (JDK) 6
oracle-java8-installer - Oracle Java(TM) Development Kit (JDK) 8
oracle-java7-set-default - Set Oracle JDK 7 as default Java
oracle-java6-set-default - Set Oracle JDK 6 as default Java
oracle-java8-set-default - Set Oracle JDK 8 as default Java
搜索到了最新的JDK,我选择了安装Java7,执行:
sudo apt-get install oracle-java7-installer
安装都是自动完成的,中间会弹出提示要求接受Oracle的授权条款,全部同意就可以了。
如果需要设置环境变量可以执行:
sudo apt-get install oracle-java7-set-default
如果安装过oracle-java6-set-default或者oracle-java8-set-default,它们将被自动替换为当前的 设置。
好了,再次运行PyCharm试试吧,执行:
 // CurrentApp.GetAppReceiptAsync();
    
            // 获取此 app 的指定产品的购买记录
            // CurrentApp.GetProductReceiptAsync();
    
            // 获取此 app 的 ListingInformation 信息
            // CurrentApp.LoadListingInformationAsync();
    
            // 获取此 app 的指定关键字的 ListingInformation 信息
            // CurrentApp.LoadListingInformationByKeywordsAsync();
    
            // 获取此 app 的指定产品 Id 的 ListingInformation 信息
            // CurrentApp.LoadListingInformationByProductIdsAsync();
    
            // 通知商城本 app 已将指定产品 Id 的产品交付给了用户,在调用此方法之前,用户不能再次购买此产品
            // CurrentApp.ReportProductFulfillment();
++++++++++
+ User name +
++++++++++
EMBRACE
    
+++++++++++
+  License Key +
+++++++++++
14203-12042010
0000107Iq75C621P7X1SFnpJDivKnX
6zcwYOYaGK3euO3ehd1MiTT"2!Jny8
bff9VcTSJk7sRDLqKRVz1XGKbMqw3G
 PyCharm 3.0.1第一次打开时,会自动询问是否要创建桌面快捷方式和Laucher。
Please enter your password to create a desktop entry
    
[sudo] password for ifantastic: 
    
Press Enter to close this window...
    
    
Please enter your password to create a launcher script in a '/usr/local/bin'
    
[sudo] password for ifantastic: 
    
Press Enter to close this window...
   LicenseInformationDemo();
        }
    
        private void CurrentAppDemo()
        {
            // 由 Windows 商店创建的此 app 的 id
            // CurrentApp.AppId;
    
            // 获取此 app 在 Windows 商店中的 URI 地址
            // CurrentApp.LinkUri;
    
            // 获取当前 app 的 LicenseInformation 对象
            // CurrentApp.LicenseInformation;
    
            // 请求应用程序内购买完整许可证(wp 目前不可用)
            // CurrentApp.RequestAppPurchaseAsync();
    
            // 请求应用程序内购买指定产品的许可证
            // CurrentApp.RequestProductPurchaseAsync
    
            // 获取此 app 的全部购买记录(wp 目前不可用
使用命令
lshw -C network
查看自己的网卡驱动。
下面详细介绍一下替换驱动的步骤。主要参考[1]。
具体步骤
1. 阻止原有驱动的加载
为了使用新驱动,我们需要屏蔽掉原有驱动。编辑/etc/modprobe.d/blacklist
sudo vim /etc/modprobe.d/blacklist
在blacklist文件中加入
# blacklist new iwl3945
blacklist iwl3945
2. 安装ipw3945 microcode
下载ipw3945 microcode,下载地址
解压缩之后,将得到的ipw3945.ucode文件,拷贝到/lib/firmware/2.6.24-19-generic/下。
注意,我这里的内核版本是2.6.24-19,请根据自己的情况,将这个数字替换为当前内核版本号。可 以使用“uname -r”命令查看当前内核版本。
sudo cp ipw3945.ucode /lib/firmware/2.6.24-19-generic/
3. 安装ipw3945 Regulatory daemon
下载ipw3945 Regulatory daemon,下载地址
解压缩后,将x86(如果是64位机器,则是x86_64)下的ipw3945d拷贝到/sbin目录下。
cp x86/ipw3945d /sbin
为了让ipw3945d工作,需要进行一些操作,这些操作已经写在了两个文件中,分别是ipw3945d-start 和ipw3945d-stop中。我们需要将这些文件拷贝到/sbin下,执行如下命令:
sudo cp ipw3945d-{start,stop} /sbin
sudo chmod a+x /sbin/ipw3945d-{start,stop}
更详细的说明,请参考README.ipw3945d
4. 安装ieee80211
一般在内核中都有,特别是ubuntu安装的内核中。所以我就不需要安装。如果你内核中没有 ieee80211,需要安装。请参考ieee80211.sf.net/。一般ubuntu用户都可以跳过这个步骤。
5. 下载ipw3945 1.2.2
下载地址,要下载1.2.2版本。如果链接不能下载,可以在本文的附件中下载。得到ipw3945- 1.2.2.tgz
6. 下载ipw3945补丁
下载地址。这个是一个文本文件,请直接点击右键另存为。得到ipw3945-1.2.2.patch文件。
7. 打补丁
解压缩ipw3945-1.2.2.tgz文件,将ipw3945-1.2.2.patch文件拷贝到ipw3945-1.2.2.tgz解压缩后的 目录下,运行patch命令
patch -p1 < ipw3945-1.2.2.patch
提示输入文件名的时候,输入ipw3945.h
Service是Android的四大组件之一,这里就不再过多的去描述,下面主要实现启动应用时候利用 service后台执行计划任务,退出应用后,关闭service,只存在整个应用的周期中。
首先使用service需要在manifest中的Application 中注册
<service android:name=".WxService" android:enabled="true" android:exported="true" >
 </service>
写一个WxService类,继承于Service,然后实现它的一些方法。
public class WxService extends Service{
    
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    
    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        Timer timer = new Timer();
        timer.schedule(new Work(),0, 30000);
            
    }
    
    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
    }
}
在onCreate()方法中去调度计划,下面介绍一个这个Schedule类。
public void schedule(TimerTask task,
                     long delay,
                     long period)
Schedules the specified task for repeated fixed-delay execution, beginning after the 


specified delay. Subsequent executions take place at approximately regular intervals 


separated by the specified period.
In fixed-delay execution, each execution is scheduled relative to the actual execution time 


of the previous execution. If an execution is delayed for any reason (such as garbage 


collection or other background activity), subsequent executions will be delayed as well. In 


the long run, the frequency of execution will generally be slightly lower than the 


reciprocal of the specified period (assuming the system clock underlying Object.wait(long) 


is accurate).
/  需要设置read和write成员变量,系统才能调用处理读写设备文件动作的函数   
static struct file_operations dev_fops =   
{ .owner = THIS_MODULE, .read = word_count_read, .write = word_count_write };   
       
//  描述设备文件的信息   
static struct miscdevice misc =   
{ .minor = MISC_DYNAMIC_MINOR, .name = DEVICE_NAME, .fops = &dev_fops };   
       
//  初始化Linux驱动   
static int word_count_init(void)   
{   
    int ret;   
    //  建立设备文件   
    ret = misc_register(&misc);   
    //  输出日志信息   
    printk("word_count_init_success\n");   
    return ret;   
}   
       
// 卸载Linux驱动   
static void word_count_exit(void)   
{   
Fixed-delay execution is appropriate for recurring activities that require 


"smoothness." In other words, it is appropriate for activities where it is more 


important to keep the frequency accurate in the short run than in the long run. This 


includes most animation tasks, such as blinking a cursor at regular intervals. It also 


includes tasks wherein regular activity is performed in response to human input, such as 


automatically repeating a character as long as a key is held down.
    
Parameters:
task - task to be scheduled.
delay - delay in milliseconds before task is to be executed.
period - time in milliseconds between successive task executions.
Throws:
IllegalArgumentException - if delay is negative, or delay + System.currentTimeMillis() is 


negative.
IllegalStateException - if task was already scheduled or cancelled, timer was cancelled, or 


timer thread terminated.
说明:该方法会在指定的延时后执行任务,并且在设定的周期定时执行任务。
www.pf025.com/bzdh/pffsqjb/jzb/1604.html?1401005437
www.pf025.com/bzdh/pffsqjb/jzb/1605.html?1401005432
当前位置: 编程入门 > 操作系统 > 手机系统 > 正文
windows phone的回退事件与android的回退事件有什么区别
时间:2014-03-18


public void onBackPressed() {
    finish();
}
如果要做一个页面导航的功能的话,就我而言,认为,windows phone开发比android更加人性化,更 加傻瓜化能够后退键保存相应的数据啊。
不是吗,windows phone 导航更加傻瓜,因为微软的api中直接有一个goback的方法,能够使你回到 相应的后退界面,因为他航到 Back 堆栈中的最新条目。 如果 Back 堆栈中没有任何条目,则此方法将 引发异常;在调用此方法前,始终都要检查 CanGoForward。 这是由于一个页面毡对相应的page进行了 管理,自愿遵守先进后出的原理也很好管理。而android中activity本身也有一个栈对象对相应的 activity进行了管理,自愿后退时候,也能够进行了后退。想法是很好的,但现实是残酷的。你看我们 android程序员必须在onkey事件中对相应的事件进行监听,判断他按下是不是back键来回退按钮。 这里 事件是activity必须要实现传递,来截获这个后退按下的事件。我这里重点要提出一个问题,onKeyDown 事件究竟是一层层实现back事件的.android 就是比.net好啊!开源,看源代码。
需调用activity中的onKeyDown事件,他的源代码如何: 这是我们定义到了activity中的onKeyDown 事件,他的源代码是这样子的:
if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (getApplicationInfo().targetSdkVersion
                    >= Build.VERSION_CODES.ECLAIR) {
                event.startTracking();
            } else {
                onBackPressed();
            }
            return true;
        }
判断其目标版本是不是比本版本大的的话,就调用event.startTracking()方法,对 event.startTracking()方法跟踪,发现他总是相隔了一段时间进行调用。
否则的话,就调用onbackPressed方法。这个方法又是个怎么鸟样。源代码如下:
   public void onBackPressed() {
       finish();
   }
class Work extends TimerTask{
    
        @Override
        public void run() {
            // TODO Auto-generated method stub
        Message message = new Message();
        message.what=1;
        handler.sendMessage(message);
        } 
     }
         
     Handler handler = new Handler()
     {
    
        @Override
        public void handleMessage(Message msg) {
            // TODO Auto-generated method stub
            super.handleMessage(msg);
            if(msg.what==1)
            {
                new Updata().execute();
            }
        }
            
ublic void finish() {
        if (mParent == null) {
            int resultCode;
            Intent resultData;
            synchronized (this) {
                resultCode = mResultCode;
                resultData = mResultData;
            }
            if (Config.LOGV) Log.v(TAG, "Finishing self: token=" + mToken);
            try {
                if (ActivityManagerNative.getDefault()
                    .finishActivity(mToken, resultCode, resultData)) {
                    mFinished = true;
                }
            } catch (RemoteException e) {
                // Empty
            }
        } else {
            mParent.finishFromChild(this)
个url,在代码中通过这样的一个方法实现
public String getXmlFromUrl(String url) {
        String xml = null;
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity,"utf-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
        return xml;
    }   public XMLParser() {
    
    }
    printk("read count:%d", (int) written_count);   
        //  设置数据已读状态   
        read_flag = 'y';   
        return written_count;   
    }   
    //  已经从设备文件读取数据,不能再次读取数据   
    else
    {      
        return 0;   
    }   
}   
//  向设备文件写入数据时调用该函数   
//  file:指向设备文件、buf:保存写入的数据   count:写入数据的字节数  ppos:写入数据的偏移量   
static ssize_t word_count_write(struct file *file, const char __user *buf, size_t count, loff_t *ppos)   
{      
    //  将用户空间的数据复制到内核空间,mem中的数据就是向设备文件写入的数据   
    copy_from_user(mem, buf, count);   
    //  设置数据的未读状态   
    read_flag = 'n';   
    //  保存写入数据的字节数   
    written_count = count;   
    //  向日志输出已写入的字节数   
    printk("written count:%d", (int)count);   


    /**
     * Getting XML from URL making HTTP request
     * @param url string
     * */
    public String getXmlFromUrl(String url) {
        String xml = null;
        try {
            // defaultHttpClient
            DefaultHttpClient httpClient = new DefaultHttpClient();
            HttpPost httpPost = new HttpPost(url);
            HttpResponse httpResponse = httpClient.execute(httpPost);
            HttpEntity httpEntity = httpResponse.getEntity();
            xml = EntityUtils.toString(httpEntity,"utf-8");
#include <linux/module.h>   
#include <linux/init.h>   
#include <linux/kernel.h>   
#include <linux/fs.h>   
#include <linux/miscdevice.h>   
#include <asm/uaccess.h>   
       
#define DEVICE_NAME "wordcount"         //  定义设备文件名   
static unsigned char mem[10000];                //  保存向设备文件写入的数据   
static char read_flag = 'y';                    //  y:已从设备文件读取数据   n:未从设备文件读取数据   
static int written_count = 0;                   // 向设备文件写入数据的字节数   
       
//  从设备文件读取数据时调用该函数   
//  file:指向设备文件、buf:保存可读取的数据   count:可读取的字节数  ppos:读取数据的偏移量   
static ssize_t word_count_read(struct file *file, char __user *buf, size_t count, loff_t *ppos)   
{      
    //  如果还没有读取设备文件中的数据,可以进行读取   
    if(read_flag == 'n')   
    {      
        //  将内核空间的数据复制到用户空间,buf中的数据就是从设备文件中读出的数据   
        copy_to_user(buf, (void*) mem, written_count);  


        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // return XML
    String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
                String cost = ((TextView) view.findViewById(R.id.cost)).getText().toString();
                String description = ((TextView) view.findViewById(R.id.desciption)).getText().toString();
                    www.lawceo.net/zlzx/by/953.html?1401005203
1.package com.idea.org;
02.
03.import java.util.ArrayList;
04.import java.util.HashMap;
05.
06.import android.app.Activity;
07.import android.os.Bundle;
08.import android.view.View;
09.import android.widget.AdapterView;
10.import android.widget.AdapterView.OnItemClickListener;
11.import android.widget.ListView;
12.import android.widget.SimpleAdapter;
13.import android.widget.Toast;
14.
15.public class Android_ListView extends Activity {
16.    /** Called when the activity is first created. */
17.    @Overrid
                // Starting new intent
                Intent in = new Intent(getApplicationContext(), SingleMenuItemActivity.class);
                in.putExtra(KEY_NAME, name);
                in.putExtra(KEY_COST, cost);
                in.putExtra(KEY_DESC, description);
                startActivity(in);
    
            }
        });
    }
}public class SingleMenuItemActivity  extends Activity {
        
    // XML node keys
    static final String KEY_NAME = "name";
    static final String KEY_COST = "cost";
    static final String KEY_DESC = "description";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.single_list_item);
    public void onCreate(Bundle savedInstanceState) {
19.        super.onCreate(savedInstanceState);
20.        setContentView(R.layout.main);
21.        ArrayList<HashMap<String,String>>list =new ArrayList<HashMap<String,String>>();
22.        HashMap<String,String> map1=new HashMap<String,String>();
23.        HashMap<String,String> map2=new HashMap<String,String>();
24.        HashMap<String,String> map3=new HashMap<String,String>();
25.        ListView listView=(ListView)findViewById(R.id.listView);
26.        map1.put("userId", "100001");
27.        map1.put("userName", "用户一");
28.        list.add(map1);
29.        map2.put("userId", "100002");
30.        map2.put("userName", "用户二");
31.        list.add(map2);
32.        map3.put("userId", "100003");
33.        map3.put("userName", "用户三");
34.        list.add(map3);
35.        //定义一个SimpleAdapter,每一个行有两个TextView,分别显示userId和userName
36.        SimpleAdapter simpleAdapter=new SimpleAdapter(this,list,R.layout.user,
37.                new String[]{"userId","userName"},new int[]{R.id.userId,R.id.userName});
38.        //为ListView添加适配器
39.        listView.setAdapter(simpleAdapter);//设置listView背后的数据为simpleAdapter。
40.        /*为listView添加单击监听器,需要import android.widget.AdapterVi
www.pf025.com/bzdh/pffsqjb/jzb/1606.html?1401005430
www.pf025.com/bzdh/pffsqjb/jzb/1607.html?1401005426


        // getting intent data
        Intent in = getIntent();
            
        // Get XML values from previous intent
        String name = in.getStringExtra(KEY_NAME);
        String cost = in.getStringExtra(KEY_COST);
        String description = in.getStringExtra(KEY_DESC);
            
        // Displaying all values on the screen
        TextView lblName = (TextView) findViewById(R.id.name_label);
        TextView lblCost = (TextView) findViewById(R.id.cost_label);
        TextView lblDesc = (TextView) findViewById(R.id.description_label);
            
        lblName.setText(name);
01.<?xml version="1.0" encoding="utf-8"?>
02.<LinearLayout xmlns:android="schemas.android.com/apk/res/android"
03.    android:orientation="vertical"
04.    android:layout_width="fill_parent"
05.    android:layout_height="wrap_content"
06.    >
07.    <!--添加一个ListView控件  -->
08.    <ListView
09.        android:id="@+id/listView"
10.        android:layout_width="fill_parent"
11.        android:layout_height="wrap_content"
12.        />
13.</LinearLayout>
      listView.setOnItemClickListener(new OnItemClickListener() {
44.
45.            @Override
46.            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
47.              long arg3) {
48.             ListView listView=(ListView)arg0;
49.             Toast.makeText(Android_ListView.this, listView.getItemAtPosition(arg2).toString(),
50.                     Toast.LENGTH_SHORT).show();
51.            }
52.           });
53.    }   
54.}
        lblCost.setText(cost);
        lblDesc.setText(description);
    }
}01.<?xml version="1.0" encoding="utf-8"?>
02.<LinearLayout xmlns:android="schemas.android.com/apk/res/android"
03.    android:orientation="horizontal"
04.    android:layout_width="fill_parent"
05.    android:layout_height="fill_parent"
06.    android:paddingRight="10dip"
07.    android:paddingLeft="10dip"
08.    android:paddingTop="1dip"
09.    android:paddingBottom="1dip"
8.0 其它: 锁屏信息和锁屏背景, 电池状态, 多分辨率, 商店, 内置协议, 快速恢复
介绍
与众不同 windows phone 8.0 之 其它
锁屏信息和锁屏背景
电池状态
多分辨率应用
与 Windows Phone 商店相关的操作
系统的内置协议
快速恢复应用
App.xaml.cs 的说明
manifest 的说明
示例
1、演示如何发送信息到锁屏,以及如何修改锁屏背景
Others/LockScreen.xaml
<phone:PhoneApplicationPage
    x:Class="Demo.Others.LockScreen"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">
    
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <StackPanel>
                
            <TextBlock Name="lblMsg" TextWrapping="Wrap" />
                
            <Button Name="btnGotoLockScreen" Content="跳转到锁屏设置界面" Click="btnGotoLockScreen_Click" />
    
            <Button Name="btnSendMessageToLockScreen" Content="发送信息到锁屏" Click="btnSendMessageToLockScreen_Click" />
    
            <Button Name="btnLockScreenBackground" Content="修改锁屏背景" Click="btnLockScreenBackground_Click" />
    
        </StackPanel>
    </Grid>
    
</phone:PhoneApplicationPage>
/*
 * 演示与 Windows Phone 商店相关的操作
 * 
 * 注:
 * 应用内购买测试请参考:http://msdn.microsoft.com/zh-cn/library/windowsphone/develop/jj681689
 */
    
using Microsoft.Phone.Controls;
using Windows.ApplicationModel.Store;
    
namespace Demo.Others
{
    public partial class StoreDemo : PhoneApplicationPage
    {
        public StoreDemo()
        {
            InitializeComponent();
    
            CurrentAppDemo();
/*
 * 演示如何发送信息到锁屏,以及如何修改锁屏背景
 * 
 * 
 * 注:在 manifest 中需要增加的内容和说明如下
 * 1、搜索并修改“<DeviceLockImageURI />”节点的内容如下:
 * <!--锁屏图标:38 * 38 像素,仅支持白色和透明-->
 * <DeviceLockImageURI IsRelative="true" IsResource="false">Assets\LockScreen.png</DeviceLockImageURI>
 * 
 * 2、在 <Extensions /> 节点中增加内容如下:
 * <!--支持锁屏上显示图标和数字-->
 * <Extension TaskID="_default" ExtensionName="LockScreen_Notification_IconCount" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" />
 * <!--支持锁屏上显示文本-->
 * <Extension TaskID="_default" ExtensionName="LockScreen_Notification_TextField" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" />
 * <!--支持锁屏背景的修改-->
 * <Extension TaskID="_default" ExtensionName="LockScreen_Background" ConsumerID="{111DFF24-AA15-4A96-8006-2BFF8122084F}" />
 */
    
using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using Windows.System;
using Windows.Phone.System.UserProfile;
    
namespace Demo.Others
{
    public partial class LockScreen : PhoneApplicationPage
    {
        public LockScreen()
        {
            InitializeComponent();
        }
    
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 在锁屏设置界面,如果将本 app 设置为背景提供程序,则锁屏界面上会有一个名为“打开应用”的按钮,点击后会通过 /MainPage.xaml?WallpaperSettings=1 启动本 app
            // 相关的 UriMapper 参见 MyUriMapper.cs
    
            IDictionary<string, string> queryStrings = this.NavigationContext.QueryString;
            if (queryStrings.ContainsKey("WallpaperSettings"))
                lblMsg.Text = "在锁屏界面启动了本 app,启动的 url 是:" + e.Uri.ToString();
    
            base.OnNavigatedTo(e);
        }
    
        // 跳转到锁屏设置界面
        private async void btnGotoLockScreen_Click(object sender, RoutedEventArgs e)
        {
            bool success = await Launcher.LaunchUriAsync(new Uri("ms-settings-lock:"));
        }
    
        // 发送信息到锁屏
        private void btnSendMessageToLockScreen_Click(object sender, RoutedEventArgs e)
        {
            // 锁屏信息来自 tile(StandardTileData, FlipTile, IconicTile, CycleTile 均可)
            ShellTile shellTile = ShellTile.ActiveTiles.First();
            if (shellTile != null)
            {
                StandardTileData tile = new StandardTileData();
                tile.BackContent = "发送信息到锁屏"; // 需要在锁屏上显示的文本内容(需要在锁屏界面设置本 app 为显示详细状态)
                tile.Count = 10; // 需要在锁屏上显示的数字内容,图标来自 <DeviceLockImageURI /> 节点的设置(需要在锁屏界面设置本 app 为显示即时状态)
    
                shellTile.Update(tile);
            }
        }
    
        // 修改锁屏背景
        private async void btnLockScreenBackground_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                /*
                 * 注:
                 * 在项目根目录下增加 DefaultLockScreen.jpg 文件,用于当 app 成为锁屏背景的实际提供程序却没有设置锁屏背景时,作为锁屏背景的默认图片
                 * 比如用户在锁屏设置页面选择了本 app 作为锁屏背景的实际提供程序,此时本 app 无法设置锁屏背景,那么锁屏背景图就会被设置为项目根目录下的 DefaultLockScreen.jpg 文件
                 *


                // 判断本 app 是否是锁屏背景的实际提供程序
                bool isProvider = LockScreenManager.IsProvidedByCurrentApplication;
                if (!isProvider)
                {
                    // 请求成为锁屏背景的实际提供程序(会弹出一个对话框)
                    LockScreenRequestResult result = await LockScreenManager.RequestAccessAsync();
    
                    // LockScreenRequestResult.Granted - 用户已允许;LockScreenRequestResult.Denied - 用户已拒绝
                    isProvider = result == LockScreenRequestResult.Granted;
                }
    
                if (isProvider)
                {
                    // 图片地址支持“ms-appx:///”和“ms-appdata:///Local/”,文件名必须与当前锁屏背景的文件名不同
                    Uri uri = new Uri("ms-appx:///Assets/AppTile.png", UriKind.Absolute);
    
                    // 设置当前锁屏的背景图
                    Windows.Phone.System.UserProfile.LockScreen.SetImageUri(uri);
    
                    // 获取当前锁屏的背景图的 uri
                    Uri currentUri = Windows.Phone.System.UserProfile.LockScreen.GetImageUri();
                    lblMsg.Text = "当前锁屏的背景图的 url: " + currentUri.ToString();
                }
                else
                {
                    lblMsg.Text = "用户不允许此 app 成为锁屏背景的实际提供程序";
                }
            }
            catch (Exception ex)
            {
                lblMsg.Text = ex.ToString();
            }
        }
    }
}
/*
 * 演示如何获取电池的状态信息
 */
    
using System;
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
using Windows.Phone.Devices.Power;
using Microsoft.Phone.Info;
    
namespace Demo.Others
{
    public partial class BatteryDemo : PhoneApplicationPage
    {
        private Battery _battery;
    
        public BatteryDemo()
        {
            InitializeComponent();
        }
    
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 获取电话的默认 Battery 对象
_battery = Battery.GetDefault();
    
            // 获取电池在完全用完之前的所剩时间
            TimeSpan remainingTime = _battery.RemainingDischargeTime;
    
            // 获取剩余电量的百分比
            int remainingChargePercent = _battery.RemainingChargePercent;
    
            // 判断当前是电池供电还是外部电源供电
            lblMsg.Text = "PowerSource: " + DeviceStatus.PowerSource.ToString();
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "剩余时间:" + string.Format("{0}{1}{2}{3}{4}{5}", remainingTime.Days, "天", remainingTime.Hours, "小时", remainingTime.Minutes, "分");
            lblMsg.Text += Environment.NewLine;
            lblMsg.Text += "电量百分比:" + remainingChargePercent.ToString() + "%";
    
            // 剩余电量的百分比发生变化时所触发的事件
            _battery.RemainingChargePercentChanged += _battery_RemainingChargePercentChanged;
    
            base.OnNavigatedTo(e);
        }
    
        protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
        {
            _battery.RemainingChargePercentChanged -= _battery_RemainingChargePercentChanged;
    
            base.OnNavigatingFrom(e);
        }
    
        void _battery_RemainingChargePercentChanged(object sender, object e)
        {
            // 剩余电量的百分比发生了变化
        }
<phone:PhoneApplicationPage
    x:Class="Demo.Others.MultiResolution"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone"
    xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    FontFamily="{StaticResource PhoneFontFamilyNormal}"
    FontSize="{StaticResource PhoneFontSizeNormal}"
    Foreground="{StaticResource PhoneForegroundBrush}"
    SupportedOrientations="Portrait" Orientation="Portrait"
    mc:Ignorable="d"
    shell:SystemTray.IsVisible="True">
    
    <Grid x:Name="LayoutRoot" Background="Transparent">
        <StackPanel>
                
            <TextBlock TextWrapping="Wrap">
                <Run>1、WVGA - 480 x 800; WXGA - 768 x 1280; 720p - 720 x 1280</Run>
                <LineBreak />
<Run>2、大多数情况下,建议使用 WXGA 资产,他们会在其他分辨率下自动缩放且显示良好</Run>
                <LineBreak />
                <Run>3、如果需要不同分辨率使用不同资产,则必须写代码,参见 code-behind 中判断当前分辨率的代码</Run>
                <LineBreak />
                <Run>4、适应不同分辨率的启动屏幕,需要在项目的根目录下放置三个启动屏幕文件:SplashScreenImage.Screen-WVGA.jpg, SplashScreenImage.Screen-WXGA.jpg, plashScreenImage.Screen-720p.jpg</Run>
                <LineBreak />
                <Run>5、如果只想用一个启动屏幕文件的话,则在项目的根目录下放置一个分辨率为 768 x 1280 的名为 SplashScreenImage.jpg 的文件即可(不同分辨率会自动缩放)


</Run>
            </TextBlock>
    
            <TextBlock Name="lblMsg" TextWrapping="Wrap" Margin="0 10 0 0" />
                
        </StackPanel>
    </Grid>
    
</phone:PhoneApplicationPage>
/*
 * 演示如何获取当前分辨率
 */
    
using System.Windows.Navigation;
using Microsoft.Phone.Controls;
    
namespace Demo.Others
{
    public partial class MultiResolution : PhoneApplicationPage
    {
        public MultiResolution()
        {
            InitializeComponent();
        }
    
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 获取当前的分辨率
            lblMsg.Text = "Resolution: " + ResolutionHelper.CurrentResolution.ToString();
                
            base.OnNavigatedTo(e);
        }
    }
    
    public static class ResolutionHelper
    {
        /// <summary>
        /// 480 x 800
        /// </summary>
        private static bool IsWvga
        {
            get
            {
                return App.Current.Host.Content.ScaleFactor == 100;
            }
        }
    
        /// <summary>
        /// 768 x 1280
        /// </summary>
        private static bool IsWxga
        {
            get
            {
                return App.Current.Host.Content.ScaleFactor == 160;
            }
        }
    
        /// <summary>
        /// 720 x 1280
        /// </summary>
        private static bool Is720p
        {
            get
            {
                return App.Current.Host.Content.ScaleFactor == 150;
            }
        }
    
        public static Resolution CurrentResolution


10.    >
11.    <!--ListView的每一项都有两个TextView,分别显示userId和userName  -->
12.    <TextView
    android:layout_width="fill_parent"
15.        android:layout_height="wrap_content"
16.        android:textSize="20pt"
17.        android:layout_weight="1"
18.        />
19.    <TextView
20.        android:id="@+id/userName"
21.        android:layout_width="fill_parent"
22.        android:layout_height="wrap_content"
23.        android:textSize="20pt"
24.        android:layout_weight="1"
25.        />
26.</LinearLayout>
           if (IsWvga) 
                    return Resolution.WVGA;
                else if (IsWxga) 
                    return Resolution.WXGA;
                else if (Is720p) 
                    return Resolution.HD720p;
                else
                    return Resolution.Unknown;
            }
0 0