Android实用代码片段

 有时候,需要一些小的功能,找到以后,就把它贴到了博客下面,作为留言,查找起来很不方便,所以就整理一下,方便自己和他人。

         一、  获取系统版本号:

?
1
2
3
PackageInfo info =  this .getPackageManager().getPackageInfo( this .getPackageName(),  0 );
int versionCode=nfo.versionCode
string versionName=info.versionNam

               二、获取系统信息:

?
1
2
3
4
5
6
7
8
9
10
11
12
<span>String archiveFilePath= "sdcard/download/Law.apk" ; //安装包路径
PackageManager pm = getPackageManager();
PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES);
if (info !=  null ){
ApplicationInfo appInfo = info.applicationInfo;
String appName = pm.getApplicationLabel(appInfo).toString();
String packageName = appInfo.packageName;  //得到安装包名称
String version=info.versionName;  //得到版本信息
Toast.makeText(test4. this "packageName:" +packageName+ ";version:" +version, Toast.LENGTH_LONG).show();
Drawable icon = pm.getApplicationIcon(appInfo); //得到图标信息
TextView tv = (TextView)findViewById(R.id.tv);  //显示图标
tv.setBackgroundDrawable(icon);</span>

        三、获取安装路径和已安装程序列表

?
1
2
3
4
<span>( 1 )android中获取当前程序路径
getApplicationContext().getFilesDir().getAbsolutePath()
( 2 )android取已安装的程序列表
List<PackageInfo> packageInfoList = getPackageManager().getInstalledPackages( 0 );</span>

       四、获取图片、应用名、包名

?
1
2
3
4
5
6
7
8
9
10
<span>PackageManager pManager = MessageSendActivity. this .getPackageManager();
List<PackageInfo> appList = Utils.getAllApps(MessageSendActivity. this );
      for ( int i= 0 ;i<appList.size();i++) {
          PackageInfo pinfo = appList.get(i);
          ShareItemInfo shareItem =  new ShareItemInfo();
          //set Icon
          shareItem.setIcon(pManager.getApplicationIcon(pinfo.applicationInfo));
          //set Application Name shareItem.setLabel(pManager.getApplicationLabel(pinfo.applicationInfo).toString());
         //set Package Name shareItem.setPackageName(pinfo.applicationInfo.packageName);
}</span>
         五、解决listview上 Item上有按钮时 item本身不能点击的问题:

?
1
2
<span> 1 . 在item试图上面添加代码: android:descendantFocusability= "blocksDescendants"
2 .在listview里 添加代码 android:focusable= "true" </span>
         六、不让文本框输入中文:

?
1
< span >在xml文件里面</ span >
?
1
2
< span >android:digits="1234567890qwertyuiopasdfghjklzxcvbnm`-=[]\;,./~!@#$%^*()_+}{:?&<>"'"
这样就不会输入中文了。</ span >
        
         七、获取屏幕宽高

?
1
2
3
4
<span>DisplayMetrics displayMetrics =  new DisplayMetrics();
this .getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
int height = displayMetrics.heightPixels;
int width = displayMetrics.widthPixels;</span>
         八、将TabWidget显示在屏幕下方

?
1
<span>设置TabWidget的属性 android:layout_alignParentBottom= "true" </span>
为了让tabHost显示在下方,要将RadioGroup的layout_gravity设置为bottom,再将FrameLayout的 layout_weight设置为1,这样就可以将RadioGroup撑到最下方。style="@style/main_tab_bottom"里面定义了样式文件      

         九、获取线程ID和线程名称:

?
1
<span>Log.v( "@@@@@@@@@@" ,Thread.currentThread().getId()+ " " +Thread.currentThread().getName());</span>

        十、android中调用其它android应用

?
1
2
3
4
5
<span>ComponentName comp =  new ComponentName( "com.Test" , "com.login.Main" );
  intent =  new Intent();
  intent.setComponent(comp);
  intent.setAction( "android.intent.action.VIEW" );
  startActivity(intent);</span>
         十一、禁止软键盘弹出

?
1
2
3
4
5
<span>EditText有焦点(focusable为 true )阻止输入法弹出 editText.setInputType(InputType.TYPE_NULL);  // 关闭软键盘
当EidtText无焦点(focusable= false )时阻止输入法弹出
 
InputMethodManager imm = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(),  0 );</span>
【Android】EditText标签调用键盘
在xml文件中EditText标签有一个属性android:editable="false"和android:numeric="integer"

android:numeric="integer"表示只允许输入数字,此属性可以限制用户只能输入数字内容。
android:editable表示是否可以输入内容TRUE表示可以输入,false表示不允许输入内容;
当为android:editable="false"时,点击输入框,虚拟键盘是显示不出来的,不过当设置了 android:editable=""属性时,不管是false还是true,在其后加入android:numeric="integer"属性时,是可以输入数字内容了;这里没搞明白是怎么回事,也许是numeric把前面的属性覆盖掉了。
当android:editable="false"时,在java类里如果再规定EditText.setEnabled(true)时,虚拟键盘还是不会显示的。

       十二、模拟器的各种规格与分辨率对照:
