WebServer

lrenwang , 2011/12/13 13:13 , windows , 评论(0) , 阅读(305) , Via 本站原创
WebServer 1.0
PHP              5.2.17
APACHE       2.2.20
MYSQL        5.1.58
WebServer是在 http://blog.lrenwang.com/wamp_v1/ 手动搭建wamp基础上改进而成
1 对Win7的友好支持
2 目录任意设定
3 优化了配置文件,把路径全部改成相对路径
4 删除一些垃圾文件,优化体积
5 运行稳定
6 安装的服务器名 apache 改成WebServer_Apache  ,MySql改成WebServer_MySql , 通过services.msc查看

绿色版


安装前
1 请确保本机没有其它apache服务环境
2 360等会拦截setup.bat批处理文件. 选择允许
WIN7下经常需要管理员身份运行
但是如果这样原来%CD%可以取到的路径变成了c:\windows\system32的...这样非常操蛋 尤其是BAT基本上都是为了操作本目录的嘛...
发现解决方法如下
在头部加入如下代码

@echo off
%~D0
CD  %~DP0
echo %cd%
pause

jquery php截图 1.0

lrenwang , 2011/11/23 10:36 , Javascript , 评论(2) , 阅读(412) , Via 本站原创
其实这个功能不是很复杂,网上也有不少例子, 感觉写的太麻烦了. 我就自己写了个简单的例子,虽然功能不是很完善,但是基础功能都有了,扩展很方便的
主要是分成几个部分
如果转载,请标明http://blog.lrenwang.com/crop_v1/,谢谢





那些坐标是为了方便理解,实际使用的时候设置成隐藏(hidden)
点击在新窗口中浏览此图片


div_ctrl.js  控制选择区域的缩放

(function($) {
  /**
   *  鼠标控制div的伸缩
   *
   */
  $.fn.div_ctrl = function(options) {
    var defaults = {
      id:"check_box",
      s:2,
      w:"dst_w",
      h:"dst_h"
    };
    
    var options = $.extend(defaults, options);
    //是否点击状态
    var m_click = false;
    
    //定时器的句柄
    var clock;
    
    var dst_w = $("#"+options.w);
    var dst_h = $("#"+options.h);
    //图形比例
    var pn = dst_h.val()/dst_w.val();
    
    var obj = $(this);
    obj.bind("mouseout",
    function() {
      m_click = false;
    }).bind("mouseup",
    function() {
      m_click = false;
    }).bind("mouseover",
    function() {
      m_click = false;
    }).bind("mousedown",
    function(s) {
      m_click = true;
      clock = setInterval( function(){div_control()},10);
    });

    function div_control ()
    {
      if(!m_click) window.clearInterval(clock)
      var obj = $("#"+options.id);
      var w = parseInt(obj.css("width").replace(/px/, ""))+options.s;
      var h = Math.ceil(w*pn);
      obj.css({width:w+"px",height:h+"px"})
      dst_w.val(w);
      dst_h.val(h);
    }
  };
})(jQuery);

div_move.js 控制选择区域的拖拽

/**
*  div拖拽
*
*
*/
(function($) {
  $.fn.div_move = function(options) {
    var defaults = {
    };
    var options = $.extend(defaults, options);
    //是否点击状态
    var m_click = false;
    var m_x,m_y;

    var obj = $(this);
    obj.bind("mouseout",
    function() {
      m_click = false;
    }).bind("mouseup",
    function() {
      m_click = false;
    }).bind("mousedown",
    function(e) {
      m_x = e.clientX ;
      m_y = e.clientY ;
      m_click = true;
    }).bind("mousemove",
    function(e) {
      if(!m_click) return ;
      var x = parseInt(e.clientX) ;
      var y = parseInt(e.clientY) ;
      var div_left = parseInt($(this).css("left").replace(/px/, ""));
      var div_top = parseInt($(this).css("top").replace(/px/, ""));
      var offset_x = div_left+(x - parseInt(m_x));
      var offset_y = div_top+(y - parseInt(m_y));
      obj.css({left:offset_x+"px",top:offset_y+"px"})

      m_x = x;
      m_y = y;

      $("#"+options.x).val(offset_x);
      $("#"+options.y).val(offset_y);
    }).bind("click",
    function() {
    });


  };
})(jQuery);


index.php
主要是控制3种操作,其实应该分成2个文件的,懒得搞那么细致
1 预览
2 下载, 和预览只有一点小差别
3 控制页面

<?php

/**
* 截图
*
* @param string $source  原图的饿url地址
* @param int $src_x    从原图的x坐标点开始
* @param int $src_y    从原图的y坐标开始
* @param int $dst_w    新图的宽度
* @param int $dst_h    新图的高度
* @param int $src_w    从原图截取的宽度
* @param int $src_h    从原图截取的高度
* @return  resource $thumb  返回新图资源
*/
function crop($src ,$src_x ,$src_y ,$dst_w ,$dst_h,$src_w,$src_h)
{
  $thumb = imagecreatetruecolor($dst_w, $dst_h);
  /**
   * 读取大图的资源
   *   请注意,这里其实应该判断文件是什么类型, getimagesize()
   *
   */
  $source_rs = imagecreatefromjpeg($src);

  imagecopyresized($thumb, $source_rs, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
  return $thumb;
}
/**
* 预览
*/
if ($_GET['type']=='preview')
{
  $thumb = crop($_GET['src'],$_GET['src_x'],$_GET['src_y'],$_GET['dst_w'],$_GET['dst_h'],$_GET['src_w'],$_GET['src_h']);
  header('Content-Type: image/jpeg');
  imagejpeg($thumb);
  exit;
}
/**
* 生成
*/
if ($_GET['type']=='make')
{
  $thumb = crop($_GET['src'],$_GET['src_x'],$_GET['src_y'],$_GET['dst_w'],$_GET['dst_h'],$_GET['src_w'],$_GET['src_h']);
  $tmp = explode('.',$_GET['src']);
  $src_new = $tmp[0].'_thumb.'.$tmp[1];
  imagejpeg($thumb,$src_new,90);
  



  Header("Content-type: {$type} ; charset=utf-8");               //输出类型
  Header("Content-Disposition:filename={$src_new}");
  Header("Accept-Ranges: bytes");                       //文件单位
  Header("Content-Disposition: attachment; filename={$src_new}");        //下载时显示的名字
  $file = fopen($src_new,"r");         // 打开文件
  echo fread($file,filesize($src_new));
  fclose($file);
  exit;
  exit;
}

//源文件
$src = '1.jpg';
//获得原图的宽高
list($src_w, $src_h) = getimagesize($src);

//小图的宽度
$dst_w  = '100';
//小图的高度
$dst_h = '100';
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
  <meta name="generator" content="WebMotionUK" />
  <title>crop</title>
  <script type="text/javascript" src="jquery.js"></script>
  <script type="text/javascript" src="div_ctrl.js"></script>
  <script type="text/javascript" src="div_move.js"></script>

<style>
#crop{
  position: absolute;
  left:100px;
  top:0px;
}
#crop1{
  position: absolute;
  left:800px;
  top:0px;
  width:650px;
  height:800px;
}
#crop img {
  position: absolute;
  left:0px;
  top:0px;
  z-index:1;
}
#check_box
{
  position: absolute;
  left:0px;
  top:0px;
  width:100px;
  height:100px;
  z-index:100;
  border:#369 solid 1px;  
  cursor:pointer;
}
</style>
</head>
<body>

<div id="crop">
<img src="<?=$src?>" >
<div id="check_box"></div>
</div>


<div id="crop1">
大图起始点x:<input type="text" id="src_x" name="src_x" value="0">
大图起始点y:<input type="text" id="src_y" name="src_y" value="0"><br />
大图截取宽度:<input type="text" id="src_w" name="src_w" value="<?=$dst_w?>">
大图截取高度:<input type="text" id="src_h" name="src_h" value="<?=$dst_h?>"><br />
<input type="button" value="预览" onclick="preview()" />
<input type="button" value="生成" onclick="image_make()" />
<input type="button" value="+" id="btm_up">
<input type="button" value="-" id="btm_down">
<p>

