针对如何使用CompletionHandlers和小于请求的ByteBuffer读取请求?和querywrapper小于这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展ByteBuffer/
针对如何使用CompletionHandlers和小于请求的ByteBuffer读取请求?和querywrapper小于这两个问题,本篇文章进行了详细的解答,同时本文还将给你拓展ByteBuffer / IntBuffer / ShortBuffer Java类是否快速?、com.google.android.gms.location.places.AutocompletePredictionBuffer的实例源码、didReceiveRemoteNotification: fetchCompletionHandler 当应用程序处于后台和非活动状态时不被调用、FileChannel 使用ByteBuffer 和 Protostuff 从文件中读写 对象信息等相关知识,希望可以帮助到你。
本文目录一览:- 如何使用CompletionHandlers和小于请求的ByteBuffer读取请求?(querywrapper小于)
- ByteBuffer / IntBuffer / ShortBuffer Java类是否快速?
- com.google.android.gms.location.places.AutocompletePredictionBuffer的实例源码
- didReceiveRemoteNotification: fetchCompletionHandler 当应用程序处于后台和非活动状态时不被调用
- FileChannel 使用ByteBuffer 和 Protostuff 从文件中读写 对象信息
如何使用CompletionHandlers和小于请求的ByteBuffer读取请求?(querywrapper小于)
我正在使用Java
7和AsynchronousSocketChannel
。我想读取一个请求(例如HTTPPOST
),但如果它大于ByteBuffer
我正在使用的大小,则我正在努力想出一个很好的解决方案来读取完整的请求。例如,如果ByteBuffer
是4048字节,并且HTTP
POST包含大于4kB的图像。
有没有很好的递归解决方案或循环呢?
这是我的阅读请求代码:
public void readRequest(final AsynchronousSocketChannel ch) { final ByteBuffer buffer = ByteBuffer.allocate(BUFFER_SIZE); final StringBuilder strBuilder = new StringBuilder(); final CharsetDecoder decoder = Charset.forName("US-ASCII").newDecoder(); ch.read(buffer, null, new CompletionHandler<Integer, Void>() { public void completed(Integer bytes, Void att) { buffer.flip(); try { decoder.reset(); strBuilder.append(decoder.decode(buffer).toString()); } catch (CharacterCodingException e) { e.printStackTrace(); } buffer.clear(); // More data to read or send response if(bytes != -1) { // More data to read ch.read(...); } else { // Create and send a response } } public void failed(Throwable exc, Void att) { exc.printStackTrace(); } });}
在我写过的地方:
// More data to readch.read(...);
它看起来像是代码重用的好地方,但是我无法提出一个好的解决方案。有什么办法可以在这里重用CompletionHandler吗?有什么建议阅读有限的完整请求ByteBuffer
吗?
我想以一种非阻塞和异步的方式解决这个问题。
答案1
小编典典completed
当读取数据块时,从java管理的线程异步调用该方法。要重用CompletionHandler:
// More data to readch.read(buffer, null, this); //here you pass the same CompletionHandler you are using
Java专家建议,当您完成读取操作(该else
块)时,应使用另一个线程上下文。
这是为了避免在a内部阻塞和长期运行的文档CompletionHandler
,请参见第33页http://openjdk.java.net/projects/nio/presentations/TS-4222.pdf
ByteBuffer / IntBuffer / ShortBuffer Java类是否快速?
我正在研究Android应用程序(显然是Java),最近我更新了我的UDP阅读器代码.在这两个版本中,我设置了一些缓冲区并接收UDP数据包:
byte[] buf = new byte[10000];
short[] soundData = new short[1000];
DatagramPacket packet = new DatagramPacket (buf,buf.length);
socket.receive (packet);
在初始版本中,我将数据一次放回一个字节(实际上是16个PCM音频数据):
for (int i = 0; i < count; i++)
soundData[i] = (short) (((buf[k++]&0xff) << 8) + (buf[k++]&0xff));
在更新的版本中,我使用了一些我开始时不知道的很酷的Java工具:
bBuffer = ByteBuffer.wrap (buf);
sBuffer = bBuffer.asShortBuffer();
sBuffer.get (soundData,count);
在这两种情况下,“计数”正在正确填充(我检查过).然而,我的流媒体音频似乎出现了新的问题 – 也许它的处理速度不够快 – 这对我来说没有任何意义.显然,缓冲区代码正在编译成三个以上的JVM代码语句,但是当我开始这个时,第二个版本会比第一个版本更快,这似乎是一个合理的假设.
很明显,我并不是说我的代码必须使用Java NIO缓冲区,但至少乍一看,它看起来似乎很难做到这一点.
任何人都有一个快速,简单的Java UDP阅读器的建议,以及是否有一个普遍接受的“最佳方式”?
谢谢,
R.
有理由使用速度以外的实用程序对象:方便性,安全性等.
在这种特殊情况下测试差异的最佳方法是实际测量它.尝试使用大型数据集的两种方法并计时.然后,您可以决定在这种情况下是否值得获益.
您还可以使用Android的分析器来查看问题的确切位置.见TraceView.
com.google.android.gms.location.places.AutocompletePredictionBuffer的实例源码
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) { if (mGoogleapiclient.isConnected()) { PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi .getAutocompletePredictions(mGoogleapiclient,constraint.toString(),mBounds,mPlaceFilter); AutocompletePredictionBuffer autocompletePredictions = results .await(60,TimeUnit.SECONDS); final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { Toast.makeText(getContext(),"Error contacting API: " + status.toString(),Toast.LENGTH_SHORT).show(); autocompletePredictions.release(); return null; } return DataBufferUtils.freezeAndClose(autocompletePredictions); } return null; }
public Observable<PlacePrediction> getAutocompleteResults(final Googleapiclient mGoogleapiclient,final String query,final LatLngBounds bounds) { return Observable.create(new Observable.OnSubscribe<PlacePrediction>() { @Override public void call(Subscriber<? super PlacePrediction> subscriber) { PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi.getAutocompletePredictions(mGoogleapiclient,query,bounds,null); AutocompletePredictionBuffer autocompletePredictions = results .await(60,TimeUnit.SECONDS); final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { autocompletePredictions.release(); subscriber.onError(null); } else { for (AutocompletePrediction autocompletePrediction : autocompletePredictions) { subscriber.onNext( new PlacePrediction( autocompletePrediction.getPlaceId(),autocompletePrediction.getDescription() )); } autocompletePredictions.release(); subscriber.onCompleted(); } } }); }
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) { if (mGoogleapiclient.isConnected()) { PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi.getAutocompletePredictions(mGoogleapiclient,mPlaceFilter); AutocompletePredictionBuffer autocompletePredictions = results.await(60,TimeUnit.SECONDS); final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { Toast.makeText(getContext(),Toast.LENGTH_SHORT).show(); autocompletePredictions.release(); return null; } return DataBufferUtils.freezeAndClose(autocompletePredictions); } return null; }
private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) { if (mGoogleapiclient.isConnected()) { PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi .getAutocompletePredictions(mGoogleapiclient,mPlaceFilter); AutocompletePredictionBuffer autocompletePredictions = results .await(60,TimeUnit.SECONDS); final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { if (callback != null) callback.onSuggestFail(status); autocompletePredictions.release(); return null; } return DataBufferUtils.freezeAndClose(autocompletePredictions); } return null; }
private ArrayList<PlaceAutocomplete> getPredictions(CharSequence constraint) { if (mGoogleapiclient != null) { Log.i(TAG,"Executing autocomplete query for: " + constraint); PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi .getAutocompletePredictions(mGoogleapiclient,mPlaceFilter); // Wait for predictions,set the timeout. AutocompletePredictionBuffer autocompletePredictions = results .await(60,TimeUnit.SECONDS); final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { Toast.makeText(getContext(),"We recommend using internet for better accuracy of the location! ",Toast.LENGTH_SHORT).show(); Log.e(TAG,"Error getting place predictions: " + status.toString()); autocompletePredictions.release(); return null; } Log.i(TAG,"Query completed. Received " + autocompletePredictions.getCount() + " predictions."); Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator(); ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount()); while (iterator.hasNext()) { AutocompletePrediction prediction = iterator.next(); resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),prediction.getFullText(null))); } // Buffer release autocompletePredictions.release(); return resultList; } Log.e(TAG,"Google Api client is not connected."); return null; }
/** * Method to call API for each user input * @param constraint User input character string * @return ArrayList containing suggestion results */ private ArrayList<PlaceAutoComplete> getAutoComplete(CharSequence constraint){ if(mGoogleapiclient.isConnected()){ //Making a query and fetching result in a pendingResult PendingResult<AutocompletePredictionBuffer> results= Places.GeoDataApi .getAutocompletePredictions(mGoogleapiclient,mPlaceFilter); //Block and wait for 60s for a result AutocompletePredictionBuffer autocompletePredictions=results.await(60,TimeUnit.SECONDS); final Status status=autocompletePredictions.getStatus(); // Confirm that the query completed successfully,otherwise return null if(!status.isSuccess()){ Log.e(TAG,"Error getting autocomplete prediction API call: " + status.toString()); autocompletePredictions.release(); return null; } Log.i(TAG,"Query completed. Received " + autocompletePredictions.getCount() + " predictions."); // copy the results into our own data structure,because we can't hold onto the buffer. // AutocompletePrediction objects encapsulate the API response (place ID and description). Iterator<AutocompletePrediction> iterator=autocompletePredictions.iterator(); ArrayList resultList=new ArrayList<>(autocompletePredictions.getCount()); while(iterator.hasNext()){ AutocompletePrediction prediction=iterator.next(); resultList.add(new PlaceAutoComplete(prediction.getPlaceId(),prediction.getPrimaryText(null),prediction.getSecondaryText(null))); } autocompletePredictions.release(); return resultList; }else{ Log.e(TAG,"Googleapiclient Not Connected"); return null; } }
private ArrayList<PlaceAutocomplete> getPredictions(CharSequence constraint) { if (mGoogleapiclient != null) { Log.i(TAG,"Error: " + status.toString(),Toast.LENGTH_SHORT).show(); Log.e(TAG,"Error getting place predictions: " + status .toString()); autocompletePredictions.release(); return null; } Log.i(TAG,"Google Api client is not connected."); return null; }
/** * Submits an autocomplete query to the Places Geo Data Autocomplete API. * Results are returned as frozen AutocompletePrediction objects,ready to be cached. * objects to store the Place ID and description that the API returns. * Returns an empty list if no results were found. * Returns null if the API client is not available or the query did not complete * successfully. * This method MUST be called off the main UI thread,as it will block until data is returned * from the API,which may include a network request. * * @param constraint Autocomplete query string * @return Results from the autocomplete API or null if the query was not successful. * @see Places#GEO_DATA_API#getAutocomplete(CharSequence) * @see AutocompletePrediction#freeze() */ private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) { if (mGoogleapiclient.isConnected()) { Log.i(TAG,"Starting autocomplete query for: " + constraint); // Submit the query to the autocomplete API and retrieve a PendingResult that will // contain the results when the query completes. PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi .getAutocompletePredictions(mGoogleapiclient,mPlaceFilter); // This method should have been called off the main UI thread. Block and wait for at most 60s // for a result from the API. AutocompletePredictionBuffer autocompletePredictions = results .await(60,TimeUnit.SECONDS); // Confirm that the query completed successfully,otherwise return null final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { Toast.makeText(getContext(),"Query completed. Received " + autocompletePredictions.getCount() + " predictions."); // Freeze the results immutable representation that can be stored safely. return DataBufferUtils.freezeAndClose(autocompletePredictions); } Log.e(TAG,"Google Api client is not connected for autocomplete query."); return null; }
/** * Submits an autocomplete query to the Places Geo Data Autocomplete API. * Results are returned as frozen AutocompletePrediction objects,ready to be cached. * objects to store the Place ID and description that the API returns. * Returns an empty list if no results were found. * Returns null if the API client is not available or the query did not statusComplete * successfully. * This method MUST be called off the main UI thread,as it will block until data is returned * from the API,which may include a network request. * * @param constraint Autocomplete query string * @return Results from the autocomplete API or null if the query was not successful. * @see Places#GEO_DATA_API#getAutocomplete(CharSequence) * @see AutocompletePrediction#freeze() */ private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) { if (mGoogleapiclient.isConnected()) { // // constraint = constraint + " " +mConstraint; // Submit the query to the autocomplete API and retrieve a PendingResult that will // contain the results when the query completes. PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi .getAutocompletePredictions(mGoogleapiclient,mPlaceFilter); // This method should have been called off the main UI thread. Block and wait for at most 60s // for a result from the API. AutocompletePredictionBuffer autocompletePredictions = results .await(60,TimeUnit.SECONDS); // Confirm that the query completed successfully,otherwise return null final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { Toast.makeText(getContext(),"Check your internet connection",Toast.LENGTH_SHORT).show(); autocompletePredictions.release(); return null; } // Freeze the results immutable representation that can be stored safely. return DataBufferUtils.freezeAndClose(autocompletePredictions); } return null; }
private ArrayList<PlaceAutocomplete> getPredictions(CharSequence constraint) { if (mGoogleapiclient != null) { Log.i(TAG,"Google Api client is not connected."); return null; }
/** * Submits an autocomplete query to the Places Geo Data Autocomplete API. * Results are returned as frozen AutocompletePrediction objects,which may include a network request. * * @param constraint Autocomplete query string * @return Results from the autocomplete API or null if the query was not successful. * @see Places#GEO_DATA_API#getAutocomplete(CharSequence) * @see AutocompletePrediction#freeze() */ private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) { if (mGoogleapiclient.isConnected()) { // Submit the query to the autocomplete API and retrieve a PendingResult that will // contain the results when the query completes. PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi .getAutocompletePredictions(mGoogleapiclient,Toast.LENGTH_SHORT).show(); autocompletePredictions.release(); return null; } // Freeze the results immutable representation that can be stored safely. return DataBufferUtils.freezeAndClose(autocompletePredictions); } return null; }
/** * Submits an autocomplete query to the Places Geo Data Autocomplete API. * Results are returned as frozen AutocompletePrediction objects,ready to be cached. * objects to store the Place ID and description that the API returns. * Returns an empty list if no results were found. * Returns null if the API client is not available or the query did not complete * successfully. * This method MUST be called off the main UI thread,which may include a network request. * * @param constraint Autocomplete query string * @return Results from the autocomplete API or null if the query was not successful. * @see Places#GEO_DATA_API#getAutocomplete(CharSequence) * @see AutocompletePrediction#freeze() */ private ArrayList<AutocompletePrediction> getAutocomplete(CharSequence constraint) { if (mGoogleapiclient.isConnected()) { // Log.i(TAG,"Starting autocomplete query for: " + constraint); // Submit the query to the autocomplete API and retrieve a PendingResult that will // contain the results when the query completes. PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi .getAutocompletePredictions(mGoogleapiclient,mPlaceFilter); // This method should have been called off the main UI thread. Block and wait for at most 60s // for a result from the API. AutocompletePredictionBuffer autocompletePredictions = results .await(60,Toast.LENGTH_SHORT).show(); // Log.e(TAG,"Error getting autocomplete prediction API call: " + status.toString()); autocompletePredictions.release(); return null; } // Log.i(TAG,"Query completed. Received " + autocompletePredictions.getCount() // + " predictions."); // Freeze the results immutable representation that can be stored safely. return DataBufferUtils.freezeAndClose(autocompletePredictions); } // Log.e(TAG,"Google Api client is not connected for autocomplete query."); return null; }
private void displayPredictiveResults( String query ) { //Southwest corner to northeast corner. LatLngBounds bounds = new LatLngBounds( new LatLng( 39.906374,-105.122337 ),new LatLng( 39.949552,-105.068779 ) ); //Filter: https://developers.google.com/places/supported_types#table3 List<Integer> filterTypes = new ArrayList<Integer>(); filterTypes.add( Place.TYPE_ESTABLISHMENT ); Places.GeoDataApi.getAutocompletePredictions( mGoogleapiclient,AutocompleteFilter.create( filterTypes ) ) .setResultCallback ( new ResultCallback<AutocompletePredictionBuffer>() { @Override public void onResult( AutocompletePredictionBuffer buffer ) { if( buffer == null ) return; if( buffer.getStatus().isSuccess() ) { for( AutocompletePrediction prediction : buffer ) { //Add as a new item to avoid IllegalArgumentsException when buffer is released add( new AutoCompletePlace( prediction.getPlaceId(),prediction.getDescription() ) ); } } //Prevent memory leak by releasing buffer buffer.release(); } },60,TimeUnit.SECONDS ); }
public Observable<Iterable<AutocompletePrediction>> queryAutocompletion(final String s) { if (!googleapiclient.isConnected()) { Timber.w("Googleapiclient is not connected"); return Observable.empty(); } return Observable.create(new Observable.OnSubscribe<Iterable<AutocompletePrediction>>() { @Override public void call(final Subscriber<? super Iterable<AutocompletePrediction>> subscriber) { LatLngBounds bounds = LatLngBounds.builder() .include(location) .build(); final PendingResult<AutocompletePredictionBuffer> result = Places.GeoDataApi .getAutocompletePredictions(googleapiclient,s,null); result.setResultCallback(new ResultCallback<AutocompletePredictionBuffer>() { @Override public void onResult(AutocompletePredictionBuffer autocompletePredictions) { subscriber.onNext(autocompletePredictions); autocompletePredictions.release(); subscriber.onCompleted(); } }); } }); }
/** * Submits an autocomplete query to the Places Geo Data Autocomplete API. * <p/> * objects to store the Place ID and description that the API returns. * Returns an empty list if no results were found. * Returns null if the API client is not available or the query did not complete * successfully. * This method MUST be called off the main UI thread,which may include a network request. * * @param constraint Autocomplete query string * @return Results from the autocomplete API or null if the query was not successful. * @see Places#GEO_DATA_API#getAutocomplete(CharSequence) */ private ArrayList<PlaceAutocomplete> getAutocomplete(CharSequence constraint) { if (mGoogleapiclient.isConnected()) { Log.i(TAG,"Please check your internet connection","Error getting autocomplete prediction API call: " + status.getStatusMessage()+status.getStatus().getStatusMessage()); autocompletePredictions.release(); return null; } Log.i(TAG,because we can't hold onto the buffer. // AutocompletePrediction objects encapsulate the API response (place ID and description). Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator(); ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount()); while (iterator.hasNext()) { AutocompletePrediction prediction = iterator.next(); // Get the details of this prediction and copy it into a new PlaceAutocomplete object. resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),prediction.getFullText(null))); } // Release the buffer Now that all data has been copied. autocompletePredictions.release(); return resultList; } Log.e(TAG,"Google Api client is not connected for autocomplete query."); return null; }
public Observable<Collection<NiboSearchSuggestionItem>> getSuggestions(final String query) { final List<NiboSearchSuggestionItem> placeSuggestionItems = new ArrayList<>(); if (mGoogleapiclient == null) { Log.d(TAG,"Google play services cannot be null"); } return new Observable<Collection<NiboSearchSuggestionItem>>() { @Override protected void subscribeActual(final Observer<? super Collection<NiboSearchSuggestionItem>> observer) { Places.GeoDataApi.getAutocompletePredictions(mGoogleapiclient,null,null) .setResultCallback( new ResultCallback<AutocompletePredictionBuffer>() { @Override public void onResult(@NonNull AutocompletePredictionBuffer buffer) { placeSuggestionItems.clear(); if (buffer.getStatus().isSuccess()) { Log.d(TAG,buffer.toString() + " " + buffer.getCount()); for (AutocompletePrediction prediction : buffer) { Log.d(TAG,prediction.getFullText(null).toString()); //Add as a new item to avoid IllegalArgumentsException when buffer is released NiboSearchSuggestionItem placeSuggestion = new NiboSearchSuggestionItem( prediction.getFullText(null).toString(),prediction.getPlaceId(),NiboSearchSuggestionItem.TYPE_SEARCH_ITEM_SUGGESTION,mContext.getResources().getDrawable(R.drawable.ic_map_marker_def) ); placeSuggestionItems.add(placeSuggestion); } observer.onNext(placeSuggestionItems); } else { Log.d(TAG,buffer.toString()); } //Prevent memory leak by releasing buffer buffer.release(); } },TimeUnit.SECONDS); } }; }
/** * Submits an autocomplete query to the Places Geo Data Autocomplete API. * objects to store the Place ID and description that the API returns. * Returns an empty list if no results were found. * Returns null if the API client is not available or the query did not complete * successfully. * This method MUST be called off the main UI thread,which may include a network request. * * @param constraint Autocomplete query string * @return Results from the autocomplete API or null if the query was not successful. * @see Places#GEO_DATA_API#getAutocomplete(CharSequence) */ private ArrayList<PlaceAutocomplete> getAutocomplete(CharSequence constraint) { if (mGoogleapiclient.isConnected()) { // Submit the query to the autocomplete API and retrieve a PendingResult that will // contain the results when the query completes. PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi .getAutocompletePredictions(mGoogleapiclient,otherwise return null final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { autocompletePredictions.release(); return null; } //Log.i(TAG,"Query completed. Received " + autocompletePredictions.getCount() // + " predictions."); // // copy the results into our own data structure,because we can't hold onto the buffer. // AutocompletePrediction objects encapsulate the API response (place ID and description). Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator(); ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount()); while (iterator.hasNext()) { AutocompletePrediction prediction = iterator.next(); // Get the details of this prediction and copy it into a new PlaceAutocomplete object. resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),prediction.getDescription())); } // Release the buffer Now that all data has been copied. autocompletePredictions.release(); return resultList; } //Log.e(TAG,"Google Api client is not connected for autocomplete query."); return null; }
/** * Submits an autocomplete query to the Places Geo Data Autocomplete API. * <p/> * objects to store the Place ID and description that the API returns. * Returns an empty list if no results were found. * Returns null if the API client is not available or the query did not complete * successfully. * This method MUST be called off the main UI thread,"Error getting autocomplete prediction API call: " + status.getStatusMessage() + status.getStatus().getStatusMessage()); autocompletePredictions.release(); return null; } Log.i(TAG,prediction.getDescription())); } // Release the buffer Now that all data has been copied. autocompletePredictions.release(); return resultList; } Log.e(TAG,"Google Api client is not connected for autocomplete query."); return null; }
/** * Submits an autocomplete query to the Places Geo Data Autocomplete API. * Results are returned as PlaceAutocomplete objects to store the Place ID and description that the API returns. * Returns an empty list if no results were found. * Returns null if the API client is not available or the query did not complete * successfully. * This method MUST be called off the main UI thread,which may include a network request. * * @param constraint Autocomplete query string * @return Results from the autocomplete API or null if the query was not successful. * @see Places#GEO_DATA_API#getAutocomplete(CharSequence) */ private ArrayList<PlaceAutocomplete> getAutocomplete(CharSequence constraint) { if (mGoogleapiclient != null) { // Submit the query to the autocomplete API and retrieve a PendingResult that will // contain the results when the query completes. PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi .getAutocompletePredictions(mGoogleapiclient,Toast.LENGTH_SHORT).show(); autocompletePredictions.release(); return null; } // copy the results into our own data structure,prediction.getDescription())); } // Release the buffer Now that all data has been copied. autocompletePredictions.release(); return resultList; } return null; }
private ArrayList<PlaceAutocomplete> getAutocomplete(CharSequence constraint) { if (mGoogleapiclient.isConnected()) { Log.i(TAG,"Starting autocomplete query for: " + constraint); // Submit the query to the autocomplete API and retrieve a PendingResult that will // contain the results when the query completes. PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi.getAutocompletePredictions(mGoogleapiclient,mPlaceFilter); // This method should have been called off the main UI thread. Block and wait for at most 60s // for a result from the API. AutocompletePredictionBuffer autocompletePredictions = results.await(60,otherwise return null final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { Log.e(TAG,"Error getting autocomplete prediction API call: " + status.toString()); autocompletePredictions.release(); return null; } // PendingResult<PlacePhotoMetadataResult> pendingMetadata = // Places.GeoDataApi.getPlacePhotos(mGoogleapiclient,placeId); // PlacePhotoMetadataResult Metadata = pendingMetadata.await(60,TimeUnit.SECONDS); // // PendingResult<PlacePhotoResult> pendingPhoto = // Metadata.getPhotoMetadata().get(0).getPhoto(mGoogleapiclient); // PlacePhotoResult p = pendingPhoto.await(60,TimeUnit.SECONDS); // Bitmap photo = p.getBitmap(); Log.i(TAG,"Query completed. Received " + autocompletePredictions.getCount() + " predictions."); // copy the results into our own data structure,because we can't hold onto the buffer. // AutocompletePrediction objects encapsulate the API response (place ID and description). Iterator<AutocompletePrediction> iterator = autocompletePredictions.iterator(); ArrayList resultList = new ArrayList<>(autocompletePredictions.getCount()); while (iterator.hasNext()) { AutocompletePrediction prediction = iterator.next(); // Only include U.S. cities // States only have 1 comma (e.g. AK,United States). Don't include states. if(prediction.getDescription().contains("United States") && prediction.getDescription().replaceAll("[^,]","").length() > 1 ) { resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),prediction.getDescription())); } } // Release the buffer Now that all data has been copied. autocompletePredictions.release(); return resultList; } Log.e(TAG,"Google Api client is not connected for autocomplete query."); return null; }
private ArrayList<PlaceAutocomplete> getAutocomplete(CharSequence constraint) { if (mGoogleapiclient.isConnected()) { Log.i("",otherwise return null final Status status = autocompletePredictions.getStatus(); if (!status.isSuccess()) { Toast.makeText(mContext,Toast.LENGTH_SHORT).show(); Log.e("","Error getting autocomplete prediction API call: " + status.toString()); autocompletePredictions.release(); return null; } Log.i("",prediction.getDescription())); } // Release the buffer Now that all data has been copied. autocompletePredictions.release(); return resultList; } Log.e("","Google Api client is not connected for autocomplete query."); return null; }
/** * Submits an autocomplete query to the Places Geo Data Autocomplete API. * <p/> * objects to store the Place ID and description that the API returns. * Returns an empty list if no results were found. * Returns null if the API client is not available or the query did not complete * successfully. * This method MUST be called off the main UI thread,"Starting autocomplete query for: " + constraint); // Submit the query to the autocomplete API and retrieve a PendingResult that will // contain the results when the query completes. PendingResult<AutocompletePredictionBuffer> results = Places.GeoDataApi.getAutocompletePredictions( mGoogleapiclient,mPlaceFilter); // This method should have been called off the main UI thread. Block and wait for at most 60s // for a result from the API. AutocompletePredictionBuffer autocompletePredictions = results.await(60,status.toString(),"Query completed. Received " + autocompletePredictions.getCount() + " predictions."); // copy the results into our own data structure,because we can't hold onto the buffer. // AutocompletePrediction objects encapsulate the API response (place ID and description). ArrayList<PlaceAutocomplete> resultList = new ArrayList<>(autocompletePredictions.getCount()); for (AutocompletePrediction prediction : autocompletePredictions) { // Get the details of this prediction and copy it into a new PlaceAutocomplete object. resultList.add(new PlaceAutocomplete(prediction.getPlaceId(),"Google Api client is not connected for autocomplete query."); return null; }
/** * Submits an autocomplete query to the Places Geo Data Autocomplete API. * <p/> * objects to store the Place ID and description that the API returns. * Returns an empty list if no results were found. * Returns null if the API client is not available or the query did not complete * successfully. * This method MUST be called off the main UI thread,"Google Api client is not connected for autocomplete query."); return null; }
/** * Returns observable that fetches autocomplete predictions from Places API. To flatmap and autorelease * {@link com.google.android.gms.location.places.AutocompletePredictionBuffer} you can use * {@link DataBufferObservable}. * * @param query search query * @param bounds bounds where to fetch suggestions from * @param filter filter * @return observable with suggestions buffer and completes */ public Observable<AutocompletePredictionBuffer> getPlaceAutocompletePredictions(final String query,final LatLngBounds bounds,final AutocompleteFilter filter) { return getGoogleapiclientObservable(Places.PLACE_DETECTION_API,Places.GEO_DATA_API) .flatMap(new Func1<Googleapiclient,Observable<AutocompletePredictionBuffer>>() { @Override public Observable<AutocompletePredictionBuffer> call(Googleapiclient api) { return fromPendingResult(Places.GeoDataApi.getAutocompletePredictions(api,filter)); } }); }
didReceiveRemoteNotification: fetchCompletionHandler 当应用程序处于后台和非活动状态时不被调用
如何解决didReceiveRemoteNotification: fetchCompletionHandler 当应用程序处于后台和非活动状态时不被调用?
在应用程序激活状态下,didReceiveRemoteNotification 方法被调用,当应用程序处于后台和非活动状态时,didReceiveRemoteNotification 方法不被调用。
代码:-
func application(_ application: UIApplication,didReceiveRemoteNotification userInfo: [AnyHashable: Any],fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void){
NSLog("Push Received: \(userInfo)")
completionHandler(UIBackgroundFetchResult.newData)
}
解决方法
如果它能让你冷静下来,我也遇到了同样的问题,我没有采取任何措施来解决这个问题,因为几个小时后,我的应用程序开始在后台收到通知。但如果没有帮助,您应该尝试使用 ARC 手动发送通知,并检查通知状态。
FileChannel 使用ByteBuffer 和 Protostuff 从文件中读写 对象信息
protostuff
protostuff 包引入
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.6.0</version>
</dependency>
<dependency>
<groupId>io.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.6.0</version>
</dependency>
protostuff 简单实用 序列化和反序列化对象信息
private LinkedBuffer linkedBuffer = LinkedBuffer.allocate(4 * 1024);
private Schema<ShowModel> schema = RuntimeSchema.getSchema(ShowModel.class);
//对象转换成 byte
private byte[] seriBean(){
linkedBuffer.clear();
ShowModel showModel = new ShowModel();
showModel.setId(1);
showModel.setName("demo");
return ProtostuffIOUtil.toByteArray(showModel, schema, linkedBuffer);
}
//byte 转换成 对象
private ShowModel deSeriBean(byte[] data){
ShowModel showModel = schema.newMessage();
ProtostuffIOUtil.mergeFrom(data, showModel, schema);
return showModel;
}
ByteBuffer
写入对象到文件中
String fileName = "e:\\aa.db";
//定义读写文件
FileChannel fileChannel = new RandomAccessFile(new File(fileName), "rw").getChannel();
//定义4个字节的空间
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
//定义一个大点的字节空间,重复利用
ByteBuffer byteBufferContent = ByteBuffer.allocate(4 * 1024);
for (int i = 0; i<12; i++){
byte[] byteWrite = seriBean();
int length = byteWrite.length;
System.out.println("写入的长度为:" + length);
byteBuffer.putInt(length);
byteBuffer.flip();
fileChannel.write(byteBuffer);
byteBufferContent.put(byteWrite);
//从0开始读取,读取到写入的长度
byteBufferContent.flip();
fileChannel.write(byteBufferContent);
byteBuffer.clear();
byteBufferContent.clear();
}
从文件中读取字节成对象信息
ByteBuffer byteBuffer = ByteBuffer.allocate(4);
fileChannel = new RandomAccessFile(new File(fileName), "rw").getChannel();
while (fileChannel.read(byteBuffer) == 4){
//把byteBuffer中的limit变成position(即4个字节),同时吧position定位成0 表示从0开始读取4个字节的数据,就是它的长度
byteBuffer.flip();
int length = byteBuffer.getInt();
System.out.println("read ==>> " + length);
byte[] b = new byte[length];
fileChannel.read(ByteBuffer.wrap(b));
System.out.println(deSeriBean(b).getName());
byteBuffer.clear();
}
fileChannel.force(true);
fileChannel.close();
注:
- 写入的时候使用的 纯ByteBuffer,采用 position 和 limit的移动方式来确定读取和写入;此种方式内存可以重复利用
- 读取的时候使用的是字节方式,此种方式简单,但是每次都需要创建一个对象;对于数据量比较大的时候不建议使用
今天关于如何使用CompletionHandlers和小于请求的ByteBuffer读取请求?和querywrapper小于的介绍到此结束,谢谢您的阅读,有关ByteBuffer / IntBuffer / ShortBuffer Java类是否快速?、com.google.android.gms.location.places.AutocompletePredictionBuffer的实例源码、didReceiveRemoteNotification: fetchCompletionHandler 当应用程序处于后台和非活动状态时不被调用、FileChannel 使用ByteBuffer 和 Protostuff 从文件中读写 对象信息等更多相关知识的信息可以在本站进行查询。
本文标签: