android 实用代码片段整理


android 常用代码片段,前1-10条是从网上摘录,向原作者致谢。后面为自己整理。

1、设置窗口格式为半透明

getWindow().setFormat(PixelFormat.TRANSLUCENT);

2、Android中在非UI线程里更新View的不同方法:

* Activity.runOnUiThread( Runnable )

* View.post( Runnable )

* View.postDelayed( Runnable, long )

* Hanlder

3、全屏显示窗口

requestWindowFeature(Window.FEATURE_NO_TITLE);

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

4、取得屏幕大小

方法A:

WindowManager windowManager = getWindowManager();

Display display = windowManager.getDefaultDisplay();

hAndW[0] = display.getWidth();

hAndW[1] = display.getHeight();

方法B:

DisplayMetrics dm = new DisplayMetrics();

getWindowManager().getDefaultDisplay().getMetrics(dm);

hAndW[0] = dm.widthPixels;

hAndW[1] = dm.heightPixels;

5、调浏览器 载入网址

Uri uri = Uri.parse("http://www.google.com");

Intent it = new Intent(Intent.ACTION_VIEW, uri);

startActivity(it);

6、取得内存大小

ActivityManager.MemoryInfo outInfo = new ActivityManager.MemoryInfo();

activityManager.getMemoryInfo(outInfo);

//可用内存

outInfo.availMem

//是否在低内存状态

outInfo.lowMemory

取得ScrollView的实际高度

scrollview.getHeight()

scrollview.getMeasuredHeight()

scrollview.compute()

scrollview.getLayoutParams().height

7、监听App安装/卸载事件

A.Define a class derived from class BroadcastReceiver;

B.Register broadcast receiver;

MyBroadcastReceiver myReceiver = new MyBroadcastReceiver();

IntentFilter filter = new IntentFilter(Intent.ACTION_PACKAGE_INSTALL);

filter.addAction(Intent.ACTION_PACKAGE_REMOVED);

filter.addAction(Intent.ACTION_PACKAGE_ADDED);

filter.addAction(Intent.ACTION_PACKAGE_CHANGED);

filter.addAction(Intent.ACTION_PACKAGE_RESTARTED);

...

filter.addDataScheme("package"); //This line is very important. Otherwise, broadcast can't be received.

registerReceiver(myReceiver, filter);

Notes: The package name is Intent.mData. Intent.mData is not available in SDK 1.0, but it can be retrieved by calling Intent.getDataString();

8、取得IP地址

A.

//Connect via WIFI 通过wifi

WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);

WifiInfo wifiInfo = wifiManager.getConnectionInfo();

int ipAddress = wifiInfo.getIpAddress();

B.

//Connect via GPRS通过gprs

public String getLocalIpAddress(){

try{

for(Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){

NetworkInterface intf = en.nextElement();

for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();){

InetAddress inetAddress = enumIpAddr.nextElement();

if (!inetAddress.isLoopbackAddress()){

return inetAddress.getHostAddress().toString();

}

}

}

}catch (SocketException ex){

Log.e(S.TAG, ex.toString());

}

return null;

}

9、ListView 后面adapter数据已更改,但是ListView没有收到Notification

首先,必须将 更新adapter数据的代码放在:Handler.post(Runnable)方法中执行;

然后,如果Adapter数据的来源如果是cursor(CursorAdapter)的话 可以cursor.requery一下,如果是别的可以强制调用一下notifyChange, notifyChange 会调用 invalidate 进行重绘;

10、模拟HOME键

Intent i=new Intent(Intent.ACTION_MAIN);

i.addCategory(Intent.CATEGORY_HOME);

i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

context.startActivity(i);

11、设置焦点

editText.setFocusable(true);

editText.requestFocus();

