关于近段时间Android学习的一些感想

    很久没有写博客了,也算应胡哥的要求,更多的是对最这段时间自己的学习和生活的一个回顾和总结吧,无关技术。
    想想自己这段时间,特别是最近这几天,确实是有点过于放松了。感觉总是不在状态,好像慢慢地没有了刚来公司时那种冲劲,那么的毅然决然。胡哥的这次博客要求,也算给自己提了个醒吧。不管怎么样,坚持下去,才有机会,不能刚刚有点起步,就开始松懈,我确实该要醒悟。就像乌拉多恩的歌曲《鸟人》里写的那样,要么飞,要么坠落,这是生命的规则!
    虽然无关技术,既然说到了Android,也就说说这段时间Android的学习吧。
    一开始开始接触Android,是因为赵欢老师的《ARM体系结构与编程》的课程设计,要求我们做个开发项目。在这之前,我想我连菜鸟都算不上,简直是一穷二白,什么都不会。只剩下2个星期的时候,我们(我和另一个同学组成一个项目小组)决定做个基于Android平台的关于GPS的百度地图小项目。做之前,我们连Android工程都还不会建。花了一个星期,各种百度,各种看视频、查资料,总算是把开发环境搭建好,学会了第一个Android工程:《Hello World!》,大概了解到了,一个Android工程,到底包括那些工程文件,哪些文件有什么作用,勉强算是入了门。然后又花了一个星期,我的同学负责界面以及功能的设计,我负责敲代码实现,每天从上午10点开始,到晚上9点,除了吃饭时间,基本就是坐在电脑前,各种百度,要实现一个什么样的功能,不会?百度!运行程序出问题了?百度!总之就是不断的尝试以及各种百度中,慢慢的拼凑成了一个“项目”!
   不管它的功能多么的不完善,不管它多么的不像是个真正的项目,但是,两个星期,从不会到有所了解,从无到有,它真的就诞生在了我们的手上!我的同学给它起了个名字:无花果!象征着我们整个项目开发的过程:没有开花就结果!
    现在回想起那几天,不管我们是多么的菜,多么的不懂技术,但是有了一个明确的目标,有了来自课程的压力,那种一往无前的冲劲,不管是多么的横冲直撞,我们总算是做了出来,不管结果是多么的不专业,不管结果是多么的不堪入目,起码,这是一个从无到有的开始,这是一颗无花果!
    今天算是给自己提个醒吧。加油,我能做到!
    (代码和文档就当是留念了)
网络检查以及百度map的key验证
public class XwhgApplication extends Application {
	
    private static XwhgApplication mInstance = null;
    public boolean m_bKeyRight = true;
    BMapManager mBMapManager = null;

    public static final String strKey = "A7Lb6Mo0veE04SS9321lX8c9";
	
	@Override
    public void onCreate() {
	    super.onCreate();
		mInstance = this;
		initEngineManager(this);
	}
	
	public void initEngineManager(Context context) {
        if (mBMapManager == null) {
            mBMapManager = new BMapManager(context);
        }

        if (!mBMapManager.init(strKey,new MyGeneralListener())) {
            Toast.makeText(XwhgApplication.getInstance().getApplicationContext(), 
                    "BMapManager  初始化错误!", Toast.LENGTH_LONG).show();
        }
	}
	
	public static XwhgApplication getInstance() {
		return mInstance;
	}
	
	
	// 常用事件监听,用来处理通常的网络错误,授权验证错误等
    static class MyGeneralListener implements MKGeneralListener {
        
        @Override
        public void onGetNetworkState(int iError) {
            if (iError == MKEvent.ERROR_NETWORK_CONNECT) {
                Toast.makeText(XwhgApplication.getInstance().getApplicationContext(), "您的网络出错啦!",
                    Toast.LENGTH_LONG).show();
            }
            else if (iError == MKEvent.ERROR_NETWORK_DATA) {
                Toast.makeText(XwhgApplication.getInstance().getApplicationContext(), "输入正确的检索条件!",
                        Toast.LENGTH_LONG).show();
            }
            // ...
        }

        @Override
        public void onGetPermissionState(int iError) {
        	//非零值表示key验证未通过
            if (iError != 0) {
                //授权Key错误:
                Toast.makeText(XwhgApplication.getInstance().getApplicationContext(), 
                        "请在 DemoApplication.java文件输入正确的授权Key,并检查您的网络连接是否正常!error: "+iError, Toast.LENGTH_LONG).show();
                XwhgApplication.getInstance().m_bKeyRight = false;
            }
            else{
            	XwhgApplication.getInstance().m_bKeyRight = true;
            	Toast.makeText(XwhgApplication.getInstance().getApplicationContext(), 
                        "key认证成功", Toast.LENGTH_LONG).show();
            }
        }
    }
}


百度map的Bitmap创建
public class XwhgBMapUtil {
    	
	/**
	 * @param view
	 * @return
	 */
	public static Bitmap getBitmapFromView(View view) {
        view.destroyDrawingCache();
        view.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED));
        view.layout(0, 0, view.getMeasuredWidth(), view.getMeasuredHeight());
        view.setDrawingCacheEnabled(true);
        Bitmap bitmap = view.getDrawingCache(true);
        return bitmap;
	}
}



登录界面模块
public class LoadingActivity extends Activity {
    private ImageView welcomeImg = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.loadingui);
        welcomeImg = (ImageView) this.findViewById(R.id.loadding);
        AlphaAnimation anima = new AlphaAnimation(0.3f, 1.0f);
        anima.setDuration(5000);// 设置动画显示时间
        welcomeImg.startAnimation(anima);
        anima.setAnimationListener(new AnimationImpl());

    }

    private class AnimationImpl implements AnimationListener {

        @Override
        public void onAnimationStart(Animation animation) {
            welcomeImg.setBackgroundResource(R.drawable.load);
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            skip(); // 动画结束后跳转到别的页面
        }

        @Override
        public void onAnimationRepeat(Animation animation) {

        }

    }

    private void skip() {
        startActivity(new Intent(this, MainActivity.class));
        finish();
    }
}

布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >
    <ImageView 
        android:id="@+id/loadding"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_weight="1"/>
</LinearLayout>


主界面部分
public class MainActivity extends Activity {

	private MapView mMapView = null;
	private MapController mMapController = null;
	OverlayTest itemOverlay;
	private TextView  popupText = null;
	private View viewCache = null;
	private View popupInfo = null;
	private OverlayItem mCurItem = null;
	private PopupOverlay   pop  = null;
	private boolean flag = false;
	LocationManager manager;
	Location location;
	
	Button self;
	Button friend;
	Button satellite;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
        //从Android 2.3开始提供了一个新的类StrictMode,可以帮助开发者改进他们的Android应用
		//StrictMode可以用于捕捉发生在应用程序主线程中耗时的磁盘、网络访问或函数调用,可以帮助开发者使其改进程序,
		//使主线程处理UI和动画在磁盘读写和网络操作时变得更平滑,避免主线程被阻塞,导致ANR窗口的发生。
		//代码在Application的OnCreate中添加,这样就能在程序启动的最初一刻进行监控了
        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
        .detectDiskReads()
        .detectDiskWrites()
        .detectNetwork() // 这里可以替换为detectAll() 就包括了磁盘读写和网络I/O
        .penaltyLog() //打印logcat,当然也可以定位到dropbox,通过文件保存相应的log
        .build());
        StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
        .detectLeakedSqlLiteObjects() //探测SQLite数据库操作
        .penaltyLog() //打印logcat
        .penaltyDeath()
        .build()); 
		super.onCreate(savedInstanceState);
		/**
         * 使用地图sdk前需先初始化BMapManager.
         * BMapManager是全局的,可为多个MapView共用,它需要地图模块创建前创建,
         * 并在地图地图模块销毁后销毁,只要还有地图模块在使用,BMapManager就不应该销毁
         */
        XwhgApplication app = (XwhgApplication)this.getApplication();
        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(this);
            /**
             * 如果BMapManager没有初始化则初始化BMapManager
             */
            app.mBMapManager.init(XwhgApplication.strKey,new XwhgApplication.MyGeneralListener());
        }
        /**
          * 由于MapView在setContentView()中初始化,所以它需要在BMapManager初始化之后
          */
        setContentView(R.layout.activity_main);
        mMapView = (MapView)findViewById(R.id.bmapView);
        /**
         * 获取地图控制器
         */
        mMapController = mMapView.getController();
        /**
         *  设置地图是否响应点击事件  .
         */
        mMapController.enableClick(true);
        /**
         * 设置地图缩放级别
         */
        mMapController.setZoom(14);
        /**
         * 显示内置缩放控件
         */
        mMapView.setBuiltInZoomControls(true);
      
        drawgpspoint();
		/**
         * 设定地图中心点
         */
        Drawable mark_st = getResources().getDrawable(R.drawable.icon_st);
        GeoPoint p = new GeoPoint((int)(28.182091 * 1E6), (int)(112.938917* 1E6));
        OverlayItem item = new OverlayItem(p, "起点", "中心点");
		item.setMarker(mark_st);
		//使用setMarker()方法设置overlay图片,如果不设置则使用构建ItemizedOverlay时的默认设置
		//创建IteminizedOverlay
		itemOverlay = new OverlayTest(mark_st, mMapView);
		//将IteminizedOverlay添加到MapView中
		//添加overlay, 当批量添加Overlay时使用addItem(List<OverlayItem>)效率更高
		itemOverlay.addItem(item);
		/**
		 * 将itemOverlay添加到地图中
		 */
		mMapView.getOverlays().clear();
		mMapView.getOverlays().add(itemOverlay);
		mMapView.refresh();
        
        mMapController.setCenter(p);
        
        self = (Button)findViewById(R.id.self);
        friend = (Button)findViewById(R.id.friend);
        satellite = (Button)findViewById(R.id.satellite);
        self.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				mMapView.refresh();
			}
		});
        
        friend.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				
				Intent intent = new Intent();
				intent.setClass(MainActivity.this, SetTimeActivity.class);
				startActivity(intent);
				
				
			}
		});
        
        satellite.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				if(flag==false){
					mMapView.setSatellite(true);
					flag = true;
				}else{
					mMapView.setSatellite(false);
					flag = false;
				}
			}
		});
	}
	
	
	private void drawgpspoint(){
		manager = (LocationManager)getSystemService(LOCATION_SERVICE);
		location = manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
		//监测GPS位置信息的变化
		manager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5*1000, 10, new LocationListener() {
			
			@Override
			public void onStatusChanged(String provider, int status, Bundle extras) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onProviderEnabled(String provider) {
				// TODO Auto-generated method stub
				UpdateOverlay(manager.getLastKnownLocation(provider));
			}
			
			@Override
			public void onProviderDisabled(String provider) {
				// TODO Auto-generated method stub
				UpdateOverlay(null);
			}
			
			@Override
			public void onLocationChanged(Location location) {
				// TODO Auto-generated method stub
				UpdateOverlay(location);
			}
		});
		
	}
	private void UpdateOverlay(Location location){
		if(location == null){
			return ;
		}
		Time t = new Time();
		t.setToNow();
		String year = t.year+"";
		String month = t.month+"";
		String date = t.monthDay+"";
		String hour = t.hour+"";
		String minute = t.minute+"";
		String second = t.second+"";
		String speed = location.getSpeed()+"";
		String info = year+"-"+month+"-"+date+"T"+hour+":"+minute+":"+second+"速度"+speed;
		double mLat = location.getLatitude();
		double mLon = location.getLongitude();
		// 用给定的经纬度构造GeoPoint,单位是微度 (度 * 1E6)
		GeoPoint p = new GeoPoint((int) (mLat * 1E6), (int) (mLon * 1E6));
		//准备overlay图像数据,根据实情情况修复
				Drawable mark= getResources().getDrawable(R.drawable.nav_turn_via_1);
				//用OverlayItem准备Overlay数据
				OverlayItem item = new OverlayItem(p, info, "中心点");
				item.setMarker(mark);
				//使用setMarker()方法设置overlay图片,如果不设置则使用构建ItemizedOverlay时的默认设置
				//创建IteminizedOverlay
				itemOverlay = new OverlayTest(mark, mMapView);
				//将IteminizedOverlay添加到MapView中
				//添加overlay, 当批量添加Overlay时使用addItem(List<OverlayItem>)效率更高
				itemOverlay.addItem(item);
				/**
				 * 将itemOverlay添加到地图中
				 */
				mMapView.getOverlays().clear();
				mMapView.getOverlays().add(itemOverlay);
				mMapView.refresh();
				/**
				 * 想地图添加自定义view
				 */
				viewCache = getLayoutInflater().inflate(R.layout.showinfo, null);
		         popupInfo = (View) viewCache.findViewById(R.id.popinfo);
		         popupText =(TextView) viewCache.findViewById(R.id.textcache);
		         
		         /**
		          * 创建一个popupoverlay
		          */
		         PopupClickListener popListener = new PopupClickListener(){
					@Override
					public void onClickedPopup(int index) {
						if ( index == 0){
							//更新item位置
						      pop.hidePop();
						      GeoPoint p = new GeoPoint(mCurItem.getPoint().getLatitudeE6()+5000,
						    		  mCurItem.getPoint().getLongitudeE6()+5000);
						      mCurItem.setGeoPoint(p);
						      itemOverlay.updateItem(mCurItem);
						      mMapView.refresh();
						}
						else if(index == 2){
							//更新图标
							mCurItem.setMarker(getResources().getDrawable(R.drawable.nav_turn_via_1));
							itemOverlay.updateItem(mCurItem);
						    mMapView.refresh();
						}
					}
		         };
		         pop = new PopupOverlay(mMapView,popListener);
				
				//删除overlay .
				//itemOverlay.removeItem(itemOverlay.getItem(0));
				//mMapView.refresh();
				//清除overlay
				// itemOverlay.removeAll();
				// mMapView.refresh();
				sendSensorValue(6319,9813,location);
		
		
	}
	 protected void onPause() {
	    	/**
	    	 *  MapView的生命周期与Activity同步,当activity挂起时需调用MapView.onPause()
	    	 */
	        mMapView.onPause();
	        super.onPause();
	    }
	    
	    @Override
	    protected void onResume() {
	    	/**
	    	 *  MapView的生命周期与Activity同步,当activity恢复时需调用MapView.onResume()
	    	 */
	        mMapView.onResume();
	        super.onResume();
	    }
	    
	    @Override
	    protected void onDestroy() {
	    	/**
	    	 *  MapView的生命周期与Activity同步,当activity销毁时需调用MapView.destroy()
	    	 */
	        mMapView.destroy();
	        super.onDestroy();
	    }
	    
	    @Override
	    protected void onSaveInstanceState(Bundle outState) {
	    	super.onSaveInstanceState(outState);
	    	mMapView.onSaveInstanceState(outState);
	    	
	    }
	    
	    @Override
	    protected void onRestoreInstanceState(Bundle savedInstanceState) {
	    	super.onRestoreInstanceState(savedInstanceState);
	    	mMapView.onRestoreInstanceState(savedInstanceState);
	    }
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}
	private void sendSensorValue(int deviceId,int sensorId,Location location)
	{
	        String site = "http://api.yeelink.net/";
	        System.out.println("try to send sensor value");
	        String siteUrl = site + "v1.0/device/"+deviceId+"/sensor/"+sensorId+"/datapoints";
	            try {
	                    URL url = new URL(siteUrl);  
	                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
	                     
	                    conn.setRequestMethod("POST");  
	                    conn.setRequestProperty("Connection", "close");  
	                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
	                    conn.setRequestProperty("U-ApiKey", "43b1c73f20849635cc4a1e350c59012a");  //replace your api key here
	                    conn.setRequestProperty("Accept", "*/*");  
	                    conn.connect();  
	                    OutputStream out = conn.getOutputStream();
	                    String value = "{\"value\":{\"lat\":"+location.getLatitude()+",\"lng\":"+location.getLongitude()+",\"speed\":"+location.getSpeed()+",\"offset\":\"yes\"}}";
	                    out.write(value.getBytes());
	                    out.flush();
	                    InputStream stream = conn.getInputStream();  
	                    byte[] data=new byte[102400];  
	                    int length=stream.read(data);  
	                    conn.disconnect();  
	                    stream.close();  
	            
	            } catch (IOException e) {
	                    e.printStackTrace();
	            }
		}
	
	/*
	 * 要处理overlay点击事件时需要继承ItemizedOverlay
	 * 不处理点击事件时可直接生成ItemizedOverlay.
	 */
	class OverlayTest extends ItemizedOverlay<OverlayItem> {
	    //用MapView构造ItemizedOverlay
	    public OverlayTest(Drawable mark,MapView mapView){
	            super(mark,mapView);
	    }
	    protected boolean onTap(int index) {
	        //在此处理item点击事件
	    	OverlayItem item = getItem(index);
			mCurItem = item ;
			
			   popupText.setText(getItem(index).getTitle());
			   Bitmap[] bitMaps={
				    XwhgBMapUtil.getBitmapFromView(popupInfo)		
			    };
			    pop.showPopup(bitMaps,item.getPoint(),32);
			
	        return true;
	    }
	        public boolean onTap(GeoPoint pt, MapView mapView){
	                //在此处理MapView的点击事件,当返回 true时
	        	if (pop != null){
	                pop.hidePop();               
				}
	                return false;
	        }
	       
	}        
}