<div id="new_img"></div>
<div id="img_src"></div>
</p>
</div>
<script>
var src = '<?=$src?>';
var dst_w = '<?=$dst_w?>';
var dst_h = '<?=$dst_h?>';

$(document).ready(function(){
  //初始化
  $("#crop").css({width:"<?=$src_w?>px",height:"<?=$src_h?>px"})
  $("#check_box").css({width:"<?=$dst_w?>px",height:"<?=$dst_h?>px"})

  $('#check_box').div_move({x:'src_x',y:'src_y'});
  $("#btm_up").div_ctrl({id:"check_box",s:2,w:"src_w",h:"src_h"});
  $("#btm_down").div_ctrl({id:"check_box",s:-2,w:"src_w",h:"src_h"});

});

function preview()
{
  var src_x = $("#src_x").val();
  var src_y = $("#src_y").val();
  var src_w = $("#src_w").val();
  var src_h = $("#src_h").val();
  var img_src = "?type=preview&src="+src+"&src_x="+src_x+"&src_y="+src_y+"&dst_w="+dst_w+"&dst_h="+dst_h+"&src_w="+src_w+"&src_h="+src_h;
  $("#new_img").html("<img src='"+img_src+"' />")
}
function image_make()
{
  var src_x = $("#src_x").val();
  var src_y = $("#src_y").val();
  var src_w = $("#src_w").val();
  var src_h = $("#src_h").val();
  var img_src = "?type=make&src="+src+"&src_x="+src_x+"&src_y="+src_y+"&dst_w="+dst_w+"&dst_h="+dst_h+"&src_w="+src_w+"&src_h="+src_h;
  $("#img_src").html("<a href='"+img_src+"' target=_blank>下载</a>")

}
</script>

ImageCopyResampled和ImageCopyResized

lrenwang , 2011/11/14 22:41 , Php , 评论(0) , 阅读(215) , Via 本站原创
PHP中缩放图像.
有两种改变图像大小的方法.
(1):ImageCopyResized() 函数在所有GD版本中有效,但其缩放图像的算法比较粗糙.
(2):ImageCopyResamples() ,其像素插值算法得到的图像边缘比较平滑.(但该函数的速度比 ImageCopyResized() 慢).
两个函数的参数是一样的.如下:
ImageCopyResampled(dest,src,dy,dx,sx,sy,dw,dh,sw,sh);
ImageCopyResized(dest,src,dy,dx,sx,sy,dw,dh,sw,sh);
bool imagecopyresampled ( resource $dst_image , resource $src_image , int $dst_x , int $dst_y , int $src_x , int $src_y , int $dst_w , int $dst_h , int $src_w , int $src_h )
$dst_image:新建的图片
$src_image:需要载入的图片(原图)
$dst_x:设定需要载入的图片在新图中的x坐标
$dst_y:设定需要载入的图片在新图中的y坐标
$src_x:设定载入图片要载入的区域x坐标
$src_y:设定载入图片要载入的区域y坐标
$dst_w:设定载入的原图的宽度(在此设置缩放)
$dst_h:设定载入的原图的高度(在此设置缩放)
$src_w:原图要载入的宽度
$src_h:原图要载入的高度

<?PHP //例子
$src = ImageCreateFromJPEG('php.jpg');
$width = ImageSx($src);
$height = ImageSy($src);
$x = $widht/2;
$y = $height/2;
$dst = ImageCreateTrueColor($x,$y);
ImageCopyResampled($dst,$src,0,0,0,0,$x,$y,$widht,$height);
//imagejpeg($thumb,'a.jpg',90);  生成图片
header('Content-Type : image/png');
ImagePNG($det);
?>


网上转载,看着很操蛋,决定用我自己的语言话解释下



