Android应用中的位置管理器

时间:2013-06-05 18:18:41

标签: android

我创建简单的Android应用程序,显示设备的位置,但是当我在模拟器中运行时,它会在运行应用程序时显示错误。

package my.loc;

import android.app.Activity;
import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.widget.TextView;

public class LocActivity extends Activity {
    /** Called when the activity is first created. */
    TextView textView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        textView = (TextView) findViewById(R.id.text_view);
        LocationManager manager =
            (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Location loc =
            manager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
            textView.setText("latitude: " + loc.getLatitude()
            + "\nlongitude: " + loc.getLongitude());
    } }

Activity.xml文件就是这样的

<?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:orientation="vertical" >

    <TextView
        android:id="@+id/text_view"
         />

和清单如

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="my.loc"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="8" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

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

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

错误是:

  

应用程序loc已意外停止。

1 个答案:

答案 0 :(得分:0)

您必须拥有类实现LocationListener并致电manager.requestLocationUpdates()才能获取位置信息。请参阅http://developer.android.com/training/location/receive-location-updates.html

的详细信息