65.9K
CodeProject 正在变化。 阅读更多。
Home

我的第一个 Android 应用

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.85/5 (52投票s)

2011年11月22日

CPOL

6分钟阅读

viewsIcon

188043

downloadIcon

9435

我希望这套教程对 Android 开发初学者有所帮助。

引言

大多数教程都从“Hello World”应用程序开始,以方便初学者上手。在本文中,我将跳过这一步,提供一系列我希望对Android开发者(初学者)有用的教程。

该应用程序是一个简单的职位搜索。用户可以从Android手机上,根据用户当前位置(使用GPS)和职位位置,在职位网站(ASP.NET网站)上搜索职位。用户输入搜索关键词和距离(英里),然后会得到在他当前位置范围内,距离他输入值的所有职位。

该应用程序将涵盖以下教程

  • 使用线程和wait命令创建启动画面
  • 在不同屏幕之间导航和使用Android导航菜单
  • 使用GPS获取当前位置
  • 使用ksoap库与.NET Web服务通信
  • 在表格中列出记录,并提供点击每一行的功能
  • 在各个屏幕之间传递参数
  • 显示Google地图

工具和IDE

以下是用于开发上述应用程序的工具和IDE

  • Android SKD:Android开发工具包,包括模拟器。可在此处下载
  • Eclipse:一个JavaScript开发IDE
  • Visual Studio 2010:用于开发Web服务的.NET

服务器端代码

首先,我将解释托管的Web服务以及包含职位广告记录的数据库表。以下是我们添加到“Jobs”表中的记录。

01.jpg - Click to enlarge image

请注意,我们为每个职位添加了“Latitude”(纬度)和“Longitude”(经度)值。这将与GPS的当前位置进行比较,并计算出距离(英里)。

我在SQL Server中有一个函数,用于计算两个地理坐标点(Latitude, Longitude)之间的距离(英里)。请看下面的代码

Create FUNCTION [dbo].[CoordinateDistanceMiles]
(
    @Latitude1 float,
    @Longitude1 float,
    @Latitude2 float,
    @Longitude2 float
)

RETURNS float 
AS  
BEGIN 
    declare @retVal float;
    
    if (@Latitude1=0 and @Longitude1=0)
        set @retVal =0
    else

    begin
    
    -- CONSTANTS
    DECLARE @EarthRadiusInMiles float;
    DECLARE @PI  float;

    SET @EarthRadiusInMiles = 3963.1
    SET @PI = PI();

    -- RADIANS conversion
    DECLARE @lat1Radians float;
    DECLARE @long1Radians float;
    DECLARE @lat2Radians float;
    DECLARE @long2Radians float;

    SET @lat1Radians = @Latitude1 * @PI / 180;
    SET @long1Radians = @Longitude1 * @PI / 180;
    SET @lat2Radians = @Latitude2 * @PI / 180;
    SET @long2Radians = @Longitude2 * @PI / 180;

    set @retVal = Acos
        (
        Cos(@lat1Radians) * Cos(@long1Radians) * Cos(@lat2Radians) * Cos(@long2Radians) + 
        Cos(@lat1Radians) * Sin(@long1Radians) * Cos(@lat2Radians) * Sin(@long2Radians) + 
        Sin(@lat1Radians) * Sin(@lat2Radians)
        ) * @EarthRadiusInMiles;

    end

    return @retVal
END

接下来,我有一个托管在本地的.NET Web服务,其中包含一个名为“JobSearch”的Web方法。该Web方法将从用户那里接收搜索关键词、距离(英里)、当前纬度值和当前经度值,然后查询数据库以获取结果。上述函数用于计算距离的查询。

 [WebMethod]
    public job[] JobSearch(string keyword, string miles, string latitude, string longitude)
    {
        List<job> retVal = new List<job>();
        SqlConnection conn = new SqlConnection
        (ConfigurationManager.ConnectionStrings["test_db"].ConnectionString);

        try
        {
            int miles_int = Convert.ToInt32(miles);
            if (miles_int == 0)
            {
                latitude = "0";
                longitude = "0";

            }
            string sql = "select *,dbo.CoordinateDistanceMiles
        (" + latitude + "," + longitude + ",latitude,longitude)  
        'DistanceMiles' from jobs where ";
            if (miles_int > 0)
                sql +=" dbo.CoordinateDistanceMiles(" + latitude + "," + 
        longitude + ",latitude,longitude) <" + miles+ " and ";        

            sql +=" (jobtitle like '%" + keyword  +  "%' or jobdesc like '%" + 
        keyword  + "%')   order by jobpostdate desc ";    

            SqlCommand cmd = new SqlCommand(sql, conn);
            conn.Open();
            SqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);

            while (dr.Read())
            {
                job jb = new job(Convert.ToInt32(dr["jobid"]), dr["jobtitle"].ToString(), 
        Convert.ToString(dr["jobdesc"]), Convert.ToDateTime(dr["jobpostdate"]), 
        Convert.ToString(dr["city"]), Convert.ToString(dr["country"]), 
        ((double)(dr["DistanceMiles"])), ((double)(dr["latitude"])), 
        ((double)(dr["longitude"])));
                retVal.Add(jb);          
            }
        }

        finally
        {
            conn.Close();
            conn.Dispose();
        }

        return retVal.ToArray(); 
    }

