1.message實現(xiàn)輪播圖效果
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center">
<ViewFlipper
android:id="@+id/view_flipper"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
代碼:
public class MessageActivity extends AppCompatActivity {
private ViewFlipper viewFlipper;
private int[] images = new int[]{
R.mipmap.bg,R.mipmap.bg2
};
Animation[] animations = new Animation[4];
final int FLAG_MSG = 0x110;
private Message message;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_message);
viewFlipper = findViewById(R.id.view_flipper);
for(int i =0;i<images.length;i++){
ImageView imageView = new ImageView(this);
imageView.setImageResource(images[i]);
viewFlipper.addView(imageView);
}
animations[0] = AnimationUtils.loadAnimation(this,R.anim.slide_in_right);
animations[1] = AnimationUtils.loadAnimation(this,R.anim.slide_out_left);
viewFlipper.setInAnimation(animations[0]);
viewFlipper.setOutAnimation(animations[1]);
message = Message.obtain();//獲取message對象
message.what = FLAG_MSG;
handler.sendMessage(message);
}
Handler handler = new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(msg.what == FLAG_MSG){
viewFlipper.showPrevious();//切換到下一張圖片
message = handler.obtainMessage(FLAG_MSG);
handler.sendMessageDelayed(message,3000);
}
}
};
}
2.Service厌处,android四大組件之一
布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/start_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAllCaps="false"
android:text="開啟service"/>
<Button
android:id="@+id/stop_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="停止service"
android:textAllCaps="false"/>
<Button
android:id="@+id/music_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="音樂service"
android:textAllCaps="false"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<TextView
android:id="@+id/txt1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="12"/>
<TextView
android:id="@+id/txt2"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="12"/>
<TextView
android:id="@+id/txt3"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="12"/>
<TextView
android:id="@+id/txt4"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center"
android:text="12"/>
</LinearLayout>
<Button
android:id="@+id/bind_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="bindservice-開始搖號"
android:textAllCaps="false"/>
<Button
android:id="@+id/intent_service"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="IntentService"
android:textAllCaps="false"/>
</LinearLayout>
-
開啟服務堰汉,停止服務
intent = new Intent(ServiceActivity.this, MyService.class); start_service.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startService(intent); } }); stop_service.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { stopService(intent); } });
MyService.class:
public class MyService extends Service {
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
Log.i("Service","service已創(chuàng)建");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("Service","service已啟動");
new Thread(new Runnable() {
@Override
public void run() {
int i = 0;
while(isRunning()){
Log.i("Service",String.valueOf(++i));
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.i("Service","service已銷毀");
super.onDestroy();
}
//判斷Service是否正在運行
public boolean isRunning(){
ActivityManager activityManager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
//獲取所有正在運行的Service
ArrayList<ActivityManager.RunningServiceInfo> runningServiceInfos = (ArrayList<ActivityManager.RunningServiceInfo>) activityManager.getRunningServices(20);
for(int i=0; i<runningServiceInfos.size();i++){
if(runningServiceInfos.get(i).service.getClassName().toString().equals("com.example.bilibili.service.MyService")){
return true;
};
}
return false;
}
}
Manifest.xml配置:
<service
android:name=".service.MyService"
android:enabled="true"
android:exported="true" />
-
音樂service
intent1 = new Intent(this,MusicService.class); music_service.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { //啟動和停止musicservice if(MusicService.isplay == false){ startService(intent1); music_service.setText("停止音樂service"); }else{ stopService(intent1); music_service.setText("開啟音樂service"); } } }); @Override protected void onStart() { startService(intent1); super.onStart(); } @Override protected void onDestroy() { stopService(intent1); super.onDestroy(); }
MusicService.class:
public class MusicService extends Service {
public static boolean isplay = false; //定義播放狀態(tài)
MediaPlayer mediaPlayer;
public MusicService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
mediaPlayer = MediaPlayer.create(this, R.raw.hua);
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if(!mediaPlayer.isPlaying()){
mediaPlayer.start();
isplay = mediaPlayer.isPlaying();
}
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
mediaPlayer.stop();
isplay = mediaPlayer.isPlaying();
mediaPlayer.release();
super.onDestroy();
}
}
-
bindservice(例:搖號)
int[] tvid = { R.id.txt1,R.id.txt2,R.id.txt3,R.id.txt4 }; private TextView tv; BindService bindService; bind_service.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { List number = bindService.getRandomNumber(); for(int i=0;i<number.size();i++){ tv = findViewById(tvid[i]); tv.setText(number.get(i).toString()); } } }); //創(chuàng)建ServiceConnection對象 private ServiceConnection conn = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { bindService = ((BindService.MyBinder)service).getService();//獲取后臺service } @Override public void onServiceDisconnected(ComponentName name) { } }; @Override protected void onStart() { Intent intent2 = new Intent(this,BindService.class); bindService(intent2,conn,BIND_AUTO_CREATE);//最后一個參數(shù)表示綁定的時候是否自動創(chuàng)建service,0表示不創(chuàng)建 super.onStart(); } @Override protected void onStop() { unbindService(conn); super.onStop(); }
BindService.class:
public class BindService extends Service {
public BindService() {
}
//創(chuàng)建MyBinder內部類
public class MyBinder extends Binder {
public BindService getService(){ //創(chuàng)建獲取service的方法
return BindService.this; //返回當前service類
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return new MyBinder();
}
//自定義方法拾枣,用于生成隨機數(shù)
public List getRandomNumber(){
List resArr = new ArrayList();
String strNumber = "";//用于保存生成的隨機數(shù)
for(int i =0;i<4;i++){
int number = new Random().nextInt(33)+1;//生成指定范圍的隨機整數(shù)
if(number<10){
strNumber = "0"+String.valueOf(number);
}else {
strNumber = String.valueOf(number);
}
resArr.add(strNumber);//把轉換后的字符串添加到list集合中
}
return resArr;
}
@Override
public void onDestroy() {
super.onDestroy();
}
}
Manifest.xml:
<service
android:name=".service.BindService"
android:enabled="true"
android:exported="true" />
-
IntentService:普通的service不能自動停止亏娜,IntentService可以
intent_service.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { startService(new Intent(ServiceActivity.this, MyIntentService.class)); } });
MyIntentService.class:
public class MyIntentService extends IntentService {
public MyIntentService(){
super("MyIntentService");
}
public MyIntentService(String name) {
super(name);
}
@Override
protected void onHandleIntent(Intent intent) {
Log.i("IntentService:","Service已啟動");
long endTime = System.currentTimeMillis()+10*1000;//結束時間
while (System.currentTimeMillis()<endTime){
//耗時任務
synchronized (this){
try {
wait(endTime-System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
@Override
public void onDestroy() {
Log.i("IntentService:","Service已銷毀");
super.onDestroy();
}
}
Manifest.xml:
<service android:name=".service.MyIntentService" />
3.Sensor傳感器
-
光線傳感器,lightSensor
布局<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" android:padding="10dp"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:text="光線傳感器" android:gravity="center"/> <EditText android:id="@+id/etv_light" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="光線值"/> </LinearLayout>
代碼:
public class LightSensorActivity extends AppCompatActivity implements SensorEventListener {
private EditText etv_light;
private SensorManager sensorManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_light_sensor);
etv_light = findViewById(R.id.etv_light);
sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE);
}
@Override
protected void onResume() {
super.onResume();
//為光線傳感器注冊監(jiān)聽器
sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_LIGHT),SensorManager.SENSOR_DELAY_GAME);
}
@Override
protected void onPause() {
super.onPause();
sensorManager.unregisterListener(this);
}
@Override
public void onSensorChanged(SensorEvent event) {
float[] values = event.values;//獲取傳感器的值
int sensorType = event.sensor.getType();//獲取傳感器類型
StringBuilder builder = null;
if(sensorType == Sensor.TYPE_LIGHT){
builder = new StringBuilder();
builder.append("光的強度值:");
builder.append(values[0]);//添加獲取的傳感器的值
etv_light.setText(builder.toString());
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
-
magneticSensor:磁場傳感器(例:指南針)
布局:<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.bilibili.sensor.PointerView android:layout_width="wrap_content" android:layout_height="wrap_content" /> </FrameLayout>
com.example.bilibili.sensor.PointerView:
public class PointerView extends View implements SensorEventListener {
private SensorManager sensorManager;
private Bitmap pointer = null;// 定義指針的位圖對象
private float[] allValue;//磁場傳感器的值
public PointerView(Context context,AttributeSet attrs) {
super(context, attrs);
sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),sensorManager.SENSOR_DELAY_GAME);
pointer = BitmapFactory.decodeResource(super.getResources(), R.drawable.zhinanzhen);
}
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
float[] value = event.values;
allValue = value;
super.postInvalidate();//刷新界面
}
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {//當傳感器精度改變時觸發(fā)
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//根據(jù)x軸厌均,y軸的磁場強度繪制指針
if(allValue!=null){
float x = allValue[0];//x軸的磁場強度
float y = allValue[1];
/*try {
canvas.restore();//重置繪圖對象
}catch (Exception e){
}*/
canvas.save();
canvas.restore();
canvas.translate(super.getWidth()/2,super.getHeight()/2);//設置旋轉中心點為屏幕中心點
if(y==0 && x>0){
canvas.rotate(90);
}else if(y==0 && x<0){
canvas.rotate(270);//正西方
}else{
if(y>=0){
canvas.rotate((float) (Math.tanh(x/y)*90));
}else{
canvas.rotate(180+(float) (Math.tanh(x/y)*90));
}
}
canvas.drawBitmap(this.pointer,-this.pointer.getWidth()/2,-this.pointer.getHeight()/2,new Paint());//繪制指針
}
}
}
-
AccelerationSensor:加速度傳感器(例:手機搖一搖)
代碼:public class AccelerationActivity extends AppCompatActivity implements SensorEventListener { private SensorManager sensorManager; private Vibrator vibrator;//振動器 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_acceleration); sensorManager = (SensorManager) getSystemService(Context.SENSOR_SERVICE); vibrator = (Vibrator) getSystemService(Service.VIBRATOR_SERVICE);//獲取振動器 } @Override protected void onResume() { super.onResume(); sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_GAME); } @TargetApi(Build.VERSION_CODES.LOLLIPOP) @Override public void onSensorChanged(SensorEvent event) { int sensorType = event.sensor.getType(); if(sensorType == Sensor.TYPE_ACCELEROMETER){ float[] values = event.values;//獲取傳感器的值 if(values[0]>15 || values[1]>15 || values[2]>15){ ToastUtil.showMsg(AccelerationActivity.this,"搖一搖"); AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setView(R.layout.tab_1); builder.show(); vibrator.vibrate(500);//設置振動器的頻率 sensorManager.unregisterListener(this); } } } @Override public void onAccuracyChanged(Sensor sensor, int accuracy) { } }
-
DirectionSensor:方向傳感器(例:水平儀)
布局:<?xml version="1.0" encoding="utf-8"?> <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <com.example.bilibili.sensor.SpiritelevelView android:layout_width="match_parent" android:layout_height="match_parent" /> </FrameLayout>
com.example.bilibili.sensor.SpiritelevelView.class:
public class SpiritelevelView extends View implements SensorEventListener {
//水平儀
private int MAX_ANGLE = 30;//手機可以傾斜的最大角度
private int bubbleX,bubbleY;//小籃球的位置坐標
private SensorManager sensorManager;
private Bitmap bubble;//小籃球位圖對象
float[] accelerometerValues = new float[3];//加速度傳感器的值
float[] maganeticValues = new float[3];//磁場傳感器的值
public SpiritelevelView(Context context, AttributeSet attrs) {
super(context, attrs);
sensorManager = (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_MAGNETIC_FIELD),SensorManager.SENSOR_DELAY_GAME);//磁場傳感器
sensorManager.registerListener(this,sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),SensorManager.SENSOR_DELAY_GAME);//加速度傳感器
bubble = BitmapFactory.decodeResource(getResources(),R.drawable.bubble);
}
@Override
public void onSensorChanged(SensorEvent event) {
if(event.sensor.getType() == Sensor.TYPE_ACCELEROMETER){
accelerometerValues = event.values.clone();//獲取加速度傳感器的值
}else if(event.sensor.getType() == Sensor.TYPE_MAGNETIC_FIELD){
maganeticValues = event.values.clone();//獲取磁場傳感器的值
}
float[] R = new float[9];//保存旋轉數(shù)據(jù)的數(shù)組
float[] values = new float[3];//保存方向數(shù)據(jù)的數(shù)組
SensorManager.getRotationMatrix(R,null,accelerometerValues,maganeticValues);//獲得一個包含旋轉矩陣的R數(shù)組
SensorManager.getOrientation(R,values);//獲取方向值
float xAngle = (float) Math.toDegrees(values[1]);//這是x軸旋轉角度
float yAngle = (float) Math.toDegrees(values[2]);//這是y軸旋轉角度
getPosition(xAngle,yAngle);//獲取小球的位置坐標
super.postInvalidate();//刷新界面
}
//根據(jù)x軸和y軸的旋轉角度確定小籃球的位置
private void getPosition(float xAngle,float yAngle){
//小籃球位于中間時(水平儀完全水平),小籃球的X,Y坐標
int x = (super.getWidth() - bubble.getWidth()) / 2;
int y = (super.getHeight() - bubble.getHeight()) / 2;
//控制小球的X軸位置
if(Math.abs(yAngle) <= MAX_ANGLE){ //如果Y軸的傾斜角度還在最大角度之內
//根據(jù)Y軸的傾斜角度計算X坐標的變化值(傾斜角度越大告唆,X坐標變化越大)
int deltaX = (int) ((super.getWidth() - bubble.getWidth()) / 2 * yAngle / MAX_ANGLE);
x -= deltaX;
}else if(yAngle > MAX_ANGLE) { //如果Y軸的傾斜角度已經(jīng)大于MAX_ANGLE棺弊,小籃球在最左邊
x = 0;
}else{ //如果與Y軸的傾斜角已經(jīng)小于負的MAX_ANGLE,小籃球在最右邊
x = super.getWidth() - bubble.getWidth();
}
//控制小球的Y軸位置
if(Math.abs(xAngle) <= MAX_ANGLE){ //如果X軸的傾斜角度還在最大角度之內
//根據(jù)X軸的傾斜角度計算Y坐標的變化值(傾斜角度越大擒悬,Y坐標變化越大)
int deltaY = (int) ((super.getHeight() - bubble.getHeight()) / 2 * xAngle / MAX_ANGLE);
y += deltaY;
}else if(xAngle > MAX_ANGLE) { //如果X軸的傾斜角度已經(jīng)大于MAX_ANGLE镊屎,小籃球在最下邊
y = super.getHeight() - bubble.getHeight();
}else{ //如果與X軸的傾斜角已經(jīng)小于負的MAX_ANGLE,小籃球在最右邊
y = 0;
}
//更新小籃球坐標
bubbleX = x;
bubbleY = y;
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
canvas.drawBitmap(bubble,bubbleX,bubbleY,new Paint());//繪制小籃球
}
@Override
public void onAccuracyChanged(Sensor sensor, int accuracy) {
}
}
4.位置服務:
本文所需權限茄螃,及動態(tài)權限配置:
Manifest.xml:
<!--允許訪問最佳location的權限-->
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION},1);
布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="10dp"
android:gravity="center_horizontal">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="可用LocationProvider"
android:gravity="center"/>
<TextView
android:id="@+id/provider"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:textColor="@color/colorBlack"
android:textStyle="bold"
android:gravity="center"/>
<TextView
android:id="@+id/location_info"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:lineSpacingExtra="5dp"
android:textColor="@color/colorAccent"
android:textStyle="bold"
android:gravity="center"/>
</LinearLayout>
代碼:
public class LocationActivity extends AppCompatActivity {
private TextView provider, location_info;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_location);
provider = findViewById(R.id.provider);
location_info = findViewById(R.id.location_info);
LocationManager locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);
List<String> providerNames = locationManager.getAllProviders();//獲取所有的LocationProvider名稱
StringBuilder stringBuilder = new StringBuilder();
for (Iterator<String> iterator = providerNames.iterator(); iterator.hasNext(); ) {
stringBuilder.append(iterator.next() + "\n");
}
// provider.setText(stringBuilder.toString());
//獲取基于GPS的LocationProvider
LocationProvider locationProvider = locationManager.getProvider(LocationManager.GPS_PROVIDER);
stringBuilder.append("--------------------" + "\n" + locationProvider.getName());
// provider.setText(stringBuilder.toString());
//獲取最佳LocationProvider
Criteria criteria = new Criteria();//創(chuàng)建一個過濾條件對象
criteria.setCostAllowed(false);//不收費的
criteria.setAccuracy(Criteria.ACCURACY_FINE);//使用精度最準確的
criteria.setPowerRequirement(Criteria.POWER_LOW);//使用耗電量最低的
String providerName = locationManager.getBestProvider(criteria, true);//獲取最佳的LocationProvider名稱
stringBuilder.append("\n" + "--------------------" + "\n" + providerName);
provider.setText(stringBuilder.toString());
/* ********************* location詳細信息 *************************** */
LocationManager locationManager1 = (LocationManager) getSystemService(LOCATION_SERVICE);
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// 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 ActivityCompat#requestPermissions for more details.
return;
}
locationManager1.requestLocationUpdates(
LocationManager.GPS_PROVIDER,//指定GPS定位的提供者
1000,//間隔時間
1,//位置間隔距離
new LocationListener() { //監(jiān)聽GPS定位信息是否改變
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {//定位提供者啟動時回調
}
@Override
public void onProviderDisabled(String provider) {//關閉
}
}
);
Location location = locationManager1.getLastKnownLocation(LocationManager.GPS_PROVIDER);//獲取最新的定位信息
locationUpdate(location);//將最新的定位信息傳遞給locationUpdate方法
}
public void locationUpdate(Location location) {
if (location != null) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append("您的位置是:\n");
stringBuilder.append("經(jīng)度:" + location.getLongitude());
stringBuilder.append("\n緯度:" + location.getLatitude());
location_info.setText(stringBuilder.toString());
} else {
location_info.setText("沒有獲取到GPS信息");
}
}
}