android查缺补漏

摘要:
这意味着您为xhdpi设备生成200x200图像,您应该为hdpi、100x100formdpi和75x75设备生成150x150的相同资源。然后,将文件放在相应的rawableresource目录中:MyProject/res/rawablexhdpi/awesomeimage.pngdrawable-hdpi/awesome image.png drawable-mdpi/awisomeimage。pngdrawable资源目录-ldpi/awesomeimage.pngAnytimeyoureference@drawable/很棒的图像,系统会根据屏幕的灵敏度选择合适的位图。4.onSaveInstanceState--onRestoreInstanceState当您的活动在先前建立后新创建时;列表<ResolveInfo>活动=packageManager。queryIntentActivities;booleanisIntentSafe=活动。大小()˃0;6.startActivityForResult----onActivityResult启动一个活动并在返回时处理结果7.LocationManager必须首先申请权限----LocationManagerlocationManager=this。获取系统服务;LocationProvider=locationManager。获取提供商;判断GPS定位是否可以使用protectedvoid onStart(){super.onStart因为系统调用//此方法,用户返回活动,从而确保活动从停止状态恢复时所需的//位置。LocationManagerlocationManager=获取系统服务;finalboolingpsEnabled=位置管理器。isProviderEnabled;如果(!

1 . Service 有两种方式:startService()--- stopService()

bindService()----unbindService()

区别:第一种方式调用者和服务之间没有关系,即使调用者退出之后,服务还是可以运行,第二种方式调用者退出之后,服务也就终止了。

2.AIDL:实现进程之间的通信

(1) create the .aidl 文件

(2) implements the interface

3.字符集,可以把按钮的文本放在string.xml 中,运行时,程序可以根据设备的语言来运行相应的字符。创建多种大小的图片,以适应不同的屏幕

This means that if you generate a 200x200 image for xhdpi devices, you should generate the same resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices.

Then, place the files in the appropriate drawable resource directory:

MyProject/
    res/
        drawable-xhdpi/
            awesomeimage.png
        drawable-hdpi/
            awesomeimage.png
        drawable-mdpi/
            awesomeimage.png
        drawable-ldpi/
            awesomeimage.png

Any time you reference@drawable/awesomeimage, the system selects the appropriate bitmap based on the screen's density.

4. onSaveInstanceState--- onRestoreInstanceState When your activity is recreated after it was previously destroyed

如果刚销毁,在创建的话,就从这里恢复

5.检查内置intent是否会被响应,如果不做判断,应用程序很有可能就会Crash

PackageManagerpackageManager =getPackageManager();
List<ResolveInfo>activities =packageManager.queryIntentActivities(intent,0);
booleanisIntentSafe =activities.size()>0;
6. startActivityForResult ---- onActivityResult
启动一个Activity,返回时处理结果
7. location Manager
首先要申请权限---
<uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/>
LocationManagerlocationManager =(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
LocationProviderprovider =locationManager.getProvider(LocationManager.GPS_PROVIDER);
判断GPS定位是不是可用
protectedvoidonStart(){super.onStart();
// This verification should be done during onStart() because the system calls// this method when the user returns to the activity, which ensures the desired// location provider is enabled each time the activity resumes from the stopped state.
LocationManagerlocationManager =(LocationManager)getSystemService(Context.LOCATION_SERVICE);
finalbooleangpsEnabled =locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
if(!gpsEnabled){// Build an alert dialog here that requests that the user enable// the location services, then when the user clicks the "OK" button,// call enableLocationSettings()
}
}
privatevoidenableLocationSettings()
{
IntentsettingsIntent =newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);  startActivity(settingsIntent);
}

8. 是否有可用的网络

AnInputStreamis a readable source of bytes. Once you get anInputStream, it's common to decode or convert it into a target data type. For example, if you were downloading image data, you might decode and display it like this:

InputStreamis=null;...
Bitmapbitmap =BitmapFactory.decodeStream(is);
ImageViewimageView =(ImageView)findViewById(R.id.image_view);
imageView.setImageBitmap(bitmap);

In the example shown above, theInputStreamrepresents the text of a web page. This is how the example converts theInputStreamto a string so that the activity can display it in the UI:

// Reads an InputStream and converts it to a String.
publicStringreadIt(InputStreamstream,intlen)throws IOException,UnsupportedEncodingException
{
Readerreader =null;reader =new InputStreamReader(stream,"UTF-8");
char[]buffer =newchar[len];reader.read(buffer);
return new String(buffer);
}
9.创建可重复利用的layouts
在程序中,经常会遇到一些需要重复利用的一些小的控件,最好的方法就是先把他们保存下来,这样就实现了重复利用。<include> Tag.
<include layout="@layout/titlebar" />
<merge > 也可以消除多余的viewGroup,把它们组合在一起
10.ListView优化中方法之 ViewHolder----------------以下方式结合效率最高
static class viewHolder
{
TextView text;
ImageView icon;  
}
viewHolder holder;
if(convertview == null)
{
holder = new viewHolder();
holder.text=...
holder.icon=...
convertview.setTag(holder);
}
else
{
holder = (viewHolder) convertView.getTag();
}
11.让程序响应硬件的声音按钮
(1)首先要注册一个 receiver 在manifest中
<receiver ...
<intent-filter>
<action android:name="android.intent.action.MEDIA_BUTTON"/>
<intent-filter>
</receiver>
public class RemoteControlReceiver extends BroadcastReceiver
{
public void onReceive(Context context , Intent intent)
{
if(Intent.ACTION_MEDIA_BUTTON.equals(intent.getAction()))
{
KeyEvent event=(KeyEvent) intent.getPracelableExtra(Intent.EXTRA_KEY_EVENT);
if(KeyEvent.KEYCODE_MEDIA_PLAY == event.getKeyCode())
{
//handle key press
}
}
}
}
绑定服务,监听button
AudioManager am = mContext.getSystemService(Context.AUDIO_SERVICE);
am.registerMediaButtonEventReceiver(RemoteControlReceiver);
am.unregisterMediaButtonEventReceiver(...);
12.监听电池,这里有两种方式 第一种是在 manifest中定义receiver ,第二种是 注册服务
private batteryReceiver = new Receiver()
{
}
IntentFilter intent= new IntentFilter();
registerReceiver(batteryReceiver,intent);
13. 优化view,不要在view中分配内存,这样会引起抖动,调用invalidate时,尽量调用带4个参数的版本,这样就可以
不是更新整个view,而只是刷新自己定义的部分view。在android 3.0 以后引入了GPU加速,同样可以用来给view加速。
14.一个Activity向另一个Activity传送数据
Intent sendIntent = new Intent();
sendIntent.setAction(Intent.SEND_ACTION);
sendIntent.putExtra(Intent.EXTRA_TEXT,"this is a text!");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent,getResources().getText());
(2)传送二进制数据
IntentshareIntent =newIntent();
shareIntent.setAction(Intent.ACTION_SEND);
shareIntent
.putExtra(Intent.EXTRA_STREAM,uriToImage);
shareIntent
.setType("image/jpeg");
startActivity
(Intent.createChooser(shareIntent,getResources().getText(R.string.send_to)));
怎么得到一张图片的URI呢?
Uri uri = Uri.fromFile();
15.从另外一个APP接收数据
在manifest中定义intentFilter
<activity android:name=".ui.MyActivity">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="image/*"/>
</intent-filter>
... ...
在onCreate中处理数据,这里我觉得可以判断是不是登陆,如果没有登陆就让用户登陆就可以,比如微博的处理逻辑应该就是这样的。
voidonCreate (BundlesavedInstanceState)
{...
// Get intent, action and MIME type
Intentintent =getIntent();
Stringaction =intent.getAction();
Stringtype =intent.getType();
if(Intent.ACTION_SEND.equals(action)&&type !=null)
{
if("text/plain".equals(type))
{
handleSendText(intent);
// Handle text being sent
}
elseif(type.startsWith("image/"))
{
handleSendImage
(intent);
// Handle single image being sent}
必须检查MIME的类型,
16.检查兼容性问题,比如 4.0的ActionBar 在 3.0以下的版本中是无法运行,那么我们需要去建立代理类,然后根据相应的sdk版本去创建类,
这样就能保证兼容性。
17.下载图片的时候,要根据ImageView的大小来采样,下载,这样才会节省流量
(1)根据目标来计算Sample的大小
public static intcalculateInSampleSize(BitmapFactory.Optionsoptions,intreqWidth,intreqHeight)
{
// Raw height and width of image
final intheight =options.outHeight;
final intwidth =options.outWidth;
intinSampleSize =1;
if(height >reqHeight ||width >reqWidth)
{
if(width >height)
{
inSampleSize
=Math.round((float)height /(float)reqHeight);
}else{
inSampleSize
=Math.round((float)width /(float)reqWidth);
}
}
returninSampleSize;
}
(2)
public static BitmapdecodeSampledBitmapFromResource(Resourcesres,intresId,intreqWidth,intreqHeight)
{
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Optionsoptions =newBitmapFactory.Options();options.inJustDecodeBounds =true;
BitmapFactory.decodeResource(res,resId,options);
// Calculate inSampleSizeoptions.inSampleSize =calculateInSampleSize(options,reqWidth,reqHeight);
// Decode bitmap with inSampleSize setoptions.inJustDecodeBounds =false;returnBitmapFactory.decodeResource(res,resId,options);
}
(3)这样就可以根据ImageView的大小来把Bitmap加载到内存中了
mImageView.setImageBitmap(decodeSampledBitmapFromResource(getResources(),R.id.myimage,100,100));
(4)如果是在网络上来下载图片的话, 用 AsyncTask 来下载,不用 UI 线程。
(5) 下载完之后可以配置缓存,缓存的大小设置为可用内存的1/8大小, 这样就可以存入一些图片

免责声明:文章转载自《android查缺补漏》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇dd命令详解Web开发-表单验证下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

android 之 桌面的小控件AppWidget

AppWidget是创建的桌面窗口小控件,在这个小控件上允许我们进行一些操作(这个视自己的需要而定)。作为菜鸟,我在这里将介绍一下AppWeight的简单使用。 1.在介绍AppWidget之前,我们先来了解一下PendingIntent和RemoteViews; PendingIntent:A description of an Intent and t...

在Android上常用的定时器 AlarmManager

AlarmManager的作用文档中的解释是:在特定的时刻为我们广播一个指定的Intent。简单的说就是我们设定一个时间,然后在该时间到来时,AlarmManager为我们广播一个我们设定的Intent,常用方法有五个: (1)set(int type,long startTime,PendingIntent pi); 该方法用于设置一次性闹钟,第一个参数...

Android Service和广播

前言: 我们都知道Android的四大基本组件:Activity、ContentProvider、Service以及BroadcastReceiver,前面的两个我们在前几篇已经具体讲解了,今天这一天我们就把后两者的使用具体说一下,由于Service和BroadcastReceiver常常一起使用,所以我们一起来学习。     一.Service的使用 S...

Android应用的电量消耗和优化的策略

 对于Android移动应用的开发者来说,耗电量的控制一直是个老大难问题。      我们想要控制耗电量,必须要有工具或者方法比较准确的定位应用的耗电情况。下面,我们先来分析下如何计算android应用的耗电量。    在android自带的设置里面有电量计算的界面,如下图: <ignore_js_op>    我们看下是如何实现的:​    ...

ANR的原理分析和简单总结

前言ANR(Application Not Responding),应用无响应,这个可能每个人都碰到过。 该篇主要简单总结下,ANR的几种常见类型(输入事件、广播接收器、Service、ContentProvider),以及ANR一般如何产生的及如何避免。 最后重点是通过源码 了解这几种类型 是如何产生ANR、超时时间是怎么来的、ANR后如何处理的等。 关...

Android Exception 10(server)' ~ Channel is unrecoverably broken and will be disposed!)

08-11 19:22:35.028: W/MemoryDealer(2123): madvise(0x43e16000, 12288, MADV_REMOVE) returned Operation not supported on transport endpoint08-11 19:22:35.038: W/InputDispatcher(2714)...