2015-10-07 214 views
0

我是新來的Android應用程序開發,我想獲得GPS座標,但我無法弄清楚我的代碼有問題。我正在使用android studio 1.4版本,並且該項目是建立在冰淇淋三明治4.0.3 使用一些文章,我試圖獲得座標,但我總是面臨問題獲取座標。Android Gps座標

這裏是我的代碼

我這是怎麼在我的manifest.xml文件定義權限設置

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

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

這些都是我在我的content_main.xml文件中的控制

<LinearLayout 
android:id="@+id/linearLayout1" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" 
android:layout_marginTop="40dip" 
android:orientation="horizontal" > 

<TextView 
android:id="@+id/TextView01" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_marginLeft="10dip" 
android:layout_marginRight="5dip" 
android:text="Latitude: " 
android:textSize="20dip" > 
</TextView> 

<TextView 
android:id="@+id/TextView02" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:text="unknown" 
android:textSize="20dip" > 
</TextView> 
</LinearLayout> 

<LinearLayout 
android:id="@+id/linearLayout2" 
android:layout_width="match_parent" 
android:layout_height="wrap_content" > 

<TextView 
android:id="@+id/TextView03" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:layout_marginLeft="10dip" 
android:layout_marginRight="5dip" 
android:text="Longitute: " 
android:textSize="20dip" > 
</TextView> 

<TextView 
android:id="@+id/TextView04" 
android:layout_width="wrap_content" 
android:layout_height="wrap_content" 
android:text="unknown" 
android:textSize="20dip" > 
</TextView> 
</LinearLayout> 

最後這是我的MainActivity.java文件

package com.example.dell.soslocation; 

import android.Manifest; 
import android.annotation.TargetApi; 
import android.app.Notification; 
import android.content.pm.PackageManager; 
import android.net.wifi.p2p.WifiP2pManager; 
import android.os.Build; 
import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.design.widget.Snackbar; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.View; 
import android.view.Menu; 
import android.view.MenuItem; 

import android.content.Context; 
import android.location.Criteria; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.widget.TextView; 
import android.widget.Toast; 

public class MainActivity extends AppCompatActivity implements  
LocationListener { 

private TextView latituteField; 
private TextView longitudeField; 
private LocationManager locationManager; 
private String provider; 

@TargetApi(Build.VERSION_CODES.M) 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); 
setSupportActionBar(toolbar); 

FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab); 
fab.setOnClickListener(new View.OnClickListener() { 
@Override 
public void onClick(View view) { 
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) 
.setAction("Action", null).show(); 
} 
}); 

latituteField = (TextView) findViewById(R.id.TextView02); 
longitudeField = (TextView) findViewById(R.id.TextView04); 

// Get the location manager 
locationManager = (LocationManager) 
getSystemService(Context.LOCATION_SERVICE); 
// Define the criteria how to select the locatioin provider -> use 
// default 
Criteria criteria = new Criteria(); 
provider = locationManager.getBestProvider(criteria, false); 
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED && 
checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != 
PackageManager.PERMISSION_GRANTED) { 
// TODO: Consider calling 
// public void requestPermissions(@NonNull String[] permissions, int 
requestCode) 
// here to request the missing permissions, and then overriding 
// public void onRequestPermissionsResult(int requestCode, String[] 
permissions, 
// int[] grantResults) 
// to handle the case where the user grants the permission. See the 
documentation 
// for Activity#requestPermissions for more details. 
return; 
} 
Location location = locationManager.getLastKnownLocation(provider); 

// Initialize the location fields 
if (location != null) { 
System.out.println("Provider " + provider + " has been selected."); 
onLocationChanged(location); 
} else { 
latituteField.setText("Location not available"); 
longitudeField.setText("Location not available"); 
} 
} 

/* Request updates at startup */ 
@TargetApi(Build.VERSION_CODES.M) 
@Override 
protected void onResume() { 
super.onResume(); 
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED && 
checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != 
PackageManager.PERMISSION_GRANTED) { 
// TODO: Consider calling 
// public void requestPermissions(@NonNull String[] permissions, int 
requestCode) 
// here to request the missing permissions, and then overriding 
// public void onRequestPermissionsResult(int requestCode, String[] 
permissions, 
// int[] grantResults) 
// to handle the case where the user grants the permission. See the 
documentation 
// for Activity#requestPermissions for more details. 
return; 
} 
locationManager.requestLocationUpdates(provider, 400, 1, this); 
} 

/* Remove the locationlistener updates when Activity is paused */ 
@TargetApi(Build.VERSION_CODES.M) 
@Override 
protected void onPause() { 
super.onPause(); 
if (checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != 
PackageManager.PERMISSION_GRANTED && 
checkSelfPermission(Manifest.permission.ACCESS_COARSE_LOCATION) != 
PackageManager.PERMISSION_GRANTED) { 
// TODO: Consider calling 
// public void requestPermissions(@NonNull String[] permissions, int 
requestCode) 
// here to request the missing permissions, and then overriding 
// public void onRequestPermissionsResult(int requestCode, String[] 
permissions, 
// int[] grantResults) 
// to handle the case where the user grants the permission. See the 
documentation 
// for Activity#requestPermissions for more details. 
return; 
} 
locationManager.removeUpdates(this); 
} 