?
1
2
3
4
5
6
7
单位:像素
WVGA854: 854*480
WVGA800: 800*480
HVGA: 480*320
QVGA: 320*240
WQVGA432:432*240
WQVGA400:400*240
    
           十三、调用Android其他Context的Activity
?
1
2
3
4
5
6
7
Context c = createPackageContext( "chroya.demo" , Context.CONTEXT_INCLUDE_CODE | Context.CONTEXT_IGNORE_SECURITY);
//载入这个类
Class clazz = c.getClassLoader().loadClass( "chroya.demo.Main" );
//新建一个实例
Object owner = clazz.newInstance();
//获取print方法,传入参数并执行
Object obj = clazz.getMethod( "print" , String. class ).invoke(owner,  "Hello" );
这个方法有两个参数: 
1、packageName  包名,要得到Context的包名 
2、 flags  标志位,有CONTEXT_INCLUDE_CODE和CONTEXT_IGNORE_SECURITY两个选项。 CONTEXT_INCLUDE_CODE的意思是包括代码,也就是说可以执行这个包里面的代码。CONTEXT_IGNORE_SECURITY的意思 是忽略安全警告,如果不加这个标志的话,有些功能是用不了的,会出现安全警告。 
 
            十四、android4.0Dialog风格小技巧

4.0上如果还用Theme.Dialog,只能说很土,跟整体UI风格差别很大

请使用android:theme="@android:style/Theme.Holo.DialogWhenLarge"


   
         十五、程序中安装apk
     
?
1
2
3
4
5
Intent intent =  new Intent();          
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
     intent.setAction(android.content.Intent.ACTION_VIEW);
     intent.setDataAndType(Uri.fromFile(“APK”), "application/vnd.android.package-archive" );
     startActivity(intent);

其中“apk”为你要安装的那个文件。

         十六、获取设备型号、SDK版本及系统版本

?
1
2
3
String device_model = Build.MODEL;  // 设备型号 
String version_sdk = Build.VERSION.SDK;  // 设备SDK版本 
String version_release = Build.VERSION.RELEASE;  // 设备的系统版本

            十七、图片分析功能

?
1
2
3
4
5
6
7
public void SharePhoto(String photoUri, final Activity activity) { 
     Intent shareIntent =  new Intent(Intent.ACTION_SEND); 
     File file =  new File(photoUri); 
     shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file)); 
     shareIntent.setType( "image/jpeg" ); 
     StartActivity(Intent.createChooser(shareIntent, activity.getTitle())); 
}


         十八、linux关机命令

在Windows下,按着电源键4秒强制关机,在Linux下强烈不建议这么做。Windows由于是单用户、“假多”任务的情况,所以即使你的计算机关机,也不会对别人造成影响。不过在Linux中,由于每个程序都是在后台执行的,因此,在你看不到的屏幕背后可能有很多人同时在你的主机上工作。而且,若不正常关机可能会造成文件系统的损毁。所以,正常情况下,要关机时需要注意下面几件事情:

(1)查看系统的使用状态。

要看目前有谁在线,可以用who命令。要看网络的联机状态,可以用netstat-a命令。要看后台执行那个的程序可以执行ps-aux命令。

(2)通知在线用户的关机时刻

这个时候可以使用shutdown命令

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Shutdown命令:
语法:shutdown[-t秒][-arkhncfF]时间 警告消息
-t:后面加描述表示过几秒之后关机。
-k:不是真的关机,仅仅发出警告消息。
-r:将系统服务停掉之后重启。
-h:将系统服务停掉之后立即关机。
-f:关机并开机之后,强制跳过fsck的磁盘检查。
-F:系统重启之后,强制进行fsck的磁盘检查。
-c:取消已经进行的shutdown命令内容。
 
另外,重启关机命令有reboot、halt、poweroff。其实在默认情况下,都完成一样的工作。
halt先调用shutdown,而shutdown最后调用halt。不过,shutdown可以根据目前已经启动的服务来逐次关闭服务后才关机;而halt能够在不理会目前系统情况下,进行硬件关机的特殊功能。
 
除了这些,还有一个关机命令是init  0
init是切换执行等级的命令。Linux共有 7 种执行等级,比较重要的是下面 4 种等级:
run level  0 :关机
run level  3 :纯命令行模式
run level  5 :含有图形界面模式
run level  6 :重启

           十九、让自己的应用不被kill掉