上面的方法使用了以下C#类“job.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// Summary description for job
/// </summary>
public class job
{
    private int _JobID = 0;
    private string _JobTitle = null;
    private string _JobDesc = null;
    private DateTime _JobPostDate = new DateTime();

    private string _country = null;
    private string _city = null;

    private double _Latitude = 0;
    private double _Longitude = 0;
    private string _distancemiles = "0";

    public int JobID
    {
        set { _JobID = value; }
        get { return _JobID; }
    }

    public string JobTitle
    {
        set { _JobTitle = value; }
        get { return _JobTitle; }
    }

    public string JobDesc
    {
        set { _JobDesc = value; }
        get { return _JobDesc; }
    }

    public DateTime JobPostDate
    {
        set { _JobPostDate = value; }
        get { return _JobPostDate; }
    }

    public string Country
    {
        set { _country = value; }
        get { return _country; }
    }

    public string City
    {
        set { _city = value; }
        get { return _city; }
    }

    public double Latitude
    {
        set { _Latitude = value; }
        get { return _Latitude; }
    }

    public double Longitude
    {
        set { _Longitude = value; }
        get { return _Longitude; }
    }

    public string DistanceMiles
    {
        set { _distancemiles = value; }
        get { return _distancemiles; }
    }

    public job(){}

    public job(int jobid, string jobtitle, string jobdesc, 
    DateTime jobpostdate, string cit, string cnt, double miles, 
    double lat, double longt)
    {
        _JobID = jobid;
        _JobTitle = jobtitle;
        _JobDesc = jobdesc;
        _JobPostDate = jobpostdate;
        _distancemiles = miles.ToString("0.00");
        _Latitude = lat;
        _Longitude = longt;
        _city = cit;
        _country = cnt;        
    }
}

客户端代码

假设Eclipse和Android SDK已安装并配置好,更多信息请点击此处

我的应用程序从一个启动画面开始。这只是第一个屏幕,包含应用程序名称和Logo,会显示大约5秒钟,然后导航到主应用程序屏幕。

布局文件:main.xml文件

<?xml version="1.0" encoding="utf-8"?>
<AbsoluteLayout
android:id="@+id/widget0"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
>
<ImageView
android:id="@+id/widget30"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="150px"
android:layout_y="80px"
android:src="@drawable/jobs_logo"
>
</ImageView>
<TextView
android:id="@+id/widget32"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_x="110px"
android:layout_y="20px" android:text="JOBS IN MY AREA - Android Job Search">
</TextView>
</AbsoluteLayout>

这是包含调用启动画面的线程函数的Java类。

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;

public class job_engine extends Activity {
    /** Called when the activity is first created. */
    
     protected boolean _active = true;
     protected int _splashTime = 2000;
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        //initially call the main screen which is the splash screen
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        // thread for displaying the next screen
        Thread splashTread = new Thread() {
            @Override
            public void run() {
                try {
                    int waited = 0;
                    while(_active && (waited < _splashTime)) {
                        sleep(100);
                        if(_active) {
                            waited += 100;
                        }
                    }
                } catch(InterruptedException e) {
                    // do nothing
                } finally {
                    //the finish function will close the current activity 
                    //which is the "main" screen.
                    finish();

                    //after waiting.. display the "home" screen: application main screen.
                    Intent i = new Intent(job_engine.this, homescreen.class);
                     startActivity(i);
                    stop();//stop thread.
                }
            }
        };
        splashTread.start();
    }
        
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            _active = false;
        }
        return true;
    }    
}

导航和菜单

接下来是“Home”屏幕,它只包含三个按钮和三个标签,用于构建菜单。

02.jpg

注意:这里,我将不关注Android组件的布局,我假设开发者已经知道如何构建布局。更多关于Android布局的信息,请参阅《理解Android用户界面》

简单看一眼,下面的代码展示了如何给按钮添加点击事件。

    //define the controls
    Button btn1;
    Button btn2;
    Button btn3;
    TextView Label4;    
    
   public void onCreate(Bundle icicle)
   {
      //set the contentview to the homescreen  
      super.onCreate(icicle);
      setContentView(R.layout.homescreen);
      
      //get the buttons objects.
      btn1 = (Button) findViewById(R.id.btn1);
      btn2 = (Button) findViewById(R.id.btn2);
      btn3 = (Button) findViewById(R.id.btn3);
      
      Label4 = (TextView) findViewById(R.id.Lable4);
      
      //create onclick event handler
      btn1.setOnClickListener(new OnClickListener() 
      {            
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                
                //this will open new screen
                Intent i = new Intent(homescreen.this, jobsearch.class);
            
                startActivity(i);
            }
        }); 
      
      //=======================================================
      btn2.setOnClickListener(new OnClickListener() 
      {        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            
            //the browse functionality is not implemented yet
            NotImplemented();            
        }
    });
      
      //=======================================================
      btn3.setOnClickListener(new OnClickListener() 
      {        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            
              //this will close the application  
              finish();            
        }
    }); 

或者,您也可以利用Android菜单来构建菜单系统。在这种情况下,您需要按下手机上的“Menu”按钮才能显示菜单,菜单会显示在手机屏幕底部。

03.jpg

以下是实现Android菜单的代码

/* Creates the menu items */
   public boolean onCreateOptionsMenu(Menu menu) {
       menu.add(0,1,0, "Job Search");
       menu.add(0,2,1, "Browse Jobs");
       menu.add(0,3,1, "Exit");
   
       return true;
   }

   /* Handles item selections */
   public boolean onOptionsItemSelected(MenuItem item) {
       switch (item.getItemId()) {
       case 1:
           Intent i = new Intent(homescreen.this, jobsearch.class);
           startActivity(i);
           return true;
       case 2:
           NotImplemented();
           return true;
           
       case 3:
          finish();
           return true;
       }
       return false;
   }

使用GPS获取当前位置

在同一个“Home”屏幕中,我添加了GPS功能来感知用户的当前位置。为此,我创建了一个实现“LocationListener”的新类,因此每次GPS检测到新位置时,Android系统都会调用此回调函数。

我们将添加自己的Location listener,并重写强制函数。在这种情况下,我们只会在以下几种情况下向屏幕打印一条消息:

  • onLocationChanged (位置更新)
  • onProviderDisabled (GPS关闭)
  • onProviderEnabled (GPS开启)
  • 并添加另一个强制方法,该方法什么也不做:onStatusChanged (我们在这里不添加任何内容)。

    请看下面的代码

/* Class My Location Listener */ 

   public class MyLocationListener implements LocationListener 
   { 

    @Override 
   public void onLocationChanged(Location loc) 
   { 
   //just passing the current latitude and logtude values to an external class 
   //for later use.     
   CurrentLocation.Latitude =Double.toString(loc.getLatitude());
   CurrentLocation.Longitude = Double.toString(loc.getLongitude());
   
   String Text = "My current location is: " + 

   "Latitud = " + loc.getLatitude() + 

   "Longitud = " + loc.getLongitude(); 
   
   Toast.makeText(getApplicationContext(), Text, Toast.LENGTH_SHORT).show();
   } 
       
   @Override 

   public void onProviderDisabled(String provider) 
   { 
   Toast.makeText(getApplicationContext(), "Gps Disabled", Toast.LENGTH_SHORT ).show(); 
   } 

   @Override 
   public void onProviderEnabled(String provider) 
   { 
   Toast.makeText( getApplicationContext(), "Gps Enabled", Toast.LENGTH_SHORT).show(); 
   } 

   @Override 
   public void onStatusChanged(String provider, int status, Bundle extras) 
   { 
   } 
   }/* End of Class MyLocationListener */ 

现在,为了显示当前位置信息,我们需要在“OnCreate”方法中添加以下代码

 //code to get the current GPS location
      
      LocationManager mlocManager = (LocationManager)getSystemService
                (Context.LOCATION_SERVICE); 
      LocationListener mlocListener = new MyLocationListener(); 

      mlocManager.requestLocationUpdates( LocationManager.GPS_PROVIDER, 
                0, 0, mlocListener); 

注意:为了能够访问GPS,我们必须在AndroidManifest.xml文件中添加权限

将权限行添加到“manifest”标签之后。请看下面

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="job.engine"
      android:versionCode="1"
      android:versionName="1.0">
     
        <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

为了模拟位置更新,我们需要通过telnet连接到模拟器,然后执行以下操作

telnet localhost 5554 

geo fix 30 28 

您应该会得到以下结果

04.jpg

连接到Web服务

接下来是“Job Search”屏幕,其中包含两个文本框和一个搜索按钮。在此屏幕上,用户将输入搜索关键词和距离(英里),然后点击搜索以从Web服务查询职位记录。

我使用了KSoap2库与.NET Web服务进行通信。

为了能够与Web服务通信,您必须在manifest文件中添加以下权限行

  <uses-permission android:name="android.permission.INTERNET" />

搜索按钮的“OnClick”方法执行时间太长。因此,我需要一个解决方案来在后台完成我的任务。Handler是解决这个问题的非常好的方案。

如果您不使用这种方法,用户会看到程序似乎卡住了。

如何使用它。首先,您需要重写handleMessage方法。

private Handler handler = new Handler() {
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
// do something
}
};

其次,您需要创建一个Thread

new Thread() {
public void run() {
//long time method
handler.sendEmptyMessage(0);
}
}.start();

这是搜索按钮的“OnClick”事件。

      btn_search.setOnClickListener(new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            //on clicking the search button.. will call the "StartThread" 
            //function that contains the thread running the handler
            StartThread();
        }
    });

这是上面调用的“StartThread”函数

//this will start the search thread.
   protected void StartThread()
   {
       //show process dialog
       pd = ProgressDialog.show(this, "Job Searching", 
        "Contacting Web Service, Please Wait...");      
                
       SearchTread = new Thread() {
           @Override
           public void run() {              
               
              handler.sendEmptyMessage(0);
           }
       };
       SearchTread.start();
   }
   
    private Handler handler = new Handler() 
   {
        public void handleMessage(Message msg) 
        {                 
            //this is the function that do the search 
            DoSearch();       
        }
    };

这是包含整个搜索过程的“DoSearch”函数。

private static final String NAMESPACE="http://tempuri.org/"; 
private static final String 
    URL ="http://10.0.2.2/webservice/service.asmx"; //Web Service URL
private static final 
   String HelloWorld_SOAP_ACTION ="http://tempuri.org/JobSearch"; //specifies the action 
private static final String METHOD_NAME1 =
    "JobSearch";  //specify the method name what you are calling    

//this function is taking long time.. that is why we use handler and thread
   protected void DoSearch()
   {
       try          
          {           
           // get the text entered in the search box
           String keyword = key_txt.getText().toString();
        
           //show alert if the user did not enter anything to search
           if (keyword.equals(""))
           {
                   Dialog dlg = new AlertDialog.Builder(this) 
                    .setIcon(R.drawable.icon) 
                    .setTitle("Jobs In My Area") 
                    .setPositiveButton("OK", null) 
                    .setMessage("Please, Enter Keyword to search") 
                    .create(); 
            dlg.show(); 
           }
           else               
           {       
              lbl_ws.setText(""); 
               
              TableLayout tbl1 = (TableLayout) findViewById(R.id.tbl1);
         
             tbl1.removeAllViews();
              
              //start calling the web service.
             //create soap request
             SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME1);
             
             //send the parameters
            request.addProperty("methodName","JobSearch"); 
            request.addProperty("keyword", keyword);
            request.addProperty("miles",miles_txt.getText().toString());
            request.addProperty("latitude", lat);
            request.addProperty("longitude", lng);
            
            //create soap client
            SoapSerializationEnvelope envelope =new  SoapSerializationEnvelope
                        (SoapEnvelope.VER11); 
            envelope.dotNet = true; 
            
            envelope.setOutputSoapObject(request); 
            HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);  
              
             //call the web method from the URL 
            androidHttpTransport.call(HelloWorld_SOAP_ACTION, envelope); 
            
            //get the response as raw;
            SoapObject  objs = (SoapObject)envelope.getResponse();
            
            //check the there is a results or not
            if (objs.getPropertyCount()==0)
            {
                   Dialog dlg = new AlertDialog.Builder(this) 
                  .setIcon(R.drawable.icon) 
                  .setTitle("Jobs In My Area") 
                  .setPositiveButton("OK", null) 
                  .setMessage("No Jobs Found for the search keyword specified!") 
                  .create(); 
          dlg.show(); 
          return;
            }
            
              //loop through the results set
              for(int i=0;i< objs.getPropertyCount();i++)
              {
                  //JobList +=objs.getPropertyCount();
                  SoapObject obj = (SoapObject) objs.getProperty(i);
                  
                  //making the job title bold. using the "SpannableString"
                  SpannableString jobTitle = new SpannableString
                (obj.getProperty("JobTitle").toString()); 
                  jobTitle.setSpan(new StyleSpan(Typeface.BOLD),0,0,0); 
                  
                  
                 // Date d = (Date) obj.getProperty("JobPostDate");
                  String date_raw = obj.getProperty("JobPostDate").toString();
                  String Formatted_Date = date_raw.substring(8,10) + 
        "-" + date_raw.substring(5,7) + "-" + date_raw.substring(0,4);
                  
                  SpannableString jobPostDate = new SpannableString(Formatted_Date);
                  jobPostDate.setSpan(new StyleSpan(Typeface.ITALIC), 0, 0, 0);                  
                  
                  String JobDesc =  obj.getProperty("Country").toString();
                  JobDesc += "," + obj.getProperty("City").toString();
                  JobDesc += "(" + obj.getProperty
            ("DistanceMiles").toString() + " Miles)";
                  JobDesc += " : " + obj.getProperty("JobDesc").toString();
                  
                  if (!JobDesc.equals(""))
                  {
                      if (JobDesc.length()>200)
                          JobDesc =   JobDesc.substring(0, 200) + " ...";
                  }                     
                    
                  TextView lbl = new TextView(this);
                  TextView lbl2 = new TextView(this);
                  TextView lbl3 = new TextView(this);
            
                  lbl.setText(jobTitle);
                  lbl2.setText(" (" + jobPostDate + ")");
                 
                  lbl3.setText(JobDesc);
                  lbl3.setTextSize(10);            
                  
                  //start build up the table
                  //creating table row    
                  TableRow tr = new TableRow(this);
                  
                  LinearLayout Cell1 = new LinearLayout(this);
                  Cell1.addView(lbl);
                  Cell1.addView(lbl2);                 
                
                  //adding the cell to the row.          
                  tr.addView(Cell1);
                  
                  TableRow tr2 = new TableRow(this);
                  LinearLayout Cell2 = new LinearLayout(this);
                  Cell2.addView(lbl3, new LinearLayout.LayoutParams
                (450, LayoutParams.WRAP_CONTENT));
                  tr2.addView(Cell2);
                 
                  TableRow tr3 = new TableRow(this);
                  LinearLayout Cell3 = new LinearLayout(this);
                  
                  View hr = new View(this);
                  //hr.setBackgroundColor(Color.WHITE);
                  hr.setMinimumHeight(9);
                  
                  Cell3.addView(hr); //adding spacer only
                  tr3.addView(Cell3);
                  
                  //registering click for the row.
                  
                  tr.setClickable(true);
                  tr.setId(Integer.parseInt(obj.getProperty("JobID").toString()));
                  
                     // Register handler for UI elements
                  tr.setOnClickListener(new View.OnClickListener() {
                      public void onClick(View v) {
                         // Log.d(TAG, "mAddAccountButton clicked");
                          int rowid;
                          rowid = v.getId();
                          String args = Integer.toString(rowid);
                        
                        //function to be called when the row is clicked.  
                          GetRowID(args);
                      }
                  }); 
                  
                  //adding the row to the table.
                  tbl1.addView(tr); //adding job title row
                  tbl1.addView(tr2); // job desc text
                  tbl1.addView(tr3); // spacer row
              }
           }
          }
          catch(Exception e)
          {
             lbl_ws.setText(e.toString()) ;
          }
          finally
          {
             pd.dismiss();
             SearchTread.stop();
          }
   }

注意:如果您需要引用主机计算机的localhost,例如当您希望模拟器客户端联系运行在同一主机上的服务器时,请使用别名10.0.2.2来引用主机计算机的回环接口。从模拟器来看,localhost (127.0.0.1)指的是它自己的回环接口。这就是为什么我的Web服务URL是

private static final String 
    URL ="http://10.0.2.2/webservice/service.asmx"; //Web Service URL

以表格格式显示结果

在上面的同一个函数中,我们创建了一个Table Layout来容纳我们的记录