布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <LinearLayout 
    android:orientation="horizontal"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content">
       
      <Button
        android:id="@+id/self"
        android:layout_height="fill_parent"
        android:layout_width="fill_parent"
        android:layout_weight="1"
        android:layout_marginLeft="2dip"
		android:layout_marginRight="2dip"
		android:layout_marginTop="2dip"
		android:layout_marginBottom="2dip"
        android:background="@drawable/button_style"
        android:onClick="clearOverlay"
        android:padding="10dip"
        android:text="自己(self)" />
      <Button
        android:id="@+id/friend"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:layout_marginLeft="2dip"
		android:layout_marginRight="2dip"
		android:layout_marginTop="2dip"
		android:layout_marginBottom="2dip"
        android:background="@drawable/button_style"
        android:onClick="resetOverlay"
        android:text="朋友(friend)" />
      <Button
        android:id="@+id/satellite"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_weight="1"
        android:layout_marginLeft="2dip"
		android:layout_marginRight="2dip"
		android:layout_marginTop="2dip"
		android:layout_marginBottom="2dip"
        android:background="@drawable/button_style"
        android:onClick="resetOverlay"
        android:text="卫星图(satellite)" />
      
        
    </LinearLayout>
  
    <com.baidu.mapapi.map.MapView android:id="@+id/bmapView"
	    android:layout_width="fill_parent" android:layout_height="fill_parent" 
	    android:clickable="true"     
	/>
