編輯:關於Android編程
今天試了下webview裡面的定位,找了好多資料,由於同事和我的手機基本上是andriod6.0的了,我測試了好幾次,老是顯示未授權,明明已經給它授權了,後來我才想到andriod6.0是有授權問題的,下面上代碼,先是webview下gps定位的:
public class MainActivity extends AppCompatActivity {
/**
* ATTENTION: This was auto-generated to implement the App Indexing API.
* See https://g.co/AppIndexing/AndroidStudio for more information.
*/
EditText mText;
private LocationManager lm;
private static final String TAG = "MainActivity";
String bestProvider;
String provider;
private WebView webView;
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
Log.e(TAG, "onRequestPermissionsResult");
//requestpermisiion result , permission
}
@Override
protected void onDestroy() {
super.onDestroy();
if (lm != null) {
lm.removeGpsStatusListener(listener);
}
}
//位置監聽
public LocationListener locationListener = new LocationListener() {
/**
* 位置信息變化時觸發
*/
@Override
public void onLocationChanged(Location location) {
updateView(location);
Log.e(TAG, "時間:" + location.getTime());
Log.e(TAG, "經度:" + location.getLongitude());
Log.e(TAG, "緯度:" + location.getLatitude());
Log.e(TAG, "海拔:" + location.getAltitude());
}
/**
* GPS狀態變化時觸發
*/
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
Log.e(TAG, "onStatusChanged status=" + status);
switch (status) {
//GPS狀態為可見時
case LocationProvider.AVAILABLE:
Log.i(TAG, "當前GPS狀態為可見狀態");
break;
//GPS狀態為服務區外時
case LocationProvider.OUT_OF_SERVICE:
Log.i(TAG, "當前GPS狀態為服務區外狀態");
break;
//GPS狀態為暫停服務時
case LocationProvider.TEMPORARILY_UNAVAILABLE:
Log.i(TAG, "當前GPS狀態為暫停服務狀態");
break;
}
}
/**
* GPS開啟時觸發
*/
@Override
public void onProviderEnabled(String provider) {
Log.e(TAG, "onProviderEnabled");
if (Build.VERSION.SDK_INT >= 23) {
int checkPermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (checkPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION}, 1);
//ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
Log.d("TTTT", "彈出提示");
}
}
Location location = lm.getLastKnownLocation(provider);
updateView(location);
}
/**
* GPS禁用時觸發
*/
@Override
public void onProviderDisabled(String provider) {
updateView(null);
}
};
//狀態監聽
GpsStatus.Listener listener = new GpsStatus.Listener() {
public void onGpsStatusChanged(int event) {
Log.e(TAG, "onGpsStatusChanged event =" + event);
switch (event) {
//第一次定位
case GpsStatus.GPS_EVENT_FIRST_FIX:
Log.i(TAG, "第一次定位");
break;
//衛星狀態改變
case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
Log.i(TAG, "衛星狀態改變");
//獲取當前狀態
GpsStatus gpsStatus = lm.getGpsStatus(null);
//獲取衛星顆數的默認最大值
int maxSatellites = gpsStatus.getMaxSatellites();
//創建一個迭代器保存所有衛星
Iterator iters = gpsStatus.getSatellites().iterator();
int count = 0;
while (iters.hasNext() && count <= maxSatellites) {
GpsSatellite s = iters.next();
count++;
}
System.out.println("搜索到:" + count + "顆衛星");
break;
//定位啟動
case GpsStatus.GPS_EVENT_STARTED:
Log.i(TAG, "定位啟動");
break;
//定位結束
case GpsStatus.GPS_EVENT_STOPPED:
Log.i(TAG, "定位結束");
break;
}
}
;
};
@Override
protected void onResume() {
super.onResume();
if (Build.VERSION.SDK_INT >= 23) {
int checkPermission = ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.ACCESS_COARSE_LOCATION);
if (checkPermission != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);
Log.d("TTTT", "彈出提示");
}
}
//為獲取地理位置信息時設置查詢條件
bestProvider = lm.getBestProvider(getCriteria(), true);
//獲取位置信息
//如果不設置查詢要求,getLastKnownLocation方法傳人的參數為LocationManager.GPS_PROVIDER
Location location;
location = lm.getLastKnownLocation(bestProvider);
updateView(location);
//監聽狀態
lm.addGpsStatusListener(listener);
//綁定監聽,有4個參數
//參數1,設備:有GPS_PROVIDER和NETWORK_PROVIDER兩種
//參數2,位置信息更新周期,單位毫秒
//參數3,位置變化最小距離:當位置距離變化超過此值時,將更新位置信息
//參數4,監聽
//備注:參數2和3,如果參數3不為0,則以參數3為准;參數3為0,則通過時間來定時更新;兩者為0,則隨時刷新
// 1秒更新一次,或最小位移變化超過1米更新一次;
//注意:此處更新准確度非常低,推薦在service裡面啟動一個Thread,在run中sleep(10000);然後執行handler.sendMessage(),更新位置
lm.requestLocationUpdates(LocationManager.GPS_PROVIDER, 1000, 1, locationListener);
// ATTENTION: This was auto-generated to implement the App Indexing API.
// See https://g.co/AppIndexing/AndroidStudio for more information.
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
lm = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
//判斷GPS是否正常啟動
if (!lm.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
Toast.makeText(this, "請開啟GPS導航...", Toast.LENGTH_SHORT).show();
//返回開啟GPS導航設置界面
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivityForResult(intent, 0);
return;
}
WebSettings settings = webView.getSettings();
settings.setJavaScriptEnabled(true);
settings.setGeolocationEnabled(true);
settings.setGeolocationDatabasePath(getFilesDir().getPath());
webView.setWebChromeClient(new WebChromeClient() {
@Override
public void onGeolocationPermissionsHidePrompt() {
super.onGeolocationPermissionsHidePrompt();
Log.i("test", "onGeolocationPermissionsHidePrompt");
}
//網頁權限彈窗
@Override
public void onGeolocationPermissionsShowPrompt(final String origin,
final GeolocationPermissions.Callback callback) {
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setMessage("Allow to access location information?");
DialogInterface.OnClickListener dialogButtonOnClickListener = new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int clickedButton) {
if (DialogInterface.BUTTON_POSITIVE == clickedButton) {
callback.invoke(origin, true, true);
} else if (DialogInterface.BUTTON_NEGATIVE == clickedButton) {
callback.invoke(origin, false, false);
}
}
};
builder.setPositiveButton("Allow", dialogButtonOnClickListener);
builder.setNegativeButton("Deny", dialogButtonOnClickListener);
builder.show();
super.onGeolocationPermissionsShowPrompt(origin, callback);
Log.i("test", "onGeolocationPermissionsShowPrompt");
}
});
webView.loadUrl("file:///android_asset/test.html");
}
//在java中調用js代碼
public void sendInfoToJs(View view) {
String msg = mText.getText().toString();
//調用js中的函數:showInfoFromJava(msg)
webView.loadUrl("javascript:showInfoFromJava('" + msg + "')");
}
private void initView() {
mText = (EditText) this.findViewById(R.id.showresult);
webView = (WebView) findViewById(R.id.webView);
}
/**
* 實時更新文本內容
*
* @param location
*/
private void updateView(Location location) {
if (location != null) {
mText.setText("設備位置信息\n\n經度:");
mText.append(String.valueOf(location.getLongitude()));
mText.append("\n緯度:");
mText.append(String.valueOf(location.getLatitude()));
} else {
//清空EditText對象
mText.getEditableText().clear();
}
}
/**
* 返回查詢條件
*
* @return
*/
private Criteria getCriteria() {
Criteria criteria = new Criteria();
//設置定位精確度 Criteria.ACCURACY_COARSE比較粗略,Criteria.ACCURACY_FINE則比較精細
criteria.setAccuracy(Criteria.ACCURACY_FINE);
//設置是否要求速度
criteria.setSpeedRequired(false);
// 設置是否允許運營商收費
criteria.setCostAllowed(false);
//設置是否需要方位信息
criteria.setBearingRequired(false);
//設置是否需要海拔信息
criteria.setAltitudeRequired(false);
// 設置對電源的需求
criteria.setPowerRequirement(Criteria.POWER_LOW);
return criteria;
}
}
gps室內定位不是很靈敏不過可以網絡定位
前言在前面的文章中我們講述了Android動畫之視圖動畫學習了怎麼對一個view實現動畫,可以實現動畫包括平移,旋轉,縮放,漸變和幀動畫,這一篇我們來學習一個新的動畫實現
在app中經常會用到底部菜單的控件,每次都需要寫好多代碼,今天我們用到了前幾篇博客裡的控件來進一步封裝底部菜單。先看效果圖:主要包括以下功能: 1 設置icon以及點擊之
前言 打造一款完整可用的Android播放器有許多功能和細節需要完成,也涉及到各種豐富的知識和內容,本章將結合Fragment、ViewPager來搭建播放器的
ChangeMode項目地址:ChangeMode Implementation of night mode for Android. 用最簡單的方式實現夜間模式,支持L