ImageCopyResampled($dst,$src,1,2,3,4,$x,$y,$widht,$height);

对图层进行拷贝操作, 再$src当中,从x坐标3,y坐标4开始, x长度是$width,y长度是$height 这个区域进行复制,
复制到$dst中, 从$dst的x是1,y是2这个点开始, 宽高是$x,$y


Android 常用代码大集合

lrenwang , 2011/11/07 10:52 , android , 评论(0) , 阅读(298) , Via 本站原创
1 活动管理器
权限
<uses-permission android:name="android.permission.GET_TASKS"/>

代码
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);


2 警报管理器 权限
代码
AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);


3 音频管理器 权限
代码
AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);

4 剪贴板管理器 权限
代码
ClipboardManager clipboardManager = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);


5 连接管理器 权限
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

代码
ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVIT


6 输入法管理器 权限
代码
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_S)

7 键盘管理器 权限
代码
KeyguardManager keyguardManager = (KeyguardManager) getSystemService(Context.KEYGUARD_SERVICE);


8 布局解压器管理器 权限
代码
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);


9 位置管理器 权限
代码
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);


10 通知管理器 权限
代码
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATIO)


11 电源管理器 权限
<uses-permission android:name="android.permission.DEVICE_POWER"/>

代码
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);


12 搜索管理器 权限
代码
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);


13 传感器管理器 权限
代码
SensorManager sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);


14 电话管理器 权限
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>

代码
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);


15 振动器 权限
<uses-permission android:name="android.permission.VIBRATE"/>

代码
Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);


16 墙纸 权限
<uses-permission android:name="android.permission.SET_WALLPAPER"/>

代码
WallpaperService wallpaperService = (WallpaperService) getSystemService(Context.WALLPAPER_SERVICE);


17 Wi-Fi管理器 权限
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>

代码
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);


18 窗口管理器 权限
代码
WindowManager windowManager = (WindowManager) getSystemService(Context.WINDOW_SERVICE);


19获取用户android手机 机器码和手机号

TelephonyManager tm = (TelephonyManager)context.getSystemService(Context.TELEPHONY_SERVICE);
       String imei = tm.getDeviceId();//获取机器码
         String tel = tm.getLine1Number();//获取手机号

20设置为横屏
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

21无标题栏、全屏  

//无标题栏  
   requestWindowFeature(Window.FEATURE_NO_TITLE);  //要在setcontentView之前哦
    //全屏模式  
   getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,  
  WindowManager.LayoutParams.FLAG_FULLSCREEN);



22 获取屏幕宽高

DisplayMetrics dm = new DisplayMetrics();  
//获取窗口属性  
getWindowManager().getDefaultDisplay().getMetrics(dm);  
int screenWidth = dm.widthPixels;//320  
int screenHeight = dm.heightPixels;//480



23使用样式表
在 res/values下面新建一个XML文件style.xml ,然后写下如下代码
<?xml version="1.0" encoding="utf-8"?>
<resources>
<style name="style1">
<item name="android:textSize">18sp</item>
<item name="android:textColor">#EC9237</item>
</style>
<style name="style2"><item name="android:textSize">10sp</item>
<item name="android:textColor">#FF9237</item>
</style>
</resources>


使用:
<TextView
style="@style/style1"//调用style
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="样式1"
android:id="@+id/Tv1">
</TextView>


24使用布局文件,切换 布局
建立两个布局文件
在事件里面写代码