</LinearLayout>

时间设置部分
public class SetTimeActivity extends Activity{
	
	Button sure;
	Button cancle;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.set_time_main);
		
		
		sure = (Button)findViewById(R.id.sure);
		cancle = (Button)findViewById(R.id.cancle);
		
		sure.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				intent.setClass(SetTimeActivity.this, FriendActivity.class);
				startActivity(intent);
			}
		});
		
		cancle.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				finish();
			}
		});
	}

}

布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@drawable/green"
    android:orientation="vertical"
    >
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:orientation="horizontal"> 
        <TextView
            android:id="@+id/start"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="起始时间" >
        </TextView>
        <EditText 
             android:id="@+id/start_time"
             android:layout_height="wrap_content"
             android:layout_width="290px"
             android:background="@drawable/button_on"
             android:text="2013-12-20T14:00:00">
        </EditText>
    </LinearLayout>
    
    <LinearLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_margin="5dp"
        android:orientation="horizontal"> 
        <TextView
            android:id="@+id/end"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:text="截止时间" >
        </TextView>
        <EditText 
             android:id="@+id/end_time"
             android:layout_height="wrap_content"
             android:layout_width="290px"
             android:background="@drawable/button_on"
             android:text="2013-12-21T12:00:00">
        </EditText>
    </LinearLayout>
    <LinearLayout 
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"> 
        <TextView
            android:id="@+id/device"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:text="设备ID" >
        </TextView>
        <EditText 
             android:id="@+id/deviceid"
             android:layout_height="wrap_content"
             android:layout_width="wrap_content"
             android:layout_weight="1"
             android:text="6790">
        </EditText>
        
        <TextView
            android:id="@+id/sensorid"
            android:layout_height="wrap_content"
            android:layout_width="wrap_content"
            android:layout_weight="1"
            android:text="传感器ID" >
        </TextView>
        <EditText 
             android:id="@+id/sensor"
             android:layout_height="wrap_content"
             android:layout_width="wrap_content"
             android:layout_weight="1"
             android:text="10530">
        </EditText>
        
    </LinearLayout>
	<LinearLayout 
	    android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:orientation="horizontal">
	    <Button
       	 	android:id="@+id/sure"
        	android:layout_width="wrap_content"
        	android:layout_height="wrap_content"
        	android:background="@drawable/confirm"
       		>
		</Button>
    	<Button
        	android:id="@+id/cancle"
        	android:layout_width="wrap_content"
        	android:layout_height="wrap_content"
        	android:background="@drawable/cancel" >
	    </Button>
	    </LinearLayout>
    
</LinearLayout>



Friend部分
public class FriendActivity extends Activity{

