iOS开发phonegap之消息推送

一、安装插件:

1、phonegaplocal plugin add https://github.com/phonegap-build/PushPlugin.git

2、phonegap plugin add cordova-plugin-device

3、phonegap plugin add cordova-plugin-media

二、在js文件中调用

var pushNotification;

var app = {
// Application Constructor

initialize: function() {
this.bindEvents();

},

// Bind Event Listeners

//

// Bind any events that are required on startup. Common events are:

// ‘load’, ‘deviceready’, ‘offline’, and ‘online’.

bindEvents: function() {
document.addEventListener(‘deviceready’, this.onDeviceReady, false);

 

},

// deviceready Event Handler

//

// The scope of ‘this’ is the event. In order to call the ‘receivedEvent’

// function, we must explicitly call ‘app.receivedEvent(…);’

 

onDeviceReady: function() {
app.receivedEvent(‘deviceready’);

app.registerN();

 

},

// Update DOM on a Received Event

receivedEvent: function(id) {

var parentElement = document.getElementById(id);

var listeningElement = parentElement.querySelector(‘.listening’);

var receivedElement = parentElement.querySelector(‘.received’);

listeningElement.setAttribute(‘style’, ‘display:none;’);

receivedElement.setAttribute(‘style’, ‘display:block;’);

console.log(‘Received Event: ‘ + id);

},

registerN: function() {

pushNotification = window.plugins.pushNotification;

 

pushNotification.register(

this.tokenHandler,

this.errorHandler,

{
“badge”:”true”,

“sound”:”true”,

“alert”:”true”,

“ecb”:”onNotificationAPN”

});

},

onNotificationAPN: function(event) {
if ( event.alert )

{
navigator.notification.alert(event.alert);

}

 

if ( event.sound )

{
var snd = new Media(event.sound);

snd.play();

}

 

if ( event.badge )

{
pushNotification.setApplicationIconBadgeNumber(successHandler, errorHandler, event.badge);

}

},

tokenHandler: function(result) {
alert (‘success’);

alert(‘device token = ‘ + result);

},

errorHandler: function(error) {
alert(‘register erro’);

alert(‘error = ‘ + error);

}

};

iphone屏幕镜像连电视_手机如何连接电视机?

一般情况下,手机想要直接的连接到电视机上是无法实现的,但是,我们如果只是想手机上的视频投影到电视机上播放还是没有问题的。我们可以通过DLNA技术来实现这个功能。

先解释一下DLNA

2b32ed1d424805d3fc88df492f78d7b0.pngDLNA其实严格来说并不是一种技术,而是一种解决方案,全程叫“DIGITAL LIVING NETWORK ALLIANCE(数字生活网络联盟)”,是由索尼、英特尔、微软等公司发起成立的。为的就是实现PC电脑、移动设备和消费电器在无线或者有线网络中的互联互通。

不过2017年1月15日,DLNA组织已经正式解散了,不过这个技术依旧被使用着。

怎么来实现投屏呢?

首先,我们需要一个联网的路由器(*好是无线),一部智能手机(iPhone和安卓都行),一台电视机。如果电视是互联网电视,能够直接连上无线网络,那么就不需要更多设备了,如果电视没有这个功能,那么你还需要一个小小的投屏设备。

我们先假设电视是互联网电视

对于iPhone手机来说,那就很简单了,先保证手机连上了你家里的wifi,然后保证你的电视机是连上wifi的。

然后打开手机,向上滑动出功能菜单,其中就有一个叫做屏幕镜像的功能。

8e8b60c1b3aca5cad8de4bba3134c12b.png7a92b788291950ff5b9750c12e76f643.png

点击以后,就能够看到你已经联网的电视机了。这是,点击选中,OK,一切就完成了,是不是很简单。

如果是安卓手机呢?华为的手机,很多是自带了投屏功能,和iPhone一样,可以直接投屏。如果是没有自带这个功能的安卓手机,你就需要安装一个投屏APP,类似的投屏APP非常多,到应用市场里面找一个就OK了。

d5f2b5943d6ba00a96b728a88c3bd088.png

使用的话,也就是打开APP,然后选择投屏,再选择设备就OK了,也非常简单。

当然,如果你是在用爱艺奇,youku等视频APP看视频,想要投屏到电视上,一般在播放视频的时候,手机屏幕的右上角会有类似的功能按钮,就可以实现投屏了。

77604225779c7f2a05136de449bb629b.png

如果我的电视不是互联网电视,不能联网怎么办呢?

那你就需要借助外力了。一般来说,小米盒子这种互联网机顶盒都是带有投屏功能的,如果你有,可以通过投屏到这些设备上,然后在电视上播放。

如果没有机顶盒,那么就只有买一个小设备了。选择设备的时候,可以根据自己的使用目的来购买。例如:你经常看爱奇艺的视频,那么你就可以选一个电视果。

fe4a2bc491ec9730acd94914981c32d4.png

非常小的个头,还送爱奇艺会员,并且,在投屏爱奇艺的视频时,其实并不是投屏,而是通过电视果直接播放。

是不是投屏有什么区别呢?

如果是投屏,手机关闭或者断网,那么电视也就不会继续播放了,因为电视是通过连接手机来播放的。但是电视果就好像一个机顶盒,如果是播放爱奇艺的视频,其实就不需要你手机作为信号源了,电视果可以直连爱奇艺视频网站进行播放。手机关机都不会受到影响。

