在此Android应用程序中获取Gps位置(长,纬度)和时间

时间:2012-04-11 22:19:10

标签: android gps

我需要帮助才能构建我的Android应用程序。在这个应用程序中,现在,我从表单结束然后我把它放在数据库上。但我需要显示,我需要输入一个数据库当前的GPS位置和当前时间。我已经尝试使用教程,并在论坛上看到其他帖子没有结果。我需要帮助,因为我不了解如何使用位置监听器以及我必须更改项目的位置。 谢谢。 这是我的代码

FORM.java

 import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.AutoCompleteTextView;

public class Form extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }

    public void onAddClick(View botton) {
        AutoCompleteTextView spedID = (AutoCompleteTextView) findViewById(R.id.SpedID);
        AutoCompleteTextView spedCliente = (AutoCompleteTextView) findViewById(R.id.SpedCliente);
        AutoCompleteTextView spedCorriere = (AutoCompleteTextView) findViewById(R.id.SpedCorriere);

        Intent intent = new Intent();
        intent.setClass(this, Result.class);

        intent.putExtra("SpedID", spedID.getText().toString());
        intent.putExtra("SpedCliente", spedCliente.getText().toString());
        intent.putExtra("SpedCorriere", spedCorriere.getText().toString());
        startActivity(intent);
    }

    public void onCancelClick(View botton) {
        Intent intent = new Intent();
        intent.setComponent(new ComponentName(this, Result.class));
        intent.putExtra("Cancel", "Cancel");
        startActivity(intent);
    }

}

RESULT.java

import android.app.Activity;
import android.content.ContentValues;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.widget.TextView;

public class Result extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.result);

        TextView resultText = (TextView) findViewById(R.id.resultText);
        Bundle bundle = getIntent().getExtras();

        if (bundle.getString("Cancel") != null) {
            resultText.setText(getString(R.string.cancelOp));
        } else {
            String spedID = bundle.getString("SpedID");
            String spedCliente = bundle.getString("SpedCliente");
            String spedCorriere = bundle.getString("SpedCorriere");
            insertSpedizione(spedID, spedCliente, spedCorriere); // metodo per
                                                                    // inserire
                                                                    // dati in
                                                                    // db
            resultText.setText(getString(R.string.resultOk) + "\n" + spedID
                    + "\n" + spedCliente + "\n" + spedCorriere);
        }
    }

    private void insertSpedizione(String idsped, String cliente,
            String idcorriere) {
        // metodo insertspedizione riceve in ingresso i parametri sped,cliente
        // etc etc
        DatabaseHelper databaseHelper = new DatabaseHelper(this);
        SQLiteDatabase db = databaseHelper.getWritableDatabase(); // creo un
                                                                    // database
                                                                    // Srivibile

        ContentValues cv = new ContentValues(); // Hashmap
        cv.put(DatabaseHelper.IDSPED, idsped); // nome colonna, valore
        cv.put(DatabaseHelper.CLIENTE, cliente);// nome colonna, valore
        cv.put(DatabaseHelper.IDCORRIERE, idcorriere);// nome colonna, valore

        db.insert("spedizioni", DatabaseHelper.IDSPED, cv); // faccio un insert
                                                            // nella TABLE
                                                            // spedizioni con
                                                            // parametri IDSPED
                                                            // not null e il
                                                            // ContentValues
        db.close(); // quando abbiamo finito chiudiamo
    }

}

DATABASEHELPER.java

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class DatabaseHelper extends SQLiteOpenHelper {
    public static final String DATABASE_NAME = "datasped.db"; // nome database
                                                                // che viene
                                                                // creato da
                                                                // SQLiteOpenHelper
    public static final String IDSPED = "idsped";
    public static final String CLIENTE = "cliente";
    public static final String IDCORRIERE = "idcorriere";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, 1); // 1 è la versione iniziale del
                                                // database che viene aggiornata
                                                // con onUpgrade
    }

    @Override
    public void onCreate(SQLiteDatabase db) { // onCreate crea la
                                                // tabella(formattazione,
                                                // indici, etc) con tutti i dati
                                                // ce voglio nel .db
        db.execSQL("CREATE TABLE spedizioni (_id INTEGER PRIMARY KEY AUTOINCREMENT,idsped TEXT, cliente TEXT,idcorriere TEXT);");
    }// in questo caso mi basta creare una Table semplice con id incrementale
        // per ogni dato inserito

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) { // cambia
                                                                                // la
                                                                                // versione
                                                                                // del
                                                                                // database
        android.util.Log.w("spedizioni",
                "Ugrading database, which will destroy all old data");
        db.execSQL("DROP TABLE IF EXIST spedizioni");
        onCreate(db); // ricreo il Database
    }

}

的Manifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="matteo.android.SpedyGo" android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="9" />

    <application android:icon="@drawable/icon" android:label="@string/app_name">
        <activity android:name=".Form" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".Result" android:label="@string/result">
        </activity>
    </application>