@Override 
public void onLocationChanged(Location location) { 
int lat = (int) (location.getLatitude()); 
int lng = (int) (location.getLongitude()); 
latituteField.setText(String.valueOf(lat)); 
longitudeField.setText(String.valueOf(lng)); 
} 

@Override 
public void onStatusChanged(String provider, int status, Bundle extras) { 
// TODO Auto-generated method stub 
} 

@Override 
public void onProviderEnabled(String provider) { 
Toast.makeText(this, "Enabled new provider " + provider, 
Toast.LENGTH_SHORT).show(); 

} 

@Override 
public void onProviderDisabled(String provider) { 
Toast.makeText(this, "Disabled provider " + provider, 
Toast.LENGTH_SHORT).show(); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
// Inflate the menu; this adds items to the action bar if it is present. 
getMenuInflater().inflate(R.menu.menu_main, menu); 
return true; 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
// Handle action bar item clicks here. The action bar will 
// automatically handle clicks on the Home/Up button, so long 
// as you specify a parent activity in AndroidManifest.xml. 
int id = item.getItemId(); 

//noinspection SimplifiableIfStatement 
if (id == R.id.action_settings) { 
return true; 
} 

return super.onOptionsItemSelected(item); 
} 
} 

當我在android模擬器Nexus 4 Api 23中運行應用程序時沒有錯誤,但它沒有顯示任何座標,因爲提供程序始終爲空。當我安裝在我的設備中它不啓動,並給出錯誤「不幸的是,應用程序已停止」

有人可以告訴我什麼是錯的代碼。

感謝,

+0

任何幫助,請 –

+0

請你能正常縮進代碼?不要在這裏放下大量的代碼。只有相關的部分。爲什麼要發佈他們,刪除xml文件?只有位置監聽器纔會這樣做,以及如何實例化它。從帖子中移除「運行代碼段」和其他按鈕。 – greenapps

+0

@greenapps,抱歉丟棄所有的代碼,但我想如果我給完整的代碼,然後有人能夠建議我,我錯了。但我按照你說的方式編輯了我的代碼。 –

回答

0
Here is an easy way to get the coordinates, 
//activity-main.xml 

    <TextView 
     android:id="@+id/tv_longitude" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@id/tv_location" 
     android:layout_centerHorizontal="true" /> 


    <TextView 
     android:id="@+id/tv_longitude" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@id/tv_location" 
     android:layout_centerHorizontal="true" /> 
<TextView 
     android:id="@+id/tv_latitude" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_below="@id/tv_longitude" 
     android:layout_centerHorizontal="true"/> 

    //MainActivity.java 

    import android.app.Activity; 
    import android.content.Context; 
    import android.location.Criteria; 
    import android.location.Location; 
    import android.location.LocationListener; 
    import android.location.LocationManager; 
    import android.os.Bundle; 
    import android.view.Menu; 
    import android.widget.TextView; 
    import android.widget.Toast; 

    public class MainActivity extends Activity implements LocationListener{ 

    LocationManager locationManager ; 
    String provider; 

    @Override 
    public void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    // Getting LocationManager object 
    locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE); 

    // Creating an empty criteria object 
    Criteria criteria = new Criteria(); 

    // Getting the name of the provider that meets the criteria 
    provider = locationManager.getBestProvider(criteria, false); 

    if(provider!=null && !provider.equals("")){ 

    // Get the location from the given provider 
    Location location = locationManager.getLastKnownLocation(provider); 

    locationManager.requestLocationUpdates(provider, 20000, 1, this); 

    if(location!=null) 
    onLocationChanged(location); 
    else 
    Toast.makeText(getBaseContext(), "Location can't be retrieved", Toast.LENGTH_SHORT).show(); 

    }else{ 
    Toast.makeText(getBaseContext(), "No Provider Found", Toast.LENGTH_SHORT).show(); 
    } 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
    getMenuInflater().inflate(R.menu.activity_main, menu); 
    return true; 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
    // Getting reference to TextView tv_longitude 
    TextView tvLongitude = (TextView)findViewById(R.id.tv_longitude); 

    // Getting reference to TextView tv_latitude 
    TextView tvLatitude = (TextView)findViewById(R.id.tv_latitude); 

    // Setting Current Longitude 
    tvLongitude.setText("Longitude:" + location.getLongitude()); 

    // Setting Current Latitude 
    tvLatitude.setText("Latitude:" + location.getLatitude()); 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    // 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 
    } 
    } 
+0

你好Sai,我嘗試了你在這裏提到的方式,但我的應用程序始終崩潰,甚至沒有開始。我不知道我的編碼有什麼問題。我盡一切努力使它運行,但沒有運氣。如果你能幫助我,我可以發佈我的完整示例應用程序。謝謝 –

+0

謝謝你,你的代碼是正確的,甚至我發佈的代碼工作正常。我遇到的新版Android SDK 23的問題。由於我是Android開發新手,我不知道如何在代碼中定義權限。只要我們嘗試訪問像gps等東西,新版本就要求在java類文件中定義權限,即使您在manifest.xml文件中定義。所以我把我的sdk降到了22,現在工作正常。如果將來有人對sdk 23有很好的瞭解,請在這裏發佈支持sdk版本23的答案。 –