editText.setFocusableInTouchMode(true);
12:在一个应用中去调用另一个app
例如:
if (Utils.isAvilible(context, "com.netschool.main.ui"))
		{
		    Intent i = new Intent();
		    ComponentName cn = new ComponentName("com.netschool.main.ui",
			    "com.netschool.main.ui.SplashScreenActivity");
		    i.setComponent(cn);
		    startActivity(i);
		}
		else
		{
		    Uri uri = Uri.parse(context.getString(R.string.url_zhuanti_download));
		    Intent it = new Intent(Intent.ACTION_VIEW, uri);
		    it.setData(uri);
		    startActivity(it);
		}

13:andoroid TextView 显示特殊字符


 String course_jianjie ="xxxxxxxxxx";
//字符串中有 \r\n 需要替换为 <br/>
	    String temp =course_jianjie.replaceAll("\\r\\n", "<br/>");
//用html 来显示
	    CharSequence styledText = Html.fromHtml(temp); 
//设置要显示的控件
	    mCourseDescTv.setText(styledText);
14:使用NotificationManager触发多个Notification,只显示最后一个的问题
只要每个不同的Intent对应传递一个独立的ID就可以了,以上函数修改如下(增加ID参数):

private Notification genreNotification(Context context, int icon, String tickerText, String title, String content, Intent intent, int id){
   
	Notification notification = new Notification(icon, tickerText, System.currentTimeMillis());
   
	// 问题就在这里的id了
        PendingIntent pendIntent = PendingIntent.getActivity(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
  
notification.setLatestEventInfo(context, title, content, pendIntent);
     
	notification.flags |= Notification.FLAG_AUTO_CANCEL;
     
return notification;
    }



...
mNotificationManager.notify(ID_1, 
            
genreNotification(mContext, ICON_RES, 
                 
notifyText1, notifyTitle1, notifyText1, intent_1, ID_1));
...
mNotificationManager.notify(ID_2, 
     
genreNotification(mContext, ICON_RES, 
                      
notifyText2, notifyTitle2, notifyText2, intent_2, ID_2));

...
mNotificationManager.notify(ID_3, 
    
genreNotification(mContext, ICON_RES, 
                   
notifyText3, notifyTitle3, notifyText3, intent_3, ID_3));



15: adb 命令截图

adb shell /system/bin/screencap -p /sdcard/screenshot.png(保存到SDCard)
adb pull /sdcard/screenshot.png d:/screenshot.png(保存到电脑)
  
16:跳出for循环

OK:
 for(int i=0;i<100;i++){
 if(i==10){
 break OK;
 }
 
 }

17:使用viewPager加载超过3页 
有时会报出 The specified child already has a parent. You must call removeView() on the child's parent first 的错误
此时:可以简单的用
mViewPager.setOffscreenPageLimit(3);解决
备注:单这不是万能之策,也不是优选之策

18:
	/**
	 * @Description:调节音量大小
	 * @author: jrh
	 * @date: 2014-11-13 下午3:06:46
	 * @return: void
	 * @param percent
	 */
	private void onVolumeSlide(float percent)
	{
	    if (mVolume == -1)
	    {
		mVolume = mAudioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
		if (mVolume < 0)
		{
		    mVolume = 0;
		}
		mOperationBg.setImageResource(R.drawable.video_volumn_bg);
		mVolumeBrightnessLayout.setVisibility(View.VISIBLE);
	    }
	    int index = (int) ((percent * mMaxVolume) + mVolume);
	    if (index > mMaxVolume)
	    {
		index = mMaxVolume;// 最大音量

	    }
	    else if (index < 0)
	    {
		index = 0;// 静音
	    }

	    // 变更声音
	    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, index, 0);

	    // 变更进度条
	    ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
	    lp.width = findViewById(R.id.operation_full).getLayoutParams().width * index /
		    mMaxVolume;
	    mOperationPercent.setLayoutParams(lp);

	}