当然,还有什么天猫魔盒、小米盒子等等很多选择。

前期回顾:

1:都说安卓手机用一两年就卡到不行,但知道这3招,同样可以用很久

2:iPhone深深隐藏的5个秘密开关,苹果官方都求着你去开,不开血亏

3:App Store里5个热门应用,款款都是黑科技,让你的苹果好用爆表!

ios屏蔽描述文件官方下载入口_iOS屏蔽更新描述文件失效解决办法:用这个方法屏蔽iOS13更新…

相信不少苹果设备的用户都经历过这样一个场景,只是睡一觉的时间,自己手中的iPhone或者iPad自动升级到了*新iOS版本。众所周知,由于iOS系统的机制,当设备开启“自动更新”,苹果设备会在适合的网络环境下自动下载*新的系统,且在充电状态+接入WI-FI的时候,自动升级新版iOS系统。

d9e9dc4dfd68cb4e5d5799b242a715de.png

对部分用户来说,他们希望能够停留在较低版本,而iPhone的升级提醒,却让人感到心烦,一旦误操作,就无法退回到已关闭验证的较早版本。在过去,我们都是利用苹果tvOS的描述文件来屏蔽iOS升级,在iOS设备上安装tvOS描述文件就可以让系统误以为检查的是tvOS的OTA更新,因此在iOS系统上就收不到更新。随着屏蔽系统更新的tvOS 12描述文件在今年1月底失效后,至今没有可用的屏蔽升级描述文件。为了避免系统意外升级,我们可以先通过其它的“曲线救国”方式来屏蔽升级。

  • 方法:关闭“设置“的网络权限

原理:因为系统升级需要联网下载新固件,关闭“设置”的网络权限,无法接入网络,所以也就不会自动下载*新固件,避免了意外升级。

使用方法:

1. 先打开“设置-iPhone存储空间”检查新固件是否已经被下载,如果系统固件已经下载,先将其删除;

2. 前往“设置-无线局域网-使用WLAN与蜂窝移动网的应用”,在列表中找到“设置”,将其权限关闭。

3. 关闭“设置”的网络权限后,我们就不用再担心新固件自动被下载到设备上。

7dcd342491b16fa1edc7861d2b6a6185.png

优点:简单,易操作,无需安装额外的配置文件或者App。

缺点:

1. 可能影响到其它需要联网才能设置的功能。

解决办法:可在需要使用“设置”联网时,重新打开网络权限,使用完成后重复上述步骤即可。

2. “设置”图标上的提醒数字“1”不会消失。

iOS开发中怎么样使用激光推送

1.注册激光推送的账号 —-> 创建应用

2.上传推送测试和发布的p12文件  注意密码的填写

3.下载sdk并拖进工程里

4.在build setting 搜索search   把路径改一下%title插图%num

%title插图%num

然后导入必须的库

CFNetwork.framework
CoreFoundation.framework
CoreTelephony.framework
SystemConfiguration.framework
CoreGraphics.framework
Foundation.framework
UIKit.framework
Security.framework
Xcode7需要的是libz.tbd;Xcode7以下版本是libz.dylib

配置plist文件

实现如下代码

AppDelegate.m
// 远程推送
//
// Created by  on 16/3/28.
// Copyright © 2016年 sjb. All rights reserved.
//
#import “AppDelegate.h”
#import “JPUSHService.h”

#define kJpushKey @”c171bc25d7754e085b48861b”
#define kMasterSecret (7f37465534cece94ac94c277)
static NSString *appKey = @”AppKey copied from JPush Portal application”;

static NSString *channel = @”Publish channel”;
static BOOL isProduction = FALSE;

@interface AppDelegate ()

@end

@implementation AppDelegate

– (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:UIUserNotificationTypeBadge|UIUserNotificationTypeSound|UIUserNotificationTypeAlert categories:nil];
[[UIApplication sharedApplication] registerUserNotificationSettings:settings];
}

if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
[JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
}else{
[JPUSHService registerForRemoteNotificationTypes:(UIUserNotificationTypeBadge | UIUserNotificationTypeSound | UIUserNotificationTypeAlert) categories:nil];
}

[JPUSHService setupWithOption:launchOptions appKey:kJpushKey
channel:channel apsForProduction:isProduction];

return YES;
}