@Override
   public void onClick(View v) {
     helllo.this.setContentView(R.layout.layout2);
     Button tempBtn=(Button)findViewById(R.id.btn_click1);
     tempBtn.setOnClickListener(new Button.OnClickListener(){
     @Override
     public void onClick(View v) {
       helllo.this.setContentView(R.layout.xxx);
     }
     });



=========================================================================
1.Intent用法
2010-04-27 12:09



Intent it = new Intent(Activity.Main.this, Activity2.class);
startActivity(it);

2. 向下一个Activity传递数据(使用Bundle和Intent.putExtras)
Intent it = new Intent(Activity.Main.this, Activity2.class);
Bundle bundle=new Bundle();
bundle.putString("name", "This is from MainActivity!");
it.putExtras(bundle); // it.putExtra(“test”, "shuju”);
startActivity(it); // startActivityForResult(it,REQUEST_CODE);
对于数据 的获取可以采用:
Bundle bundle=getIntent().getExtras();
String name=bundle.getString("name");

3. 向上一个Activity返回结果(使用setResult,针对startActivityForResult(it,REQUEST_CODE)启动 的Activity)
Intent intent=getIntent();
Bundle bundle2=new Bundle();
bundle2.putString("name", "This is from ShowMsg!");
intent.putExtras(bundle2);
setResult(RESULT_OK, intent);

4. 回调上一个Activity的结果处理函数(onActivityResult)

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_CODE){
if(resultCode==RESULT_CANCELED)
setTitle("cancle");
else if (resultCode==RESULT_OK) {
String temp=null;
Bundle bundle=data.getExtras();
if(bundle!=null) temp=bundle.getString("name");
setTitle(temp);
}
}
}
显示网页
1. Uri uri = Uri.parse("http://google.com");
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. startActivity(it);
显示地图
1. Uri uri = Uri.parse("geo:38.899533,-77.036476");
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. startActivity(it);
4. //其他 geo URI 範例
5. //geo:latitude,longitude
6. //geo:latitude,longitude?z=zoom
7. //geo:0,0?q=my+street+address
8. //geo:0,0?q=business+near+city
9. //google.streetview:cbll=lat,lng&cbp=1,yaw,,pitch,zoom&mz=mapZoom
路 径规划
1. Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en");
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. startActivity(it);
4. //where startLat, startLng, endLat, endLng are a long with 6 decimals like: 50.123456
打 电话
1. //叫出拨号程序
2. Uri uri = Uri.parse("tel:0800000123");
3. Intent it = new Intent(Intent.ACTION_DIAL, uri);
4. startActivity(it);
1. //直接打电话出去
2. Uri uri = Uri.parse("tel:0800000123");
3. Intent it = new Intent(Intent.ACTION_CALL, uri);
4. startActivity(it);
5. //用這個,要在 AndroidManifest.xml 中,加上
6. //<uses-permission id="android.permission.CALL_PHONE" />
传 送SMS/MMS
1. //调用短信程序
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. it.putExtra("sms_body", "The SMS text");
4. it.setType("vnd.android-dir/mms-sms");
5. startActivity(it);
1. //传送消息
2. Uri uri = Uri.parse("smsto://0800000123");
3. Intent it = new Intent(Intent.ACTION_SENDTO, uri);
4. it.putExtra("sms_body", "The SMS text");
5. startActivity(it);
1. //传送 MMS
2. Uri uri = Uri.parse("content://media/external/images/media/23");
3. Intent it = new Intent(Intent.ACTION_SEND);
4. it.putExtra("sms_body", "some text");
5. it.putExtra(Intent.EXTRA_STREAM, uri);
6. it.setType("image/png");
7. startActivity(it);
传 送 Email
1. Uri uri = Uri.parse("mailto:xxx@abc.com");
2. Intent it = new Intent(Intent.ACTION_SENDTO, uri);
3. startActivity(it);
1. Intent it = new Intent(Intent.ACTION_SEND);
2. it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");
3. it.putExtra(Intent.EXTRA_TEXT, "The email body text");
4. it.setType("text/plain");
5. startActivity(Intent.createChooser(it, "Choose Email Client"));
1. Intent it=new Intent(Intent.ACTION_SEND);
2. String[] tos={"me@abc.com"};
3. String[] ccs={"you@abc.com"};
4. it.putExtra(Intent.EXTRA_EMAIL, tos);
5. it.putExtra(Intent.EXTRA_CC, ccs);
6. it.putExtra(Intent.EXTRA_TEXT, "The email body text");
7. it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
8. it.setType("message/rfc822");
9. startActivity(Intent.createChooser(it, "Choose Email Client"));
1. //传送附件
2. Intent it = new Intent(Intent.ACTION_SEND);
3. it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
4. it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");
5. sendIntent.setType("audio/mp3");
6. startActivity(Intent.createChooser(it, "Choose Email Client"));
播 放多媒体
Uri uri = Uri.parse("file:///sdcard/song.mp3");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
it.setType("audio/mp3");
startActivity(it);
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
Market 相关
1. //寻找某个应用
2. Uri uri = Uri.parse("market://search?q=pname:pkg_name");
3. Intent it = new Intent(Intent.ACTION_VIEW, uri);
4. startActivity(it);
5. //where pkg_name is the full package path for an application
1. //显示某个应用的相关信息
2. Uri uri = Uri.parse("market://details?id=app_id");
3. Intent it = new Intent(Intent.ACTION_VIEW, uri);
4. startActivity(it);
5. //where app_id is the application ID, find the ID
6. //by clicking on your application on Market home
7. //page, and notice the ID from the address bar
Uninstall 应用程序
1. Uri uri = Uri.fromParts("package", strPackageName, null);
2. Intent it = new Intent(Intent.ACTION_DELETE, uri);
3. startActivity(it);
===============================================================================
1 调用浏览器 载入某网址
view plaincopy to clipboardprint?
Uri uri = Uri.parse("http://www.baidu.com");          
Intent it = new Intent(Intent.ACTION_VIEW, uri);          
startActivity(it);  
2 Broadcast接收系统广播的intent 监控应用程序包的安装 删除
view plaincopy to clipboardprint?
public class getBroadcast extends BroadcastReceiver {  
        @Override  
        public void onReceive(Context context, Intent intent) {  
                  if(Intent.ACTION_PACKAGE_ADDED.equals(intent.getAction())){  
                    Toast.makeText(context, "有应用被添加", Toast.LENGTH_LONG).show();  
            }  
                else  if(Intent.ACTION_PACKAGE_REMOVED.equals(intent.getAction())){  
                    Toast.makeText(context, "有应用被删除", Toast.LENGTH_LONG).show();  
            }  
                else  if(Intent.ACTION_PACKAGE_REPLACED.equals(intent.getAction())){  
                    Toast.makeText(context, "有应用被替换", Toast.LENGTH_LONG).show();  
            }  
                else  if(Intent.ACTION_CAMERA_BUTTON.equals(intent.getAction())){  
                    Toast.makeText(context, "按键", Toast.LENGTH_LONG).show();  
            }  
        }  
}  
需要声明的权限如下AndroidManifest.xml
view plaincopy to clipboardprint?
<?xml version="1.0" encoding="utf-8"?>  
<manifest xmlns:android="http://schemas.android.com/apk/res/android"  
      package="zy.Broadcast"  
      android:versionCode="1"  
      android:versionName="1.0">  
    <application android:icon="@drawable/icon" android:label="@string/app_name">  
        <activity android:name=".Broadcast"  
                  android:label="@string/app_name">  
            <intent-filter>  
                <action android:name="android.intent.action.MAIN" />  
                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>  
        </activity>  
      <receiver android:name="getBroadcast" android:enabled="true" >  
         <intent-filter>  
             <action android:name="android.intent.action.PACKAGE_ADDED"></action>  
             <!-- <action android:name="android.intent.action.PACKAGE_CHANGED"></action>-->  
             <action android:name="android.intent.action.PACKAGE_REMOVED"></action>  
             <action android:name="android.intent.action.PACKAGE_REPLACED"></action>  
             <!-- <action android:name="android.intent.action.PACKAGE_RESTARTED"></action>-->  
           <!--    <action android:name="android.intent.action.PACKAGE_INSTALL"></action>-->  
               <action android:name="android.intent.action.CAMERA_BUTTON"></action>  
               <data android:scheme="package"></data>  
              </intent-filter>  