</manifest>

的strings.xml

<resources>
    <string name="hello">Hello World, Form!</string>
    <string name="app_name">SpedyGo</string>
    <string name="InserisciSpedizione">Inserisci Spedizione</string>
    <string name="textsped">Id Spedizione</string>
    <string name="textcliente">Cliente</string>
    <string name="textCorriere">Id Corriere</string>
    <string name="cancel">Cancella</string>
    <string name="confirm">Conferma</string>

    <string name="result">Risultato</string>
    <string name="resultOk">Operazione Avvenuta con Successo</string>
    <string name="cancelOp">Operazione Cancellata</string>
</resources>

main.xml中

<?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">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:text="@string/InserisciSpedizione"
        android:textSize="30sp" android:textStyle="bold" android:gravity="center" />
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content" android:id="@+id/linearLayout1">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:text="@string/textsped"
            android:textStyle="bold" android:padding="5sp" android:width="120sp"
            android:textSize="16sp"></TextView>
        <AutoCompleteTextView android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:width="500sp" android:id="@+id/SpedID"></AutoCompleteTextView>
    </LinearLayout>
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content" android:id="@+id/linearLayout1">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:textStyle="bold"
            android:padding="5sp" android:text="@string/textcliente"
            android:textSize="16sp" android:width="120sp"></TextView>
        <AutoCompleteTextView android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:width="500sp" android:id="@+id/SpedCliente"></AutoCompleteTextView>
    </LinearLayout>
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content" android:id="@+id/linearLayout1">
        <TextView android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:textStyle="bold"
            android:padding="5sp" android:text="@string/textCorriere"
            android:textSize="16sp" android:width="120sp"></TextView>
        <AutoCompleteTextView android:layout_weight="1"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" android:width="500sp" android:id="@+id/SpedCorriere"></AutoCompleteTextView>
    </LinearLayout>
    <LinearLayout android:layout_width="match_parent"
        android:layout_height="wrap_content" android:id="@+id/linearLayout2">
        <Button android:layout_height="wrap_content" android:text="@string/cancel"
            android:layout_width="130sp" android:onClick="onCancelClick"></Button>
        <Button android:layout_height="wrap_content" android:text="@string/confirm"
            android:layout_width="130sp" android:onClick="onAddClick"></Button>
    </LinearLayout>
</LinearLayout>

为result.xml

<?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">
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:textStyle="bold"
        android:focusableInTouchMode="false" android:textSize="25sp"
        android:padding="10sp" android:gravity="center" android:text="@string/result" />
    <TextView android:layout_width="fill_parent"
        android:layout_height="wrap_content" android:textStyle="bold"
        android:focusableInTouchMode="false" android:textSize="20sp"
        android:padding="10sp" android:gravity="center" android:text=""
        android:id="@+id/resultText" />

</LinearLayout>

2 个答案:

答案 0 :(得分:0)

声明private LocationManager locationManager;

然后

locationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, new GeoUpdateHandler());

接下来创建一个实现LocationListener并具有函数

的GeoUpdateHandler类
public void onLocationChanged(Location location) {
            int lat = (int) (location.getLatitude() * 1E6);
            int lon = (int) (location.getLongitude() * 1E6);
            String tim = String.format("%d", location.getTime());}

答案 1 :(得分:0)

以下是使用网络提供商

检索用户位置的简单示例
// Acquire a reference to the system Location Manager
        myLocManager = (LocationManager)getSystemService( Context.LOCATION_SERVICE );

        // Define a listener that responds to location updates
        locationListener = new LocationListener()
        {
                    @Override
                    public void onLocationChanged(Location location) 
                    {
                        // Return a string representation of the latitude & longitude. Pass it to the textview and update the text
                        String tempLat = ""+location.getLatitude();
                        String tempLon = ""+location.getLongitude();

                        tempLat = refineStrg( tempLat );
                        tempLon = refineStrg( tempLon );

                        // Store/set lat and long values
                        storeLat_storeLong( tempLat, tempLon );
                    }

                    @Override
                    public void onProviderDisabled(String arg0) 
                    {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onProviderEnabled(String provider) 
                    {
                        // TODO Auto-generated method stub

                    }

                    @Override
                    public void onStatusChanged(String provider, int status, Bundle extras) 
                    {
                        // TODO Auto-generated method stub  
                    }
        };  
        // The two lines below request location updates from the network location provider
        myLocManager.requestLocationUpdates( LocationManager.NETWORK_PROVIDER, 0, 0,locationListener );

请记住在清单文件中包含适当的权限以访问用户位置(请参阅我在评论中发布的网站)

最后要检索当前时间,您可以使用Calendar或Date类,如下所示:

Calendar cal = Calendar.getInstance();
cal.getTime();

查看here,了解如何在日历上使用Date类。