- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我设法将 Google Maps API 合并到 TabLayout 中,但它有两个问题。一种是应用程序立即询问用户位置,一种是授予权限,但它不会显示新的更新位置。谁能帮帮我吗?
主要 Activity
public class MainActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener{
private Toolbar toolbar;
private TabLayout tabLayout;
private ViewPager viewPager;
private PagerAdapter pagerAdapter;
private DrawerLayout drawerLayout;
//private ViewPagerAdapter viewPagerAdapter;
private String[] pageTitle = {"myPlanner", "News", "Parking"};
private String studyRooms = "http://library2.csumb.edu/mrbs/mobilenow.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
setSupportActionBar(toolbar);
//create default navigation drawer toggle
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(this, drawerLayout, toolbar,
R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawerLayout.addDrawerListener(toggle);
toggle.syncState();
tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(viewPager);
for (int i = 0; i < 3; i++) {
//TabLayout.Tab tab = tabLayout.getTabAt(i);
//tab.setCustomView(pagerAdapter.getTabView(i));
tabLayout.addTab(tabLayout.newTab().setText(pageTitle[i]));
}
//set gravity for tab bar
tabLayout.setTabGravity(TabLayout.GRAVITY_FILL);
//handling navigation view item event
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
assert navigationView != null;
navigationView.setNavigationItemSelectedListener(this);
viewPager = (ViewPager)findViewById(R.id.view_pager);
pagerAdapter = new PagerAdapter(getSupportFragmentManager(), MainActivity.this);
viewPager.setAdapter(pagerAdapter);
//setting Tab layout (number of Tabs = number of ViewPager pages)
viewPager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tabLayout));
viewPager.setOffscreenPageLimit(3);
tabLayout.addOnTabSelectedListener(new TabLayout.ViewPagerOnTabSelectedListener(viewPager));
}
class PagerAdapter extends FragmentPagerAdapter{
String tabTitles[] = new String[]{"myPlanner", "News", "Parking"};
public Fragment[] fragments = new Fragment[tabTitles.length];
Context context;
public PagerAdapter(FragmentManager fm, Context context){
super(fm);
this.context = context;
}
@Override
public int getCount(){
return tabTitles.length;
}
@Override
public Fragment getItem(int position){
switch (position){
case 0:
return new myPlanner();
case 1:
return new News();
case 2:
return new MapsFragment();
}
return null;
}
public View getTabView(int position) {
View tab = LayoutInflater.from(MainActivity.this).inflate(R.layout.custom_tab, null);
TextView tv = (TextView) tab.findViewById(R.id.custom_text);
tv.setText(tabTitles[position]);
return tab;
}
@Override
public CharSequence getPageTitle(int position){
//Generate title based on item position
return tabTitles[position];
}
@Override
public Object instantiateItem(ViewGroup container, int position){
Fragment createdFragment = (Fragment)super.instantiateItem(container,position);
fragments[position] = createdFragment;
return createdFragment;
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[],int[] grantResults){
if(requestCode == MapsFragment.MY_PERMISSIONS_REQUEST_LOCATION){
MapsFragment mapFragment = (MapsFragment) pagerAdapter.fragments[2];
if(mapFragment != null){
mapFragment.onRequestPermissionsResult(requestCode,permissions,grantResults);
}
}
else{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
/*
Method for the navigation Drawer that takes in the id from the navigation drawer
and based on the view, an action will be performed.
*/
@Override
public boolean onNavigationItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.DinningCommonsItem) {
viewPager.setCurrentItem(0);
} else if (id == R.id.LibraryStudyRooms) {
Uri uri = Uri.parse(studyRooms);
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
startActivity(intent);
// viewPager.setCurrentItem(1);
} else if (id == R.id.MapYourRoute) {
viewPager.setCurrentItem(2);
} else if (id == R.id.CampusPD) {
Intent i = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + "18316550268"));
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} else if (id == R.id.close) {
finish();
}
drawerLayout.closeDrawer(GravityCompat.START);
return true;
}
@Override
public void onBackPressed() {
assert drawerLayout != null;
if (drawerLayout.isDrawerOpen(GravityCompat.START)) {
drawerLayout.closeDrawer(GravityCompat.START);
} else {
super.onBackPressed();
}
}
}
map fragment
public class MapsFragment extends SupportMapFragment implements OnMapReadyCallback,GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener{
GoogleMap mGoogleMap;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
MapView mMapView;
View mView;
LocationManager locationManager;
static final int REQUEST_LOCATION = 1;
@Override
public void onResume() {
super.onResume();
Log.d("MapsFragment", "Inside onResume");
setUpMapIfNeeded();
}
private void setUpMapIfNeeded() {
Log.d("MapsFragment", "Inside setUpMapIfNeeded");
if (mGoogleMap == null) {
getMapAsync(this);
}
}
//This method gets called when the activity's view is obstructed.
@Override
public void onPause() {
super.onPause();
Log.d("MapsFragment", "Inside onPause");
//mMapView.onPause();
//Stop location updates when Activity is no longer active
if(mGoogleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
}
//Call back method for when map is ready to be used.
@Override
public void onMapReady(GoogleMap googleMap){
Log.d("MapsFragment", "Inside onMapReady");
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
//Initialize Google Play Services
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
if(ContextCompat.checkSelfPermission(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
//Location Permission already granted
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}else{
//Request location permission
checkLocationPermission();
}
}
else{
buildGoogleApiClient();
mGoogleMap.setMyLocationEnabled(true);
}
}
private void buildGoogleApiClient() {
Log.d("MapsFragment", "Inside buildGoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
//After calling connect(), this method will be invoked asynch when the
//connect request has successfully completed.
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.d("MapsFragment", "Inside onConnected");
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED){
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
Log.d("MapsFragment", "Inside onLocationChanged");
mLastLocation = location;
if(mCurrLocationMarker != null){
mCurrLocationMarker.remove();
}
//Place current location marker
LatLng latLng = new LatLng(location.getLatitude(),location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
mCurrLocationMarker = mGoogleMap.addMarker(markerOptions);
//Move map Camera
mGoogleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
mGoogleMap.animateCamera(CameraUpdateFactory.zoomBy(11));
//Optionally, stop location updates if only current location is needed
if(mGoogleApiClient != null){
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient,this);
}
}
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void checkLocationPermission() {
Log.d("MapsFragment", "Inside checkLocationPermission");
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED){
//Should we show an explanation?
if(ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
Manifest.permission.ACCESS_FINE_LOCATION)){
//Show an explanation to the user *asyncly* -- dont block
//this thread waiting for the user's response! After the user
//sees the explanation try again to request the permission
new AlertDialog.Builder(getActivity())
.setTitle("Location permission needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
//prompt the user once the explanation has been shown
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
}
else{
//NO explanation needed, we can request the permission.
ActivityCompat.requestPermissions(getActivity(),
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[]
, int[] grantResults){
Log.d("MapsFragment", "Inside onRequestPermissionsResult");
switch (requestCode){
case MY_PERMISSIONS_REQUEST_LOCATION:{
//If request is cancelled, the results arrays are empty
if(grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Permission was granted do the location-related task you need to do.
if(ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED){
if(mGoogleApiClient == null){
buildGoogleApiClient();
}
mGoogleMap.setMyLocationEnabled(true);
}
}
else{
//permissions were denied. Disable the functionality that depends onthis permission
Toast.makeText(getActivity(), "Permission denied",Toast.LENGTH_LONG).show();
}
return;
}//Other case lines to check for other permissions this app might request
}
}
最佳答案
请尝试这个类(class),它运行良好。
public class MapsFragmentDemo extends com.google.android.gms.maps.MapFragment implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks,
GoogleApiClient.OnConnectionFailedListener, LocationListener {
private static final int REQUEST_LOCATION = 1;
private final int REQUEST_CHECK_SETTINGS = 300;
GoogleMap mGoogleMap;
LocationRequest mLocationRequest;
GoogleApiClient mGoogleApiClient;
Location mLastLocation;
Marker mCurrLocationMarker;
boolean isFragmentVisible = false;
private LocationSettingsRequest.Builder builder;
private PendingResult<LocationSettingsResult> result;
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
isFragmentVisible = true;
Log.d("MapsFragment", "Inside Visible");
getMapAsync(this);
createLocationRequest();
buildGoogleApiClient();
}
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(1000);
mLocationRequest.setFastestInterval(1000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
mLocationRequest.setSmallestDisplacement(.5f);
}
@Override
public void onResume() {
super.onResume();
Log.d("MapsFragment", "Inside onResume");
if (isFragmentVisible) {
Log.d("MapsFragment", "Inside onResume true");
if (mGoogleApiClient != null && mGoogleApiClient.isConnected()) {
if (checkAccessPermission())
startLocationUpdates();
else
askForPermission();
}
}
}
@Override
public void onPause() {
super.onPause();
Log.d("MapsFragment", "Inside onPause");
stopLocationUpdates();
}
@Override
public void onStop() {
super.onStop();
Log.d("MapsFragment", "onStop fired ..............");
if (mGoogleApiClient != null && !mGoogleApiClient.isConnected())
mGoogleApiClient.disconnect();
}
protected void stopLocationUpdates() {
if (mGoogleApiClient != null)
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
protected void startLocationUpdates() {
if (mGoogleApiClient != null) {
accessLocation();
}
}
private boolean checkAccessPermission() {
return (ContextCompat.checkSelfPermission(getActivity(), android.Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED);
}
@SuppressWarnings("MissingPermission")
private void accessLocation() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
if (mGoogleMap != null)
mGoogleMap.setMyLocationEnabled(true);
}
private void askForPermission() {
// Should we show an explanation?
if (android.support.v4.app.ActivityCompat.shouldShowRequestPermissionRationale(getActivity(),
android.Manifest.permission.ACCESS_FINE_LOCATION)) {
new AlertDialog.Builder(getActivity())
.setTitle("Location permission needed")
.setMessage("This app needs the Location permission, please accept to use location functionality")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int i) {
//prompt the user once the explanation has been shown
FragmentCompat.requestPermissions(MapsFragmentDemo.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
}
})
.create()
.show();
} else
FragmentCompat.requestPermissions(MapsFragmentDemo.this,
new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION},
REQUEST_LOCATION);
}
//Call back method for when map is ready to be used.
@Override
public void onMapReady(GoogleMap googleMap) {
Log.d("MapsFragment", "Inside onMapReady");
mGoogleMap = googleMap;
mGoogleMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
}
private void buildGoogleApiClient() {
Log.d("MapsFragment", "Inside buildGoogleApiClient");
mGoogleApiClient = new GoogleApiClient.Builder(getActivity())
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mGoogleApiClient.connect();
}
@Override
public void onConnected(@Nullable Bundle bundle) {
Log.d("MapsFragment", "Inside onConnected");
builder = new LocationSettingsRequest.Builder().addLocationRequest(mLocationRequest);
result = LocationServices.SettingsApi.checkLocationSettings(mGoogleApiClient, builder.build());
result.setResultCallback(new ResultCallback<LocationSettingsResult>() {
@Override
public void onResult(LocationSettingsResult result) {
final Status status = result.getStatus();
final LocationSettingsStates mState = result.getLocationSettingsStates();
switch (status.getStatusCode()) {
case LocationSettingsStatusCodes.SUCCESS:
if (!checkAccessPermission()) {
askForPermission();
} else
startLocationUpdates();
break;
case LocationSettingsStatusCodes.RESOLUTION_REQUIRED:
try {
status.startResolutionForResult(getActivity(), REQUEST_CHECK_SETTINGS);
} catch (IntentSender.SendIntentException e) {
}
break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
break;
}
}
});
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case REQUEST_CHECK_SETTINGS:
switch (resultCode) {
case Activity.RESULT_OK:
if (!checkAccessPermission()) {
askForPermission();
} else
startLocationUpdates();
break;
case Activity.RESULT_CANCELED:
break;
}
break;
}
}
@Override
public void onConnectionSuspended(int i) {
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
}
@Override
public void onLocationChanged(Location location) {
mGoogleMap.clear();
Log.d("MapsFragment", "Inside onLocationChanged");
LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
MarkerOptions markerOptions = new MarkerOptions();
markerOptions.position(latLng);
markerOptions.title("Current Position");
markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
Marker currLocationMarker = mGoogleMap.addMarker(markerOptions);
CameraPosition cameraPosition = new CameraPosition.Builder()
.target(latLng).zoom(14).build();
mGoogleMap.animateCamera(CameraUpdateFactory
.newCameraPosition(cameraPosition));
//Optionally, stop location updates if only current location is needed
if (mGoogleApiClient != null) {
stopLocationUpdates();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String permissions[]
, int[] grantResults) {
Log.d("MapsFragment", "Inside onRequestPermissionsResult");
switch (requestCode) {
case REQUEST_LOCATION: {
//If request is cancelled, the results arrays are empty
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
accessLocation();
} else {
// permission was denied
Toast.makeText(getActivity(), "Permission denied", Toast.LENGTH_LONG).show();
}
return;
}//Other case lines to check for other permissions this app might request
}
}
}
关于java - TabLayout 在 TabLayout 内请求权限后不更新用户位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42662976/
我正在尝试从该网站抓取历史天气数据: http://www.hko.gov.hk/cis/dailyExtract_uc.htm?y=2016&m=1 在阅读了 AJAX 调用后,我发现请求数据的正确
我有两个 postman 请求 x,y,它们命中了两个不同的休息 api X,Y 中的端点。 x 会给我一个身份验证 token ,这是发出 y 请求所必需的。如何在请求 y 中发出请求 x ?也就是
我使用请求库通过 API 与其他服务器进行通信。但现在我需要同时发送多个(10 个或更多)POST 请求,并且只有在所有响应都正确的情况下才能进一步前进。通常语法看起来有点像这样: var optio
背景:当用户单击按钮时,其类会在class1和class2之间切换,并且此数据是通过 AJAX 提交。为了确认此数据已保存,服务器使用 js 进行响应(更新按钮 HTML)。 问题:如果用户点击按钮的
我正在将 Node.js 中的请求库用于 Google 的文本转语音 API。我想打印出正在发送的请求,如 python example . 这是我的代码: const request = requi
我经常使用requests。最近我发现还有一个 requests2 和即将到来的 requests3 虽然有一个 page其中简要提到了 requests3 中的内容,我一直无法确定 requests
我正在尝试将图像发送到我的 API,然后从中获取结果。例如,我使用发送一个 bmp 图像文件 file = {"img": open("img.bmp)} r = requests.post(url,
我发现 Google Cloud 确保移出其物理环境的任何请求都经过强制加密,请参阅(虚拟机到虚拟机标题下的第 6 页)this link Azure(和 AWS)是否遵循类似的程序?如果有人能给我指
我有一个 ASP.NET MVC 应用程序,我正在尝试在 javascript 函数中使用 jQuery 来创建一系列操作。该函数由三部分组成。 我想做的是:如果满足某些条件,那么我想执行同步 jQu
我找不到如何执行 get http 请求,所以我希望你们能帮助我。 这个想法是从外部url(例如 https://api.twitter.com/1.1/search/tweets.json?q=tw
我的应用只需要使用“READ_SMS”权限。我的问题是,在 Android 6.0 上,当我需要使用新的权限系统时,它会要求用户“发送和查看短信”。 这是我的代码: ActivityCompat.re
我的前端代码: { this.searchInput = input; }}/> 搜索 // search method: const baseUrl = 'http://localho
我有一个由 AJAX 和 C# 应用程序使用的 WCF 服务, 我需要通过 HTTP 请求 header 发送一个参数。 在我的 AJAX 上,我添加了以下内容并且它有效: $.ajax({
我正在尝试了解如何使用 promises 编写代码。请检查我的代码。这样对吗? Node.js + 请求: request(url, function (error, response, body)
如果失败(除 HTTP 200 之外的任何响应代码),我需要重试发送 GWT RPC 请求。原因很复杂,所以我不会详细说明。到目前为止,我在同一个地方处理所有请求响应,如下所示: // We
当用户单击提交按钮时,我希望提交表单。然而,就在这种情况发生之前,我希望弹出一个窗口并让他们填写一些数据。一旦他们执行此操作并关闭该子窗口,我希望发出 POST 请求。 这可能吗?如果可能的话如何?我
像 Facebook 这样的网站使用“延迟”加载 js。当你必须考虑到我有一台服务器,流量很大时。 我很感兴趣 - 哪一个更好? 当我一次执行更多 HTTP 请求时 - 页面加载速度较慢(由于限制(一
Servlet 容器是否创建 ServletRequest 和 Response 对象或 Http 对象?如果是ServletRequest,谁在调用服务方法之前将其转换为HttpServletReq
这是维基百科文章的摘录: In contrast to the GET request method where only a URL and headers are sent to the serv
我有一个循环,每次循环时都会发出 HTTP post 请求。 for(let i = 1; i console.log("succes at " + i), error => con
我是一名优秀的程序员,十分优秀!