可以在frameworks\base\services\java\com\android\server\am\ActivityManagerService.java这个类的forceStopPackage中加一个条件:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
public void forceStopPackage( final String packageName) {
         if (checkCallingPermission(android.Manifest.permission.FORCE_STOP_PACKAGES)
                 != PackageManager.PERMISSION_GRANTED) {
             String msg =  "Permission Denial: forceStopPackage() from pid="
                     + Binder.getCallingPid()
                     ", uid=" + Binder.getCallingUid()
                     " requires " + android.Manifest.permission.FORCE_STOP_PACKAGES;
             Slog.w(TAG, msg);
             throw new SecurityException(msg);
         }       
         long callingId = Binder.clearCallingIdentity();
         try {
             IPackageManager pm = ActivityThread.getPackageManager();
             int pkgUid = - 1 ;
             synchronized ( this ) {
                 try {
                     pkgUid = pm.getPackageUid(packageName);
                 catch (RemoteException e) {
                 }
                 if (pkgUid == - 1 ) {
                     Slog.w(TAG,  "Invalid packageName: " + packageName);
                     return ;
                 }
                 //begin:加入一个判断条件
                 if (packageName.equals( "你的进程名" )) {
                     return ;
                 }
                 //end: 加入一个判断条件                                forceStopPackageLocked(packageName, pkgUid);
             }
         finally {
             Binder.restoreCallingIdentity(callingId);
         }
     }

这样的话在任务管理器里可以保证KISS不掉的;
还有在这个方法上还有个方法clearApplicationUserData中保证如果是该进程就不让调用forceStopPackage()方法。
另:其他方法:
1,首先在你的service的onDestory方法里面写上启动你自己的代码,为什么要写这个?因为如果用户是在设置->应用程序->正在运行服务这里面杀掉你service的话会调用到onDestory方法的,这里就可以启动了,
2:监听屏幕关闭广播,屏幕已关闭,就启动服务。
3:监听屏幕解锁广播,一样的道理,这样,基本上,你的service就达到永不停止了。对用户来说有点变态,但很多软件都这样。
     二十、EditText获取焦点
?
1
EditText.requestFoucus()
    二十一、获取手机屏幕分辨率
?
1
2
3
4
5
6
7
DisplayMetrics  dm =  new DisplayMereics();
 
         getWindowManager().getDefaultDisplay().getMetrics(dm);
 
         float width = dm.widthPixels * dm.density;
 
         float height = dm.heightPixels * dm.density
     在这里问什么要乘以  dm.density   了,是因为通过dm.widthPixels的到的结果始终是320,不是真实的屏幕分辨率,所以要乘以dm.density得到真实的分辨率。
     二十二、在Activity里面播放背景音乐
?
1
2
3
4
5
6
7
8
public void onCreate(Bundle savedInstanceState) {
              super .onCreate(savedInstanceState);
              setContentView(R.layout.mainlay);
              mediaPlayer = MediaPlayer.create( this , R.raw.mu);
              mediaPlayer.setLooping( true );
              mediaPlayer.start();
 
                    }


      二十三、让程序的界面不随机器的重力感应而翻转

                 第一种方法,在manifast文件里面

?
1
2
3
< activity
   android:screenOrientation = "portrait" >
   </ activity >

                   第二种,在代码里面

?
1
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

     二十四、使activity全屏显示

?
1
2
3
requestWindowFeature(Window.FEATURE_NO_TITLE);
         getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,     
                 WindowManager.LayoutParams. FLAG_FULLSCREEN);

        二十五、在RelativeLayout中使selector要注意点

         关于selector的使用方法,可以参考http://blog.csdn.net/aomandeshangxiao/article/details/6759576这篇文章,今天,遇到在RelativeLayout中添加background为selector后没有反应的问题,寻摸了很长时间,一直没有找到原因,其实只要加上一句代码就完全可以解决:

?
1
<span>RelativeLayout 里面加上android:clickable= "true" </span>

这样,RelativLayout就会出现在selector里面定义的效果。


   二十六、显示或隐藏虚拟键盘

?
1
2
3
4
5
6
7
显示:
InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,  0 );
 
隐藏:
InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));
imm.hideSoftInputFromWindow(m_edit.getWindowToken(),  0 );

   二十七、退出程序时清除通知中信息  

?
1
2
NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.cancelAll();

     二十八、创建快捷方式

?
1
2
3
4
5
Intent intent= new Intent();
//设置快捷方式的图标
intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext( this , R.drawable.img));
//设置快捷方法的名称
intent.putExtra(Intent.EXTRA_SHORTCUT_NAME,  "点击启动哥的程序" );             //设置点击快键图标的响应操作
?
1
2
3
4
intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT,  new Intent( this ,MainActivity. class ));
//传递Intent对象给系统
setResult(RESULT_OK, intent);
finish();

  

   二十九、获取文件中的类名:

?
1
2
3
4
5
6
7
8
String path = context.getPackageManager().getApplicationInfo(
                                         context.getPackageName(),  0 ).sourceDir;
                         DexFile dexfile =  new DexFile(path);
                         Enumeration<String> entries = dexfile.entries();
                         while (entries.hasMoreElements()) {
                                 String name = (String) entries.nextElement();
                                 ......
                         }

 来自:http://blog.csdn.net/aomandeshangxiao/article/details/7006211

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值