</receiver>  
    </application>  
    <uses-sdk android:minSdkVersion="3" />  
</manifest>  
3 使用Toast输出一个字符串
view plaincopy to clipboardprint?
public void DisplayToast(String str)  
        {  
      Toast.makeText(this,str,Toast.LENGTH_SHORT).show();  
        }  
4 把一个字符串写进文件
view plaincopy to clipboardprint?
public void writefile(String str,String path )  
        {  
            File file;  
            FileOutputStream out;  
             try {  
                 //创建文件  
                 file = new File(path);  
                 file.createNewFile();  
                 //打开文件file的OutputStream  
                 out = new FileOutputStream(file);  
                 String infoToWrite = str;  
                 //将字符串转换成byte数组写入文件  
                 out.write(infoToWrite.getBytes());  
                 //关闭文件file的OutputStream  
                 out.close();  
             } catch (IOException e) {  
                 //将出错信息打印到Logcat  
              DisplayToast(e.toString());  
             }  
        }  
5 把文件内容读出到一个字符串
view plaincopy to clipboardprint?
public String getinfo(String path)  
        {  
            File file;  
            String str="";  
            FileInputStream in;  
         try{  
            //打开文件file的InputStream  
             file = new File(path);  
             in = new FileInputStream(file);  
             //将文件内容全部读入到byte数组  
             int length = (int)file.length();  
             byte[] temp = new byte[length];  
             in.read(temp, 0, length);  
             //将byte数组用UTF-8编码并存入display字符串中  
             str =  EncodingUtils.getString(temp,TEXT_ENCODING);  
             //关闭文件file的InputStream  
             in.close();  
         }  
         catch (IOException e) {  
          DisplayToast(e.toString());  
         }  
         return str;  
        }  
