0

我创建了显示设备位置的简单 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 已意外停止。

4

1 回答 1

0

您必须让您的类实现LocationListener并调用manager.requestLocationUpdates()才能获取位置信息。在http://developer.android.com/training/location/receive-location-updates.html查看更多详情

于 2013-06-05T18:30:15.543 回答