zoukankan      html  css  js  c++  java
  • android查缺补漏

    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

    PackageManager packageManager =getPackageManager();

    List<ResolveInfo> activities = packageManager.queryIntentActivities(intent,0);

    boolean isIntentSafe = activities.size()>0;

    6. startActivityForResult ---- onActivityResult
      启动一个Activity,返回时处理结果

    7. location Manager
      首先要申请权限---
    <uses-permissionandroid:name="android.permission.ACCESS_COARSE_LOCATION"/>
    LocationManager locationManager =(LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
    LocationProvider provider =locationManager.getProvider(LocationManager.GPS_PROVIDER);

    判断GPS定位是不是可用
    protectedvoid onStart(){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.

    LocationManager locationManager =(LocationManager) getSystemService(Context.LOCATION_SERVICE);

    finalboolean gpsEnabled = 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()

    }

    }

    privatevoid enableLocationSettings()

    {

      Intent settingsIntent =newIntent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);   startActivity(settingsIntent);

    }
    
    

    8. 是否有可用的网络

    An InputStream is a readable source of bytes. Once you get an InputStream, 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;...

    Bitmap bitmap =BitmapFactory.decodeStream(is);

    ImageView imageView =(ImageView) findViewById(R.id.image_view);

    imageView.setImageBitmap(bitmap);
    
    

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

    
    
    // Reads an InputStream and converts it to a String.

    public String readIt(InputStream stream,int len)throws IOException,UnsupportedEncodingException
    {

       Reader reader =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)传送二进制数据
        Intent shareIntent =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中处理数据,这里我觉得可以判断是不是登陆,如果没有登陆就让用户登陆就可以,比如微博的处理逻辑应该就是这样的。
      void onCreate (Bundle savedInstanceState)
      
    {...
        
    // Get intent, action and MIME type
        
    Intent intent = getIntent();
        
    String action = intent.getAction();
        
    String type = 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 int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight)
    {
    // Raw height and width of image
    final int height = options.outHeight;
    final int width = options.outWidth;
    int inSampleSize =1;
    if(height > reqHeight || width > reqWidth)
    {
    if(width > height)
    {
      inSampleSize
    =Math.round((float)height /(float)reqHeight);
    }else{
      inSampleSize
    =Math.round((float)width /(float)reqWidth);
    }
    }
    return inSampleSize;
    }
    (2)
    public static Bitmap decodeSampledBitmapFromResource(Resources res,int resId,int reqWidth,int reqHeight)

    {

    // First decode with inJustDecodeBounds=true to check dimensions

       final BitmapFactory.Options options =newBitmapFactory.Options(); options.inJustDecodeBounds =true;
    BitmapFactory.decodeResource(res, resId, options);
    // Calculate inSampleSize options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
    // Decode bitmap with inSampleSize set options.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大小, 这样就可以存入一些图片












  • 相关阅读:
    Laravel5.1学习笔记15 数据库1 数据库使用入门
    Laravel5.1学习笔记i14 系统架构6 Facade
    Laravel5.1学习笔记13 系统架构5 Contract
    Laravel5.1学习笔记12 系统架构4 服务容器
    Laravel5.1学习笔记11 系统架构3 服务提供者
    JavaScript之“创意时钟”项目
    JQuery轮播图
    SQL Server之增删改操作
    jQuery之基本选择器Practice
    JQuery---选择器、DOM节点操作练习
  • 原文地址:https://www.cnblogs.com/zhanglanyun/p/2708997.html
Copyright © 2011-2022 走看看