	private MapView mMapView = null;
	private MapController mMapController = null;
	OverlayTest itemOverlay;
	private TextView  popupText = null;
	private View viewCache = null;
	private View popupInfo = null;
	private OverlayItem mCurItem = null;
	private PopupOverlay   pop  = null;
	
	private String day1;
	private String speed1;
	private String lat1;
	private String lng1;
	
	ArrayList<String> date = new ArrayList<String>();
    ArrayList<String> speed = new ArrayList<String>();
    ArrayList<Double> lat=new ArrayList<Double>();
    ArrayList<Double> lng=new ArrayList<Double>();
	
	private int deviceId = 6319;
	private int sensorId = 9813;
	private int j = 0;
	private Button back;
	
	private Thread newThread;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		/**
         * 使用地图sdk前需先初始化BMapManager.
         * BMapManager是全局的,可为多个MapView共用,它需要地图模块创建前创建,
         * 并在地图地图模块销毁后销毁,只要还有地图模块在使用,BMapManager就不应该销毁
         */
        XwhgApplication app = (XwhgApplication)this.getApplication();
        if (app.mBMapManager == null) {
            app.mBMapManager = new BMapManager(this);
            /**
             * 如果BMapManager没有初始化则初始化BMapManager
             */
            app.mBMapManager.init(XwhgApplication.strKey,new XwhgApplication.MyGeneralListener());
        }
        /**
          * 由于MapView在setContentView()中初始化,所以它需要在BMapManager初始化之后
          */
		setContentView(R.layout.friend);
		mMapView = (MapView)findViewById(R.id.bmapView);
		back = (Button)findViewById(R.id.back);
		back.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
        /**
         * 获取地图控制器
         */
        mMapController = mMapView.getController();
        /**
         *  设置地图是否响应点击事件  .
         */
        mMapController.enableClick(true);
        /**
         * 设置地图缩放级别
         */
        mMapController.setZoom(14);
        /**
         * 显示内置缩放控件
         */
        mMapView.setBuiltInZoomControls(true);
		/**
         * 设定地图中心点
         */
        Drawable mark_st = getResources().getDrawable(R.drawable.icon_st);
        GeoPoint p = new GeoPoint((int)(28.182091 * 1E6), (int)(112.938917* 1E6));
        OverlayItem item = new OverlayItem(p, "起点", "中心点");
		item.setMarker(mark_st);
		//使用setMarker()方法设置overlay图片,如果不设置则使用构建ItemizedOverlay时的默认设置
		//创建IteminizedOverlay
		itemOverlay = new OverlayTest(mark_st, mMapView);
		//将IteminizedOverlay添加到MapView中
		//添加overlay, 当批量添加Overlay时使用addItem(List<OverlayItem>)效率更高
		itemOverlay.addItem(item);
		/**
		 * 将itemOverlay添加到地图中
		 */
		mMapView.getOverlays().clear();
		mMapView.getOverlays().add(itemOverlay);
		mMapView.refresh();
        
		/**
		 * 想地图添加自定义view
		 */
		viewCache = getLayoutInflater().inflate(R.layout.showinfo, null);
         popupInfo = (View) viewCache.findViewById(R.id.popinfo);
         popupText =(TextView) viewCache.findViewById(R.id.textcache);
         
         /**
          * 创建一个popupoverlay
          */
         PopupClickListener popListener = new PopupClickListener(){
			@Override
			public void onClickedPopup(int index) {
				if ( index == 0){
					//更新item位置
				      pop.hidePop();
				      GeoPoint p = new GeoPoint(mCurItem.getPoint().getLatitudeE6()+5000,
				    		  mCurItem.getPoint().getLongitudeE6()+5000);
				      mCurItem.setGeoPoint(p);
				      itemOverlay.updateItem(mCurItem);
				      mMapView.refresh();
				}
				else if(index == 2){
					//更新图标
					mCurItem.setMarker(getResources().getDrawable(R.drawable.nav_turn_via_1));
					itemOverlay.updateItem(mCurItem);
				    mMapView.refresh();
				}
			}
         };
         pop = new PopupOverlay(mMapView,popListener);
		
        mMapController.setCenter(p);
        
