问题描述
我想创建一个启用 GPS 并将位置更新发送到数据库的 android 应用程序(即使手机被锁定)。
我需要实现 GPS 侦听器。当位置发生变化时,代码必须通过日志记录来工作。
此外,当位置更新时,图形界面也必须更新。 TextViews 也必须更新新的位置、速度等。请检查下面的代码并帮助我完成它。谢谢!
import android.content.Context;
import android.content.Intent;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private final static int GROUP_ID = 0;
LocationManager locationManager;
Button GPSButton;
Button mapsButton;
TextView TextLon,TextLat,TextSpeed,TextHead,TextAccu;
Boolean Flag = true;
double latitude,longitude;
float speed,accuracy,heading;
//Database helper
LocationDbHelper mDbHelper;
//Wakelock - Makes sure phone keeps sending data when screen is off
PowerManager.WakeLock wakeLock;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GPSButton = (Button) findViewById(R.id.GPSButton);
mapsButton = (Button) findViewById(R.id.mapsButton);
TextLon = (TextView) findViewById(R.id.TextLon);
TextLat = (TextView) findViewById(R.id.TextLat);
TextSpeed = (TextView) findViewById(R.id.TextSpeed);
TextHead = (TextView) findViewById(R.id.Textheading);
TextAccu = (TextView) findViewById(R.id.TextAccuracy);
TextLon.setText("Longitude : " + longitude);
TextLat.setText("Latitude : " + latitude);
TextSpeed.setText("Speed : " + speed);
TextHead.setText("heading : " + heading);
TextAccu.setText("Accuracy : " + accuracy);
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
// show location button click event
GPSButton.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
toggleGpsListener();
}
});
//Open maps activity
mapsButton.setonClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
Intent intent = new Intent(getApplicationContext(),MapsActivity.class);
startActivity(intent);
}
});
//Initialize database helper
mDbHelper = new LocationDbHelper(this);
}
private void toggleGpsListener() {
if (Flag) {
//Wakelock
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MyWakelockTag");
if(!wakeLock.isHeld())
wakeLock.acquire();
GPSButton.setText("STOP GPS");
Flag = false;
//Todo Start GPS-listener (Complete the code here)
} else {
Flag = true;
GPSButton.setText("START GPS");
if(wakeLock.isHeld())
wakeLock.release();
//Todo Stop GPS-listener (Complete the code here)
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if(wakeLock.isHeld())
wakeLock.release();
//Todo Stop GPS-listener (Complete the code here)
}
}
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)