//outside the loop
 TableLayout tbl1 = (TableLayout) findViewById(R.id.tbl1);

 //inside the loop
  TableRow tr = new TableRow(this);
                  
                  LinearLayout Cell1 = new LinearLayout(this);
                  Cell1.addView(lbl);
                  Cell1.addView(lbl2);  
                
                  //adding the cell to the row.
                  tr.addView(Cell1);
                  
                  TableRow tr2 = new TableRow(this);
                  LinearLayout Cell2 = new LinearLayout(this);
                  Cell2.addView(lbl3, new LinearLayout.LayoutParams
                (450, LayoutParams.WRAP_CONTENT));
                  tr2.addView(Cell2);
                 
                  TableRow tr3 = new TableRow(this);
                  LinearLayout Cell3 = new LinearLayout(this);
                  
                  View hr = new View(this);
                  //hr.setBackgroundColor(Color.WHITE);
                  hr.setMinimumHeight(9);
                  
                  Cell3.addView(hr); //adding spacer only
                  tr3.addView(Cell3);
//outside the loop
//adding the row to the table.
                  tbl1.addView(tr); //adding job title row
                  tbl1.addView(tr2); // job desc text
                  tbl1.addView(tr3); // spacer row

05.jpg

为了使表格行可点击,以便用户可以查看职位详情,我们注册了一个点击事件。

//registering click for the row.
                  
                  tr.setClickable(true);
                  tr.setId(Integer.parseInt(obj.getProperty("JobID").toString()));
                  
                     // Register handler for UI elements
                  tr.setOnClickListener(new View.OnClickListener() {
                      public void onClick(View v) {
                      
                          int rowid;
                          rowid = v.getId();
                          String args = Integer.toString(rowid);
                        
                        //function to be called when the row is clicked.  
                          GetRowID(args);
                      }
                  });

通过传递职位ID查看职位详情屏幕

GetRowID”函数将打开“Job Details”屏幕,并传递job id参数。以下是如何将参数传递给“Intent

 public void GetRowID(String Args) 
   {
             //open the job details     
          Intent i = new Intent(jobsearch.this, jobdetails.class);
          
          //passing the parameters - Job ID
          i.putExtra("JobID",Args);
           startActivity(i);
   } 

接下来,在“Job Details”屏幕中,我们需要读取从前一个屏幕传递过来的参数。为此,我们需要在“OnCreate”中添加以下代码

 Intent  i = super.getIntent();
      //get all parameters passed from previous screen
      Bundle bun =  i.getExtras();
      
      //get the parameter by name
      String JobID = bun.getString("JobID");
      
      //this will again connect to the web service and get the job details by id.
      PopulateJob(JobID);

在地图上显示职位位置

当用户点击职位查看职位详情时,他可以选择在地图上查看职位位置。我使用了Android的Google MAP库。注意:您需要一个Google API Key。

在布局文件中,我有以下代码

<com.google.android.maps.MapView
        android:id="@+id/mapview1"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:clickable="true"
        android:apiKey="your key is here"
    />

这是用于显示地图的完整Java文件

import android.os.Bundle;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;

public class map extends MapActivity 
{    
     private MapView myMap;    
      
      private double lat; 
      private double lon;
  
    @Override
     public void onCreate(Bundle icicle)
       {
          super.onCreate(icicle);
          setContentView(R.layout.map);
          
          myMap = (MapView) findViewById(R.id.mapview1); //Get map from XML 

          lat = Double.parseDouble(CurrentLocation.Latitude);
          lon = Double.parseDouble(CurrentLocation.Longitude);
          navigateToLocation((lat * 1000000), 
        (lon * 1000000), myMap); //display the found address
       }

    @Override
    protected boolean isRouteDisplayed() {
        // TODO Auto-generated method stub
        return false;
    }    
    
    public static void navigateToLocation 
    (double latitude, double longitude, MapView mv) { 
        GeoPoint p = new GeoPoint((int) latitude, (int) longitude); //new GeoPoint 
        mv.displayZoomControls(true); //display Zoom 
        MapController mc = mv.getController(); 
        mc.animateTo(p); //move map to the given point 
        int zoomlevel = mv.getMaxZoomLevel(); //detect maximum zoom level 
        mc.setZoom(zoomlevel - 1); //zoom 
        mv.setSatellite(false); //display only "normal" mapview  
      } 
}

结论

有关源代码的更多详细信息,请从本文顶部的链接下载源代码。源代码简单且注释良好。

希望本教程有用,我很乐意看到其他评论和投票。

© . All rights reserved.