        getSensorValue(6319,9813);
	}
	
	private void drawgpspoint(){
		
	}
	
	private void getSensorValue(int deviceId,int sensorId)
	{
	        String site = "http://api.yeelink.net/";
	        String startday = "2013-12-02T14:01:46";
	        String endday = "2013-12-3T20:21:40";
	        String site2 = "start="+startday+"&end="+endday+"&interval=30&page=1";
	        System.out.println("try to get sensor value");
	        String siteUrl = site + "v1.0/device/"+deviceId+"/sensor/"+sensorId+".json?"+site2;
	            try {
	                    URL url = new URL(siteUrl);  
	                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
	                     
	                    conn.setRequestMethod("GET");  
	                    conn.setRequestProperty("Connection", "close");  
	                    conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
	                    conn.setRequestProperty("U-ApiKey", "43b1c73f20849635cc4a1e350c59012a");  //replace your api key here
	                    conn.setRequestProperty("Accept", "*/*");  
	                    conn.connect();  
	                    InputStream stream = conn.getInputStream();  
	                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(stream));
	                    String sCurrentLine = "";   
	                    String sTotalString = "";
	                    while ((sCurrentLine = bufferedReader.readLine()) != null) {   
	                        sTotalString += sCurrentLine + "\n";   
	                    } 
	                    
	                    String temp = sTotalString;
	                    JiexiString(temp);
	                    System.out.println(temp);
	                    
	                    String[] resulte = new String[20];
	                    int i=0;
	                    while(temp.indexOf("}}")!=-1){
	                   	 int k = temp.indexOf("}}");
	                   	 int j = temp.indexOf("{");
	                   	 resulte[i++] = temp.substring(j+1,k);
	                   	 temp = temp.substring(k+1);
	                    }
	                    
	                    
	                    i=0;
	                    String t;
	                    while(resulte[i]!=null){
	                   	 System.out.println("reslte"+"--"+i+"--"+resulte[i]);
	                   	 String s = resulte[i];
	                   	 int a = resulte[i].indexOf(":")+2;
	                        int b = resulte[i].indexOf(",")-1;
	                   	 t= s.substring(a, b);
	                   	 date.add(t);
	                   	 
	                   	 a= resulte[i].indexOf("lat")+5;
	                        b= resulte[i].indexOf("lng")-2;
	                   	 t=s.substring(a, b);
	                   	 double tem = Double.parseDouble(t);
	                   	 lat.add(tem);
	                   	 
	                   	 a= resulte[i].indexOf("lng")+5;
	                        b= resulte[i].indexOf("speed")-2;
	                   	 t=s.substring(a, b);
	                   	 tem = Double.parseDouble(t);
	                   	 lng.add(tem);
	                   	 
	                   	 a= resulte[i].indexOf("speed")+7;
	                        b= resulte[i].indexOf("offset")-2;
	                        t=s.substring(a, b);
	                        speed.add(t);
	                        
	                   	 i++;
	                    }
	                    temp = resulte[i-1];
	                    int a = resulte[i-1].indexOf(":")+2;
	                    int b = resulte[i-1].indexOf(",")-1;
	                    day1 = temp.substring(a,b);
	                    a= resulte[i-1].indexOf("lat")+5;
	                    b= resulte[i-1].indexOf("lng")-2;
	                    lat1 = resulte[i-1].substring(a,b);
	                    a= resulte[i-1].indexOf("lng")+5;
	                    b= resulte[i-1].indexOf("speed")-2;
	                    lng1 = resulte[i-1].substring(a,b);
	                    
	                    a= resulte[i-1].indexOf("speed")+7;
	                    b= resulte[i-1].indexOf("offset")-2;
	                    speed1 = resulte[i-1].substring(a,b);
	                    
	                    conn.disconnect();  
	                    stream.close();  
	            System.out.println("day="+day1+"  "+"lat="+lat1+"  "+"lng="+lng1+"  "+"speed"+speed1);
	            double la = Double.parseDouble(lat1);
	            double ln = Double.parseDouble(lng1);
	            
	            Drawable mark = getResources().getDrawable(R.drawable.icon_st);
	            Drawable mark_test = getResources().getDrawable(R.drawable.icon_marka);
	            for(j=0;j<lat.size();j++){
						GeoPoint test = new GeoPoint((int)(lat.get(j)*1E6),(int)(lng.get(j)*1E6));
				        OverlayItem item = new OverlayItem(test,date.get(j), "");
				        item.setMarker(mark_test);
				        itemOverlay.addItem(item);
					    /**
					    * 将itemOverlay添加到地图中
					    */
					    mMapView.getOverlays().clear();
					    mMapView.getOverlays().add(itemOverlay);
					    mMapView.refresh();
					    mMapController.setCenter(test);
	            }
	            
	            GeoPoint p = new GeoPoint((int)(la * 1E6), (int)(ln* 1E6));
	            OverlayItem item = new OverlayItem(p, "起点", "中心点");
	    		item.setMarker(mark);
	    		//使用setMarker()方法设置overlay图片,如果不设置则使用构建ItemizedOverlay时的默认设置
	    		//创建IteminizedOverlay
	    		//itemOverlay = new OverlayTest(mark, mMapView);
	    		//将IteminizedOverlay添加到MapView中
	    		//添加overlay, 当批量添加Overlay时使用addItem(List<OverlayItem>)效率更高
	    		itemOverlay.addItem(item);
	    		/**
	    		 * 将itemOverlay添加到地图中
	    		 */
	    		mMapView.getOverlays().clear();
	    		mMapView.getOverlays().add(itemOverlay);
	    		mMapView.refresh();
	            
	            mMapController.setCenter(p);
	            
	            } catch (IOException e) {
	                    // TODO Auto-generated catch block
	                    e.printStackTrace();
	            }
	}
	private void JiexiString(String s){
		
		
		
	}
	
	protected void onPause() {
    	/**
    	 *  MapView的生命周期与Activity同步,当activity挂起时需调用MapView.onPause()
    	 */
        mMapView.onPause();
        super.onPause();
    }
    
    @Override
    protected void onResume() {
    	/**
    	 *  MapView的生命周期与Activity同步,当activity恢复时需调用MapView.onResume()
    	 */
        mMapView.onResume();
        super.onResume();
    }
    
    @Override
    protected void onDestroy() {
    	/**
    	 *  MapView的生命周期与Activity同步,当activity销毁时需调用MapView.destroy()
    	 */
        mMapView.destroy();
        super.onDestroy();
    }
    
    @Override
    protected void onSaveInstanceState(Bundle outState) {
    	super.onSaveInstanceState(outState);
    	mMapView.onSaveInstanceState(outState);
    	
    }
    
    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
    	super.onRestoreInstanceState(savedInstanceState);
    	mMapView.onRestoreInstanceState(savedInstanceState);
    }
	/**
	 * 要处理overlay点击事件时需要继承ItemizedOverlay
	 * 不处理点击事件时可直接生成ItemizedOverlay.
	 */
	class OverlayTest extends ItemizedOverlay<OverlayItem> {
	    //用MapView构造ItemizedOverlay
	    public OverlayTest(Drawable mark,MapView mapView){
	            super(mark,mapView);
	    }
	    protected boolean onTap(int index) {
	        //在此处理item点击事件
	    	OverlayItem item = getItem(index);
			mCurItem = item ;
			
			   popupText.setText(getItem(index).getTitle());
			   Bitmap[] bitMaps={
				    XwhgBMapUtil.getBitmapFromView(popupInfo)		
			    };
			    pop.showPopup(bitMaps,item.getPoint(),32);
			
	        return true;
	    }
	        public boolean onTap(GeoPoint pt, MapView mapView){
	                //在此处理MapView的点击事件,当返回 true时
	        	if (pop != null){
	                pop.hidePop();               
				}
	                return false;
	        }
	       
	}
	

}

布局文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <LinearLayout 
	    android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="right"
        android:orientation="horizontal">
	    <Button
        android:id="@+id/back"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/button_style"
        android:text="返回" />
	    </LinearLayout>
    
  <com.baidu.mapapi.map.MapView android:id="@+id/bmapView"
	    android:layout_width="fill_parent" android:layout_height="fill_parent" 
	    android:clickable="true"     
	/>
    
</LinearLayout>

还有一个自定义弹框的布局文件
<?xml version="1.0" encoding="utf-8"?>

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
	    android:orientation="horizontal"
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    >

     <LinearLayout 
	    android:layout_width="wrap_content"
	    android:layout_height="wrap_content"
	    android:orientation="vertical"
	    android:id="@+id/popinfo"
	    >
	    
    <TextView
        android:id="@+id/textcache"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/popup_middle"
        android:gravity="center"
        android:textStyle="bold"
        android:textColor="@android:color/black"
        android:textSize="12sp"
        android:text="显示信息" />
    
     <TextView
        android:id="@+id/popdown"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/popup_down"
        android:textColor="@android:color/black"
        android:textSize="12sp" />

    </LinearLayout>
</LinearLayout>

猜你喜欢

转载自1139988263.iteye.com/blog/2007940