– (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {

// Required
[JPUSHService registerDeviceToken:deviceToken];
}

– (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {

// Required,For systems with less than or equal to iOS6
[JPUSHService handleRemoteNotification:userInfo];
}

– (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {

// IOS 7 Support Required
[JPUSHService handleRemoteNotification:userInfo];
completionHandler(UIBackgroundFetchResultNewData);
}

– (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {

//Optional
NSLog(@”did Fail To Register For Remote Notifications With Error: %@”, error);
}

phonegap+激光推送做ios的消息推送

*光推送插件地址:https://github.com/jpush/jpush-phonegap-plugin

1.cordova,git 环境

2.过程遇到的错误

将这个包再次导入

%title插图%num

%title插图%num

修改一处地方

%title插图%num

字典里appkey的修改

%title插图%num

3.

登陆并加标注
var onDeviceReady = function(){
console.log(“JPushPlugin:Device ready!”);
initiateUI();
}
var initiateUI = function(){
try{
window.plugins.jPushPlugin.init();
if(device.platform != “Android”){
window.plugins.jPushPlugin.setBadge(0);//服务器角标清0
window.plugins.jPushPlugin.setDebugModeFromIos();
window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);//角标
}else{
window.plugins.jPushPlugin.setDebugMode(true);
}
var alias=userName;
window.plugins.jPushPlugin.setAlias(alias);
}catch(exception){
console.log(exception);
}

}
document.addEventListener(“deviceready”, onDeviceReady, false);//初始化设备

4.公用函数的加载

//检索是否session过期

function checkSession(){
try{
$.post(conn+”ds=DS_EASYJOINT_MOBIL_GROUP_LIST”,{},function(data){
var nowHref=window.location.href;
if((data.indexOf(“html”)>-1) && nowHref.indexOf(“login.html”)==-1){
window.location.href=”login.html”;
}
});
}catch(e){
console.log(“checkSession:”+e);
}
}

//推送函数
//window.plugins.jPushPlugin.resumePush(callback)
//var onCallback = function(data) {
// if(data>0){
// //开启
// }else{
// //关闭
// }
//}
function pushMessage(){
var openNotification = function(event){
try{
window.plugins.jPushPlugin.setBadge(0);//服务器角标清0
window.plugins.jPushPlugin.setDebugModeFromIos();
window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);
checkSession();//过期
}
catch(exception){
console.log(“jpush.openNotification”+exception);
}
}

function onDeviceReadyPush() {
document.addEventListener(“resume”, onResume, false);
window.plugins.jPushPlugin.init();
}
// 处理resume事件
function onResume() {
try{
window.plugins.jPushPlugin.setBadge(0);//服务器角标清0
window.plugins.jPushPlugin.setDebugModeFromIos();
window.plugins.jPushPlugin.setApplicationIconBadgeNumber(0);//角标
checkSession();//过期
}
catch(exception){
console.log(exception);
}
}
document.addEventListener(“deviceready”, onDeviceReadyPush, false);
document.addEventListener(“jpush.openNotification”, openNotification, false);
}

$(function(){
pushMessage();//推送
});

 

ntp服务安装

ntp服务安装
1.查看是否存在对应服务
rpm -qa | grep ntp

2.如果不存在安装对应服务
yum install ntp ntpdate -y

3.查看ntp运行状态
systemctl status ntpd

4.修改配置文件
vim /etc/ntp.conf

注释

#拒* IPv4 的用户与IPv6的用户

#restrict default kod nomodify notrap nopeer noquery
#restrict -6 default kod nomodify notrap nopeer noquery

#放行本机来源

#restrict 127.0.0.1
#restrict -6 ::1

#默认ntp服务器

#server 0.centos.pool.ntp.org iburst

#server 1.centos.pool.ntp.org iburst

#server 2.centos.pool.ntp.org iburst

#server 3.centos.pool.ntp.org iburst

添加

#默认只能通过ntp进行校时

restrict default nomodify notrap nopeer noquery

#ntp服务器地址

server 172.16.1.1

fudge 172.16.1.1 stratum 0

5.重启服务并查看状态
systemctl restart ntpd 或 service ntpd restart

6.查看是否同步
ntpq -p

7.如果失败查看是否开启端口(ntp协议默认端口123)
firewall-cmd –permanent –add-port=123/udp

firewall-cmd –reload

8.设置开机自启
**chkconfig –list ntpd 查看是否开机自启 **

systemctl enable ntpd 或 service ntpd enable
————————————————
版权声明:本文为CSDN博主「Farmermark993」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/zalu9810/article/details/112358788

Groovy基本语法(三)

Groovy中的循环
可以说,Groovy把Java循环结构折腾的面目全非,似乎主流脚本语音能用到的循环方式Groovy都给加了进去,实际上不同的循环语法和功能差异很小,这类玩意儿多了意义并不明显,例如我就比较喜欢for循环而不太爱用while循环,但并不是说while循环没有用处,虽然for循环完全可以涵盖while循环的所有功能。
Groovy的开发者目标很明确,让Groovy的语法甜的腻死你们!

package plswg.edu.groovy.basic

// groovy中可以使用传统的while循环或for循环

n = 0
while (n < 10) {
print n + ” ”
n++
}
println “”

for (i = 0; i < 10; i++) {
print i + ” ”
}
println “\r\n”

// groovy引入新风格的for循环

for (i in 0 .. 9) { // (i in 0 .. 9)表示循环从i=0开始,到i<=9时结束
print i + ” ”
}
println “”

// 利用数值类型可以也可以进行循环

// 利用整数的upto方法进行循环
i = 0
i.upto(9) { // 整数的upto方法可以启动一个循环, 循环体在一个闭包内执行
print it + ” ” // 在闭包内部,it关键字表示循环过程的整数值
}
println “; at the end of loop, the var i is ” + i // 循环结束后i的值仍是0,不会增加到9

// upto方法可以用在常量上
10.upto(19) { // 10.upto(20)表示从10开始循环到19结束
print it + ” ”
}
println “”

// upto方法中的整数是循环的起始点,time方法可以将整数作为循环的终止点
10.times { // 10.times表示从0开始循环到9结束
print it + ” ”
}
println “”

// step方法可以设置循环的步长值
0.step(11, 2) { // 0.step(11, 2)表示从0循环到11,每次循环值增加2
print it + ” ”
}
println “\r\n”

// 例子,利用groovy新语法输出一个99乘法表
// 方法1
for (i in 1 .. 9) {
for (j in 1 .. 9) {
z = i * j
print ((z < 10 ? ” ” + z : z) + ” “)
}
println “”
}
// 方法2
1.upto(9) {
x = it
1.upto(9) {
z = x * it
print ((z < 10 ? ” ” + z : z) + ” “)
}
println “”
}
// 方法3
9.times {
x = it + 1
9.times {
z = x * (it + 1)
print ((z < 10 ? ” ” + z : z) + ” “)
}
println “”
}
可以看到,Groovy对Java循环结构作了如下的修整:
对于for循环:除了传统三表达式的for循环和用于迭代的for each循环外,Groovy允许for循环遍历一个范围(Range),例如 for (i in 1..10),表示循环10次,i在1至10之间取值;
对于整数,Groovy增加了如下几个方法来进行循环:
upto:n.upto(m) 函数,表示循环 m- n 次,并且会有一个循环变量it,从n开始,每次循环增加1,直到m。循环体写在upto方法之后大括号中,表示一个闭包,在闭包中,it作为循环变量,值从a增长到n;
times:n.times 函数,表示循环n次,循环变量it从0开始到n结束。
step:n.step(x, y) 函数,表示循环变量从n开始到x结束,每次循环后循环变量增加y,所以整个循环次数为 (x – n) / y 次;
6、字符串

Groovy对字符串增加了一些新的特性,让字符串操作更加简单了:

package plswg.edu.groovy.basic

// groovy中对字符串的使用做了大量的简化

// 获取字符串中的字符
s = “Hello”
println s[0] // 输出’H’

// 遍历字符串中的所有字符
s.each {
print it + “, ” // 遍历字符串中的所有字符
}
println “”

// 截取字符串
s1 = s[1..3] // 截取s字符串标号从1到3的3个字符,组成新的字符串赋予s1
// 该语法是String类的substring方法的简化
println s1

// 模板式字符串

n = 100
s1 = “The number n is ${n}” // ${n}表示将变量n的值放在字符串该位置
println s1

// 带格式的长字符串
// “””和”””之间的所有字符都会被算做字符串内容,包括// /*以及回车,制表符等
s = “””
大家好
欢迎大家学习Groovy编程
Groovy is a better Java
“””
println s

// groovy中单引号的作用

// 在不定义类型时,单引号也表示字符串
c1 = ‘A’
println c1.getClass().getName()

// 要明确的定义字符类型,需要给变量增加定义
char c2 = ‘A’
println c2.getClass().getName()

// 取消转义字符
s = ‘c:\\windows\\system’
println s
s = /c:\windows\system/ // 利用/字符串/定义的字符串
println s

// 字符串运算
s = “hello”
s = s + ” world” // +运算符用于连接字符串
println s

s -= “world” // -可以从字符串中去掉一部分
println s

s = s * 2 // *可以让字符串重复n次
println s

// 字符串比较
s1 = “Abc”
s2 = “abc”

println s1 == s2 ? “Same” : “Different” // 执行s1.equals(s2)
println s1 != s2 ? “Different” : “Same” // 执行!s1.equals(s2)
println s1 > s2 ? “Great” : “Less” // 执行s1.compareTo(s2) > 0
println s1 < s2 ? “Less” : “Great” // 执行s1.compareTo(s2) < 0
// s1 >= s2, s1 <= s2
println s1 <=> s2 == 1 ? “Same” : “Different” // 执行s1.compareTo(s2)
Groovy增加了对字符串的如下操作:
集合操作,Groovy将字符串看为字符的集合,可以通过 [n] 运算符直接访问字符串内的字符,也可以通过each循环遍历字符串的每一个字符;
截取子字符串的substring方法被简化为使用数值范围来进行截取,”hello”[1..3]表示截取字符串”hello”从下标为1到下标为3的部分,结果为 “ell”;
Groovy增加了一个新的字符串类型 GString,这种字符串可以进行格式化,在GString字符串中使用 ${变量},可以将该变量的值放入字符串的相应位置;
带格式的字符串,使用 “””字符串内容”””(连续的三个引号),这种字符串中可以包含直接输入的回车,TAB键,//或/*等字符,而这些在Java原本的字符串里,都必须通过转义字符来表示,例如只能用\n表示回车;
单引号问题,和Javascript和PHP类似,Groovy中无论是单引号还是双引号都表示是字符串类型,例如 ‘a’ 和”a”都是字符串类型,所以如果要确定存储一个 char 类型变量,就必须使用 char 类型定义强类型变量;实际上Groovy认为char类型并不是必须的,大部分时候字符串类型更方便一些;
用 / 包围的字符串,即 /字符串内容/,可以避免在字符串中使用转义字符,但 \n 字符不包含在内;
Java中对字符串的运算只有+运算,在Groovy中,字符串还可以使用 -运算 和 *运算,减法运算可以从一个字符串中删除一部分,乘法运算可以将一个字符串重复n次;
Groovy还为字符串加入了所有关系运算符,包括 ==, !=, >, <, >=, <=,这要归功于Groovy允许运算符重载,对于 == 和 !=,将调用String类的equals 方法,对于 >, >=, <, <=,将调用String类的compareTo方法;Groovy还增加了一个特殊的运算符<=>,这个运算符也会调用 compareTo 方法,返回 compareTo 方法的返回值;
Groovy对字符串增强了很多,使其更加方便使用,也更加符合主流动态语言的语法设定,当然这里面很多内容并不是简单的针对字符串的,例如Groovy的闭包,运算符重载等特性,都侧面的让Groovy字符串更加强大

IOS高级开发~开机启动&无限后台运行&监听进程

非越狱情况下实现:

开机启动:App安装到IOS设备设备之后,无论App是否开启过,只要IOS设备重启,App就会随之启动;

无限后台运行:应用进入后台状态,可以无限后台运行,不被系统kill;

监听进程:可获IOS设备运行除系统外的App(包括正在运行和后台运行);

配置项目 plist文件

添加:

<key>UIBackgroundModes</key>

<array>

<string>voip</string>

</array>

功能类:ProccessHelper

  1. #import <Foundation/Foundation.h>
  2. @interface ProccessHelper : NSObject
  3. + (NSArray *)runningProcesses;
  4. @end
  5. [cpp] view plaincopyprint?
  6. #import “ProccessHelper.h”
  7. //#include<objc/runtime.h>
  8. #include <sys/sysctl.h>
  9. #include <stdbool.h>
  10. #include <sys/types.h>
  11. #include <unistd.h>
  12. #include <sys/sysctl.h>
  13. @implementation ProccessHelper
  14. //You can determine if your app is being run under the debugger with the following code from
  15. static bool AmIBeingDebugged(void)
  16. // Returns true if the current process is being debugged (either
  17. // running under the debugger or has a debugger attached post facto).
  18. {
  19. int junk;
  20. int mib[4];
  21. struct kinfo_proc info;
  22. size_t size;
  23. // Initialize the flags so that, if sysctl fails for some bizarre
  24. // reason, we get a predictable result.
  25. info.kp_proc.p_flag = 0;
  26. // Initialize mib, which tells sysctl the info we want, in this case
  27. // we’re looking for information about a specific process ID.
  28. mib[0] = CTL_KERN;
  29. mib[1] = KERN_PROC;
  30. mib[2] = KERN_PROC_PID;
  31. mib[3] = getpid();
  32. // Call sysctl.
  33. size = sizeof(info);
  34. junk = sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, NULL, 0);
  35. assert(junk == 0);
  36. // We’re being debugged if the P_TRACED flag is set.
  37. return ( (info.kp_proc.p_flag & P_TRACED) != 0 );
  38. }
  39. //返回所有正在运行的进程的 id,name,占用cpu,运行时间
  40. //使用函数int sysctl(int *, u_int, void *, size_t *, void *, size_t)
  41. + (NSArray *)runningProcesses
  42. {
  43. //指定名字参数,按照顺序*个元素指定本请求定向到内核的哪个子系统,第二个及其后元素依次细化指定该系统的某个部分。
  44. //CTL_KERN,KERN_PROC,KERN_PROC_ALL 正在运行的所有进程
  45. int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL ,0};
  46. size_t miblen = 4;
  47. //值-结果参数:函数被调用时,size指向的值指定该缓冲区的大小;函数返回时,该值给出内核存放在该缓冲区中的数据量
  48. //如果这个缓冲不够大,函数就返回ENOMEM错误
  49. size_t size;
  50. //返回0,成功;返回-1,失败
  51. int st = sysctl(mib, miblen, NULL, &size, NULL, 0);
  52. struct kinfo_proc * process = NULL;
  53. struct kinfo_proc * newprocess = NULL;
  54. do
  55. {
  56. size += size / 10;
  57. newprocess = realloc(process, size);
  58. if (!newprocess)
  59. {
  60. if (process)
  61. {
  62. free(process);
  63. process = NULL;
  64. }
  65. return nil;
  66. }
  67. process = newprocess;
  68. st = sysctl(mib, miblen, process, &size, NULL, 0);
  69. } while (st == -1 && errno == ENOMEM);
  70. if (st == 0)
  71. {
  72. if (size % sizeof(struct kinfo_proc) == 0)
  73. {
  74. int nprocess = size / sizeof(struct kinfo_proc);
  75. if (nprocess)
  76. {
  77. NSMutableArray * array = [[NSMutableArray alloc] init];
  78. for (int i = nprocess – 1; i >= 0; i–)
  79. {
  80. NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
  81. NSString * processID = [[NSString alloc] initWithFormat:@”%d”, process[i].kp_proc.p_pid];
  82. NSString * processName = [[NSString alloc] initWithFormat:@”%s”, process[i].kp_proc.p_comm];
  83. NSString * proc_CPU = [[NSString alloc] initWithFormat:@”%d”, process[i].kp_proc.p_estcpu];
  84. double t = [[NSDate date] timeIntervalSince1970] – process[i].kp_proc.p_un.__p_starttime.tv_sec;
  85. NSString * proc_useTiem = [[NSString alloc] initWithFormat:@”%f”,t];
  86. NSString *startTime = [[NSString alloc] initWithFormat:@”%ld”, process[i].kp_proc.p_un.__p_starttime.tv_sec];
  87. NSString * status = [[NSString alloc] initWithFormat:@”%d”,process[i].kp_proc.p_flag];
  88. NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
  89. [dic setValue:processID forKey:@”ProcessID”];
  90. [dic setValue:processName forKey:@”ProcessName”];
  91. [dic setValue:proc_CPU forKey:@”ProcessCPU”];
  92. [dic setValue:proc_useTiem forKey:@”ProcessUseTime”];
  93. [dic setValue:proc_useTiem forKey:@”ProcessUseTime”];
  94. [dic setValue:startTime forKey:@”startTime”];
  95. // 18432 is the currently running application
  96. // 16384 is background
  97. [dic setValue:status forKey:@”status”];
  98. [processID release];
  99. [processName release];
  100. [proc_CPU release];
  101. [proc_useTiem release];
  102. [array addObject:dic];
  103. [startTime release];
  104. [status release];
  105. [dic release];
  106. [pool release];
  107. }
  108. free(process);
  109. process = NULL;
  110. //NSLog(@”array = %@”,array);
  111. return array;
  112. }
  113. }
  114. }
  115. return nil;
  116. }
  117. @end

 