19	/**
	 * @Description:调节屏幕亮度
	 * @author: jrh
	 * @date: 2014-11-13 下午3:17:40
	 * @return: void
	 * @param percent
	 */
	private void onBrightnessSlide(float percent)
	{
	    if (mBrightness < 0)
	    {
		mBrightness = getWindow().getAttributes().screenBrightness;
		if (mBrightness <= 0.00f)
		{
		    mBrightness = 0.50f;
		}
		else if (mBrightness < 0.01f)
		{

		    mBrightness = 0.01f;

		}
		// 显示
		mOperationBg.setImageResource(R.drawable.video_brightness_bg);
		mVolumeBrightnessLayout.setVisibility(View.VISIBLE);

	    }

	    WindowManager.LayoutParams lpa = getWindow().getAttributes();
	    lpa.screenBrightness = mBrightness + percent;
	    if (lpa.screenBrightness > 1.0f)
	    {
		lpa.screenBrightness = 1.0f;// 最亮
	    }
	    else if (lpa.screenBrightness < 0.01f)
	    {

		lpa.screenBrightness = 0.01f;
	    }
	    getWindow().setAttributes(lpa);

	    ViewGroup.LayoutParams lp = mOperationPercent.getLayoutParams();
	    lp.width = (int) (findViewById(R.id.operation_full).getLayoutParams().width * lpa.screenBrightness);
	    mOperationPercent.setLayoutParams(lp);

	}
20:viewpager + fragment 布局时有时会报下面的错误
11-14 13:52:45.266: E/AndroidRuntime(4561): FATAL EXCEPTION: main
11-14 13:52:45.266: E/AndroidRuntime(4561): java.lang.NullPointerException
11-14 13:52:45.266: E/AndroidRuntime(4561): 	at android.support.v4.app.FragmentManagerImpl.saveFragmentBasicState(FragmentManager.java:1576)
解决方法:
在继承fragment的里面重写
    @Override
    public void onSaveInstanceState(Bundle outState)
    {
        // TODO Auto-generated method stub
        super.onSaveInstanceState(outState);
        setUserVisibleHint(true);
    }


21:service 服务并不是另开一个线程 ,处理service 时最好单独开线程进行处理
22:不要在receiver 里面处理耗时工作
23:如果布局时: 想要在字中间加空格 可以使用 " ;" html 的空格实体编号添加。注意:一个汉字相当于 两个空格字符。

24:volatile java 关键字 保证了线程可以读取其他线程的写入值、
   Thread.join()  方法保证了该线程优先执行 其他线程等待
   Thread.yied() 方法 让出时间让其它线程可以执行
   如何停止线程?
   不要随意调用 Thread.stop()方法 ,该方法不是正确的停止线程方法 会导致一些其他的问题
   使用推出的旗杆标志 :如设置 boolean 值等 
   结束时及时清理资源
   使用代码逻辑来使得线程执行结束 (使thread 线程内部的代码 任务执行完毕)

25:如何在TextVeiw下加入一条线

TextView tv = new TextView();
tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);

26:android 4.4 以上无法在外置SD卡创建文件夹
 解决方法:
  @A   File dirFile = new File(temp.trim());
	if (!dirFile.exists())
	{// 对于4.4以上版本特别重要
	    getApplicationContext().getExternalFilesDir(null);
	    dirFile.mkdirs();
	}
   @B   文件路径:/android/data/包名/
27:在:
 android:targetSdkVersion="18" 

 随着版本号的改变 界面元素,显示方式是不一样的

28:android 获取所有存储卡的地址
 	private String[] getSdCard() {
		StorageManager sm = (StorageManager) getSystemService(Context.STORAGE_SERVICE);
		String[] paths = null;
		try {
			paths = (String[]) sm.getClass().getMethod("getVolumePaths", null)
					.invoke(sm, null);
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (NoSuchMethodException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return paths;
	}


29:百度地图 出现问题
A:报错
java.lang.UnsatisfiedLinkError: Couldn't load BaiduMapSDK_
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值