6 调用Android installer 安装和卸载程序
view plaincopy to clipboardprint?
Intent intent = new Intent(Intent.ACTION_VIEW);  
       intent.setDataAndType(Uri.fromFile(new File("/sdcard/WorldCupTimer.apk")), "application/vnd.android.package-archive");  
       startActivity(intent); //安装 程序  
       Uri packageURI = Uri.parse("package:zy.dnh");      
       Intent uninstallIntent = new Intent(Intent.ACTION_DELETE, packageURI);      
       startActivity(uninstallIntent);//正常卸载程序  
7 结束某个进程
view plaincopy to clipboardprint?
activityManager.restartPackage(packageName);  
8 设置默认来电铃声
view plaincopy to clipboardprint?
public void setMyRingtone()  
    {  
   File k = new File("/sdcard/Shall We Talk.mp3"); // 设置歌曲路径  
    ContentValues values = new ContentValues();  
    values.put(MediaStore.MediaColumns.DATA, k.getAbsolutePath());  
    values.put(MediaStore.MediaColumns.TITLE, "Shall We Talk");  
    values.put(MediaStore.MediaColumns.SIZE, 8474325);  
    values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");  
    values.put(MediaStore.Audio.Media.ARTIST, "Madonna");  
    values.put(MediaStore.Audio.Media.DURATION, 230);  
    values.put(MediaStore.Audio.Media.IS_RINGTONE, true);  
    values.put(MediaStore.Audio.Media.IS_NOTIFICATION, false);  
    values.put(MediaStore.Audio.Media.IS_ALARM, false);  
    values.put(MediaStore.Audio.Media.IS_MUSIC, false);  
    // Insert it into the database  
    Uri uri = MediaStore.Audio.Media.getContentUriForPath(k.getAbsolutePath());  
    Uri newUri = this.getContentResolver().insert(uri, values);  
    RingtoneManager.setActualDefaultRingtoneUri(this, RingtoneManager.TYPE_RINGTONE, newUri);  
    ;}  
需要的权限
view plaincopy to clipboardprint?
<uses-permission android:name="android.permission.WRITE_SETTINGS"></uses-permission>
分页: 4/36 第一页 上页 1 2 3 4 5 6 7 8 9 10 下页 最后页 [ 显示模式: 摘要 | 列表 ]