实现代码:

  1. systemprocessArray = [[NSMutableArray arrayWithObjects:
  2. @”kernel_task”,
  3. @”launchd”,
  4. @”UserEventAgent”,
  5. @”wifid”,
  6. @”syslogd”,
  7. @”powerd”,
  8. @”lockdownd”,
  9. @”mediaserverd”,
  10. @”mediaremoted”,
  11. @”mDNSResponder”,
  12. @”locationd”,
  13. @”imagent”,
  14. @”iapd”,
  15. @”fseventsd”,
  16. @”fairplayd.N81″,
  17. @”configd”,
  18. @”apsd”,
  19. @”aggregated”,
  20. @”SpringBoard”,
  21. @”CommCenterClassi”,
  22. @”BTServer”,
  23. @”notifyd”,
  24. @”MobilePhone”,
  25. @”ptpd”,
  26. @”afcd”,
  27. @”notification_pro”,
  28. @”notification_pro”,
  29. @”syslog_relay”,
  30. @”notification_pro”,
  31. @”springboardservi”,
  32. @”atc”,
  33. @”sandboxd”,
  34. @”networkd”,
  35. @”lsd”,
  36. @”securityd”,
  37. @”lockbot”,
  38. @”installd”,
  39. @”debugserver”,
  40. @”amfid”,
  41. @”AppleIDAuthAgent”,
  42. @”BootLaunch”,
  43. @”MobileMail”,
  44. @”BlueTool”,
  45. nil] retain];

 

  1. – (void)applicationDidEnterBackground:(UIApplication *)application
  2. {
  3. while (1) {
  4. sleep(5);
  5. [self postMsg];
  6. }
  7. [cpp] view plaincopyprint?
  8. [[UIApplication sharedApplication] setKeepAliveTimeout:600 handler:^{
  9. NSLog(@”KeepAlive”);
  10. }];
  11. }
  12. – (void)applicationWillResignActive:(UIApplication *)application
  13. {
  14. }
  15. – (void)applicationWillEnterForeground:(UIApplication *)application
  16. {
  17. }
  18. – (void)applicationDidBecomeActive:(UIApplication *)application
  19. {
  20. }
  21. – (void)applicationWillTerminate:(UIApplication *)application
  22. {
  23. }
  24. #pragma mark –
  25. #pragma mark – User Method
  26. – (void) postMsg
  27. {
  28. //上传到服务器
  29. NSURL *url = [self getURL];
  30. NSURLRequest *request = [[NSURLRequest alloc]initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:10];
  31. NSError *error = nil;
  32. NSData *received = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
  33. if (error) {
  34. NSLog(@”error:%@”, [error localizedDescription]);
  35. }
  36. NSString *str = [[NSString alloc]initWithData:received encoding:NSUTF8StringEncoding];
  37. NSLog(@”%@”,str);
  38. }
  39. – (NSURL *) getURL
  40. {
  41. UIDevice *device = [UIDevice currentDevice];
  42. NSString* uuid = @”TESTUUID”;
  43. NSString* manufacturer = @”apple”;
  44. NSString* model = [device model];
  45. NSString* mobile = [device systemVersion];
  46. NSString *msg = [NSString stringWithFormat:@”Msg:%@ Time:%@”, [self processMsg], [self getTime]];
  47. CFShow(msg);
  48. / 省略部分代码 /
  49. NSString *urlStr = [strUrl stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  50. NSURL *url = [NSURL URLWithString:urlStr];
  51. return url;
  52. }
  53. – (BOOL) checkSystemProccess:(NSString *) proName
  54. {
  55. if ([systemprocessArray containsObject:proName]) {
  56. return YES;
  57. }
  58. return NO;
  59. }
  60. – (BOOL) checkFirst:(NSString *) string
  61. {
  62. NSString *str = [string substringToIndex:1];
  63. NSRange r = [@”ABCDEFGHIJKLMNOPQRSTUVWXWZ” rangeOfString:str];
  64. if (r.length > 0) {
  65. return YES;
  66. }
  67. return NO;
  68. }
  69. – (NSString *) processMsg
  70. {
  71. NSArray *proMsg = [ProccessHelper runningProcesses];
  72. if (proMsg == nil) {
  73. return nil;
  74. }
  75. NSMutableArray *proState = [NSMutableArray array];
  76. for (NSDictionary *dic in proMsg) {
  77. NSString *proName = [dic objectForKey:@”ProcessName”];
  78. if (![self checkSystemProccess:proName] && [self checkFirst:proName]) {
  79. NSString *proID = [dic objectForKey:@”ProcessID”];
  80. NSString *proStartTime = [dic objectForKey:@”startTime”];
  81. if ([[dic objectForKey:@”status”] isEqualToString:@”18432″]) {
  82. NSString *msg = [NSString stringWithFormat:@”ProcessName:%@ – ProcessID:%@ – StartTime:%@ Running:YES”, proName, proID, proStartTime];
  83. [proState addObject:msg];
  84. } else {
  85. NSString *msg = [NSString stringWithFormat:@”ProcessName:%@ – ProcessID:%@ – StartTime:%@ Running:NO”, proName, proID, proStartTime];
  86. [proState addObject:msg];
  87. }
  88. }
  89. }
  90. NSString *msg = [proState componentsJoinedByString:@”______”];
  91. return msg;
  92. }
  93. // 获取时间
  94. – (NSString *) getTime
  95. {
  96. NSDateFormatter *formatter =[[[NSDateFormatter alloc] init] autorelease];
  97. formatter.dateStyle = NSDateFormatterMediumStyle;
  98. formatter.timeStyle = NSDateFormatterMediumStyle;
  99. formatter.locale = [NSLocale currentLocale];
  100. NSDate *date = [NSDate date];
  101. [formatter setTimeStyle:NSDateFormatterMediumStyle];
  102. NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
  103. NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
  104. NSInteger unitFlags = NSYearCalendarUnit |
  105. NSMonthCalendarUnit |
  106. NSDayCalendarUnit |
  107. NSWeekdayCalendarUnit |
  108. NSHourCalendarUnit |
  109. NSMinuteCalendarUnit |
  110. NSSecondCalendarUnit;
  111. comps = [calendar components:unitFlags fromDate:date];
  112. int year = [comps year];
  113. int month = [comps month];
  114. int day = [comps day];
  115. int hour = [comps hour];
  116. int min = [comps minute];
  117. int sec = [comps second];
  118. NSString *time = [NSString stringWithFormat:@”%d-%d-%d %d:%d:%d”, year, month, day, hour, min, sec];
  119. return time;
  120. }
  121. @end

Groovy基本语法(二)

静态import

我是*早在.net framework 3.5上使用类似import static这种语法的,用起来相当方便的说,但JDK一直没有引入这玩意儿,按道理说加上这么个小功能是很容易实现的。不过Groovy倒是带来来功能更强大的import static语法,用起来也很方便:

package plswg.edu.groovy.basic

// 将Integer类的MAX_VALUE静态成员变量引入
import static Integer.MAX_VALUE

// 将Double类的parseDoubl静态成员方法引入
import static Double.parseDouble

// 给静态引入赋予别名
import static Boolean.TRUE as T // 将Boolean.TRUE取名为T
import static Boolean.FALSE as F // 将Boolean.FALSE取名为F

// 给静态引入的方法赋予别名
import static Calendar.getInstance as now

// 代码中凡是用到MAX_VALUE, 指的都是Integer.MAX_VALUE
println MAX_VALUE

// 代码中凡是用到parseDouble, 指的都是Double.parseDouble
s = “123.123”
println parseDouble(s);

// 代码中凡是使用T的地方表示true,使用F的地方表示false
println T
println !T
println F

// 代码中凡是使用now的地方表示Calendar.getInstance
println now().get(Calendar.HOUR)
这玩意儿的主要作用就是避免重复书写哪些又臭又长的类名,随着JDK类库的不断增加,类名字是越来越长,像造句一样,import static恰好解决了这一问题,还是很贴心的。
5、分支结构语句

Groovy的结构化语句仍旧是三种:顺序结构、分支结构和循环结构,其中分支结构和循环结构增加了很多意想不到的功能,先看分支结构:
package plswg.edu.groovy.basic

// groovy中if条件分支的新规定

// groovy中,非0的数值可以表示true
int num = 0
if (num) {
println “True”
} else {
println “False”
}

println (++num ? “True” : “False”)

if (!!num) { // !!运算符可以将num转化为boolean类型
println “num=${num}为${!!num}”
}
println “”

// 引用为null时,表示false
Object o = null
if (o) {
println “True”
} else {
println “False”
}
o = new Date()
if (o) {
println “True”
} else {
println “False”
}
println “”

// 字符串为””时,表示false
String s = “”
if (s) {
println “True”
} else {
println “False”
}
s += “hello”
if (s) {
println “True”
} else {
println “False”
}
println “”

// 集合为空时,表示False
ArrayList array = new ArrayList()
if (array) {
println “True”
} else {
println “False”
}
array.add(100)
if (array) {
println “True”
} else {
println “False”
}
println “”

// groovy中switch选择分支的新规定

// switch对字符串类型的支持

print “Please input your words: ”
s = new BufferedReader(new InputStreamReader(System.in)).readLine()

switch (s) {
case “how are you”:
println “fine, thank you”
break;
case “how do you do”:
println “how do you do too”
break;
default:
println “nice to meet you”
}

// switch对集合和范围的支持
n = new Random().nextInt(101)
print “you got ${n} point, ”
switch (n) {
case [98, 99, 100]: // n为98, 99, 100这三个数字时
println “very good!!”
break;
case 90 .. 97: // n为90-97之间时
println “nice job!!”
break;
case 70 .. 89: // n为70-89之间时
println “good”
break;
case 60 .. 79: // n为60-79之间时
println “can be better”
break;
case {it > 0 && it < 60}: // n比0大且比60小时
println “too bad”
break;
case 0: // n为0时
println “nothing to say”
break;
}
首先,Groovy对boolean类型放宽了限制:
常量true和false分别表示“真”和“假”;
null表示false,非null表示true;
空字符串””表示false,非空字符串表示true;
0表示false,非0表示true;
空集合表示false,非空集合表示true;
好了,从这一角度上,Groovy确实和Javascript或者PHP非常相似了,用起来非常方便。
Groovy中对于switch语句的修改也是非常夸张的,这让我甚至有些怀疑Groovy中的switch是否还能达到O1的执行效率,因为Groovy的swtich表现的太像嵌套的if…else if了,在例子中,switch的case后面可以跟随如下几种玩意儿:

常量,在Groovy中,case后的常量包括数值型常量或字符串类型常量,方便很多了,JDK7中新增加了使用字符串常量的case语句,而在.net framework 1.1中早就有了,诸如Basic,PHP,Python,Javascript等脚本,更是一开始就支持字符串常量的case语句;
Range:即范围,语法 n1 .. n2 表示n1和n2之间的所有数值n(n1 <= n <= n2);
Collection:集合,语法 [a1, a2, a3, … , an],表示由中括号中的n个元素构成的集合,其中各个元素类型不必统一;
闭包:由 { 语句 } 构成的匿名函数体,这个后面会重点讲述,这里只要知道,一旦case之后的闭包返回true,则冒号之后的代码将会执行;
总之Groovy对分支语句的改造,让其更符合主流动态语言的特点,目前大家都在玩动态语言,就算强类型语言例如C#也在向动态语言方向靠拢,C++有泛型可以一直淡定,Java也有泛型,但那就不是个玩意儿。Groovy这下改的彻底,该有的全都有了!

Groovy基本语法(一)

Starting Groovy

相比于一个传统的Java类,一个包含main方法的Groovy类可以如下书写:

代码1:具有main函数的Groovy类
package plswg.edu.groovy.basic

// 利用class关键字创建一个groovy类
class G01_HelloWorldClass {

// 静态的main方法作为程序入口
static main(args) {

// 使用println命令输出
println “HelloWorld in class”
}

}
和Java一样,程序会从这个类的main方法开始执行,和Java的区别是:

class前省略public修饰;
main方法前省略public修饰;
main方法省略返回值类型void;
main方法形参列表省略类型String[];
当然,这只是Groovy代码的一种写法,实际上执行Groovy代码完全可以不必需要一个类或main方法,所以更简单的写法如下:
package plswg.edu.groovy.basic

// 对于groovy程序来说,可以没有类和main方法,直接书写的代码就可以作为脚本运行
println “HelloWorld in script”
这段代码仍可以直接运行。

实际上,*终编译器仍会为这段代码生成一个类,类名和文件名相同,只不过从源码的角度上,确实不用写类或者main方法了,这一点很像Javascript等其它脚本语言。

可以注意到,Groovy将Java中繁琐的System.out.println简化为了println,甚至可以不为形参列表加括号,这都是允许的,Groovy非常简洁,甚至不要求语句末尾的分号(当然,写上分号也无伤大雅)

3、Groovy变量

既然是脚本语言,Groovy的变量也被设计成为了类似的弱类型,实际上Groovy同时支持强类型变量和“弱”类型变量,强类型变量拥有自己的类型,而“弱”类型变量则全部会被编译为Object类型,从代码的角度上,Groovy的变量无需声明类型了:

package plswg.edu.groovy.basic

// groovy可以使用类型确定的变量或常量

String s1 = “Hello ”
print s1

final String s2 = “World”
println s2

// 利用def关键字可以定义可变类型的变量或常量

def s3 = “Welcome ”
print s3

// 对于可变类型,即随时可以改变其类型,赋予不同的量

s3 = 123 // 此时str3被赋予了整型量,所以其类型变为Integer类型
println s3

s3 += 100 // 整型的str3和整型相加,结果是整型223
println s3

s3 = true // str3目前是boolean类型
println (“Ok ” + s3)

// 对于局部变量,甚至可以不使用def关键字来定义
s4 = “Good job”
println s4

// 对于数值类型,有如下规则

int n1 = 10
n2 = n1 / 3
println n2 // 对于n1为整数时, 10 / 3的结果并不是整数,这说明常量n2并不是整数

int n3 = n1 / 3 // 明确定义n3为整数后,相除的结果为整数
println n3

n2 = n1.intdiv(3)
println n2 // intdiv用于进行整除

n2 = n1.power(2) // 求平方 groovy方法
println n2

n2 = n1 ** 2 // 求平方的groovy语法
println n2

n1 = Math.sqrt(n2) // 求开方 java方法
println n1
从上面的代码可以看到,Groovy支持有类型的变量,例如 String s;也支持无类型的变量,例如 def s,相当于Java中的Object s;对于无类型的变量,甚至可以不写 def关键字。
final关键字依然作为常量标识,这一点和Java相同。

*后注意一点,Groovy中没有Java中的值类型简单对象,所有的对象都是引用类型对象,例如定义def n = 10,n的类型应该是Integer类型而不是int类型;即便定义了int n = 100,n的类型依然是Integer类型;如果定义了def n = 12.34,则注意,n的类型是BigDecimal类型而不是Double类型,只有显式定义double n = 12.34,n的类型才明确为Double类型(依旧不是double类型)

对于基本算术运算符,Groovy增加了**运算符,表示求幂,x ** y表示求x的y次方