在本文中,我们将带你了解GoogleGuava与ApacheCommons在这篇文章中,同时我们还将给您一些技巧,以帮助您实现更有效的android–错误“java.lang.NoClassDefFo
在本文中,我们将带你了解Google Guava与Apache Commons在这篇文章中,同时我们还将给您一些技巧,以帮助您实现更有效的android – 错误“java.lang.NoClassDefFoundError:com.google.repacked.apache.commons.io.FileUtils”、apache-commons commons-pool2整合 commons-net 自定 FTPClient对象池、apache.commons.vfs2与apache.commons.io监听文件的有什么区别、com.google.android.gms.common.api.CommonStatusCodes的实例源码。
本文目录一览:- Google Guava与Apache Commons
- android – 错误“java.lang.NoClassDefFoundError:com.google.repacked.apache.commons.io.FileUtils”
- apache-commons commons-pool2整合 commons-net 自定 FTPClient对象池
- apache.commons.vfs2与apache.commons.io监听文件的有什么区别
- com.google.android.gms.common.api.CommonStatusCodes的实例源码
Google Guava与Apache Commons
我一直在寻找Java中的双向地图实现,偶然发现了这两个库:
- Google Guava(以前称为“ Google Collections”)
- Apache Commons集合
两者都是免费的,具有我一直在寻找的双向地图实现(Apache中的BidiMap,谷歌中的BiMap),尺寸几乎惊人地相同(Apache 493
kB,Google 499 kB)[ed .:不再是真的!在所有方面都和我很相似。
我应该选择哪一个,为什么?还有其他等效的替代方法(必须免费并且至少具有双向地图)吗?我正在使用最新的Java SE,因此无需人为地限制为Java5或类似的东西。
答案1
小编典典我认为更好的选择是 Guava (以前称为Google收藏):
- 它更现代(具有泛型)
- 它绝对遵循Collections API要求
- 积极维护
CacheBuilder
它的前身MapMaker
简直很棒
Apache Commons Collections也是一个很好的库,但是长期以来它一直未能提供启用了泛型的版本(我认为这是Collections API的 主要 缺点),并且通常看起来是在维护中/不做太多的工作模式最近,Commons CommonsCollections又重新吸收了一些精力,但还有一些工作要做。。
如果下载大小/内存占用空间/代码大小是一个问题,那么Apache Commons
Collections可能是一个更好的选择,因为它是其他库的常见依赖项。因此,也有可能在不添加任何其他依赖项的情况下在自己的代码中使用它。编辑:这个特殊的“优势”现在已经被部分颠覆了,因为许多新库实际上依赖于Guava而
不是 Apache Commons Collections。
android – 错误“java.lang.NoClassDefFoundError:com.google.repacked.apache.commons.io.FileUtils”
Android应用在build.gradle中包含以下内容:
dependencies {
...
compile 'commons-io:commons-io:2.4'
}
构建和安装应用程序没有问题.但是以下代码:
FileUtils.writeStringToFile(fText, "Test");
导致以下异常:
java.lang.NoClassDefFoundError: com.google.repacked.apache.commons.io.FileUtils
任何人都可以提供一个如何解决这个问题的提示吗?
[编辑:]
我刚刚意识到应用程序仍然可以在build.gradle中没有以下内容的情况下构建:
dependencies {
...
compile 'commons-io:commons-io:2.4'
}
FileUtils如下:
任何人都可以告诉com.google.repacked是什么以及如何摆脱它?
解决方法:
快速猜测,但似乎你没有使用公共库中的FileUtils.仔细检查import语句以查看从哪里导入FileUtils.
确保您要导入org.apache … FileUtils类,而不是com.google …包中的内容.
apache-commons commons-pool2整合 commons-net 自定 FTPClient对象池
commons-net 包介绍
commons-net 是 apachecommons 用于网络的工具包,它实现了一些常见的网络工具,如 smtp
,pop3
,telnet
,ftp
,udp
等,本文主要使用它的 ftp 工具。
使用 FTP 工具时的问题
在使用 commons-net 提供的 ftp 工具的时候 ,发现每次都要走一遍完整的连接,登录流程。每次都创建连接的话,很快就会把连接耗光,如果使用单例,则效率过低,因为只有一个连接,所以考虑用对象池的方式。
自已定义对象池的话,我之前有弄过,但要考虑好多的问题。像线程池一样,需要考虑核心对象数、最大对象数、何时创建对象 、及队列等,这时可以使用 apache 的 commons-pool2 来做一个对象池。
重要说明 : FTPClient 每次使用都需要重新连接,不然它会自动断开连接,使用会直接返回 421 ,本文章只是给个使用 commons-pool2 对象池的示例。
如何使用 commons-pool2
可以这么想,如果我要做个对象池的工具给别人用,首先要考虑的是池子里装的什么,用户要如何创建池子里的对象,然后提供方法借对象和回收对象,我可以把池子中的对象抽象出来,由一个工厂统一管理,用户的对象从我的通用对象继承或实现,或使用聚合方式 。
其实 spring-data-redis 已经给我们一个完整的使用 commons-pool2 的例子,它就是用的 commons-pool2 ,它的池中对象是 redis 连接,有兴趣可以去瞧瞧。
定义池中对象 FTPClient 的扩展对象
因为 FTPClient 的功能太过简单,连多层目录时自己创建目录都不会,所以有必要给它包装一下,这里你可以扩展常用到的方法。
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
@Slf4j
public class FtpClientExtend {
private FTPClient ftpClient ;
public FtpClientExtend(FTPClient ftpClient) {
this.ftpClient = ftpClient;
}
/**
* 列出文件列表
* @param filePath
* @return
* @throws IOException
*/
public FTPFile[] listFiles(String filePath) throws IOException {
return ftpClient.listFiles(filePath);
}
/**
* 下载文件
* @param filePath
* @return
*/
public InputStream downloadFile(String filePath) throws IOException {
return ftpClient.retrieveFileStream(filePath);
}
/**
* 存储文件
* @param s
* @param inputStream
*/
public void uploadFile(String filePath, InputStream inputStream) throws IOException {
File targetFilePath = new File(filePath);
Path path = targetFilePath.getParentFile().toPath();
Iterator<Path> iterator = path.iterator();
StringBuffer root = new StringBuffer("");
while (iterator.hasNext()){
Path next = iterator.next();
root.append("/").append(next);
//尝试切入目录
boolean success = ftpClient.changeWorkingDirectory(root.toString());
if(!success){
int mkd = ftpClient.mkd(next.toString());
ftpClient.changeWorkingDirectory(root.toString());
}
}
ftpClient.enterLocalPassiveMode();
ftpClient.setControlEncoding("UTF-8");
ftpClient.setFileType(FTP.BINARY_FILE_TYPE);
boolean storeFileResult = ftpClient.storeFile(targetFilePath.getName(), inputStream);
if (storeFileResult) {
log.debug("上传文件:" + filePath + ",到目录:" + ftpClient.printWorkingDirectory() + " 成功");
}else{
log.debug("上传文件:" + filePath + ",到目录:" + ftpClient.printWorkingDirectory() + " 失败");
}
}
}
使用聚合包裹池中对象
这个包裹对象的类才是工厂真正产生在池中的类,文末给出图示
import org.apache.commons.pool2.PooledObjectFactory;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
public class FtpClientPool extends GenericObjectPool<FtpClientExtend> {
public FtpClientPool(PooledObjectFactory<FtpClientExtend> factory) {
super(factory);
}
public FtpClientPool(PooledObjectFactory<FtpClientExtend> factory, GenericObjectPoolConfig config) {
super(factory, config);
}
}
建立创建对象的工厂
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.pool2.BasePooledObjectFactory;
import org.apache.commons.pool2.PooledObject;
import org.apache.commons.pool2.impl.DefaultPooledObject;
public class FtpClientFactory extends BasePooledObjectFactory<FtpClientExtend> {
@Value("${ftp.host:localhost}")
private String host;
@Value("${ftp.port:21}")
private int port;
@Value("${ftp.username:ftpadmin}")
private String username;
@Value("${ftp.password:salt202}")
private String password;
@Override
public FtpClientExtend create() throws Exception {
FTPClient ftpClient = new FTPClient();
ftpClient.connect(host,port);
boolean login = ftpClient.login(username, password);
if(!login){
throw new RuntimeException("ftp 登录失败,检查用户名密码是否正确["+host+":"+port+"]["+username+"]["+password+"]");
}
return new FtpClientExtend(ftpClient);
}
@Override
public PooledObject<FtpClientExtend> wrap(FtpClientExtend ftpClientExtend) {
return new DefaultPooledObject(ftpClientExtend);
}
}
使用方法
@Autowired
private FtpClientPool ftpClientPool;
public void method(){
FtpClientExtend ftpClientExtend = null;
try{
ftpClientExtend = ftpClientPool.borrowObject();
}finally{
if(ftpClientExtend != null) {
ftpClientPool.returnObject(ftpClientExtend);
}
}
}
原理图示
apache.commons.vfs2与apache.commons.io监听文件的有什么区别
请问各位大佬,用apache.commons.vfs2与apache.commons.io监听文件的有什么区别?
com.google.android.gms.common.api.CommonStatusCodes的实例源码
@Override protected void onActivityResult(int requestCode,int resultCode,Intent data) { super.onActivityResult(requestCode,resultCode,data); if (requestCode == PROFILE_REQUEST && resultCode == CommonStatusCodes.SUCCESS) { preferences.setIdAuth(""); preferences.setUserData(""); preferences.setUserDni(""); preferences.setEmail(""); preferences.setIsLogged(false); setDataToHeader(preferences); if (!(getSupportFragmentManager().findFragmentById(R.id.containerHome) instanceof MapFragment)) { navigationView.getMenu().getItem(0).setChecked(true); setTitletoolbar(getString(R.string.map_stations)); getSupportFragmentManager().popBackStack("",FragmentManager.POP_BACK_STACK_INCLUSIVE); } } else if (requestCode == 140) { Fragment fragment = getSupportFragmentManager().findFragmentById(R.id.containerHome); if (fragment != null && fragment instanceof MapFragment) { fragment.onActivityResult(requestCode,data); } } else if (resultCode == Activity.RESULT_OK && requestCode == LoginActivity.LOGIN_RESULT) { navigationView.getMenu().getItem(itemSelected).setChecked(true); preferences.setIsLogged(true); setDataToHeader(preferences); } }
protected void handleSignInResult(GoogleSignInResult result) { Schedulers.newThread() .scheduleDirect(() -> { if (result.isSuccess()) { if (result.getSignInAccount() != null && result.getSignInAccount().getAccount() != null) { Account account = result.getSignInAccount().getAccount(); try { String token = GoogleAuthUtil.getToken(activity,account,"oauth2:" + ScopE_PICASA); emitter.onSuccess(new GoogleSignIn.SignInAccount(token,result.getSignInAccount())); } catch (IOException | GoogleAuthException e) { emitter.onError(new SignInException("SignIn",e)); } } else { emitter.onError(new SignInException("SignIn","getSignInAccount is null!",0)); } } else { if (result.getStatus().getStatusCode() == CommonStatusCodes.SIGN_IN_required) { emitter.onError(new SignInrequiredException()); } else { emitter.onError(new SignInException("SignIn",result.getStatus().getStatusMessage(),result.getStatus().getStatusCode())); } } }); }
/** * onTap is called to capture the first TextBlock under the tap location and return it to * the Initializing Activity. * * @param rawX - the raw position of the tap * @param rawY - the raw position of the tap. * @return true if the activity is ending. */ private boolean onTap(float rawX,float rawY) { Ocrgraphic graphic = mGraphicOverlay.getGraphicAtLocation(rawX,rawY); TextBlock text = null; if (graphic != null) { text = graphic.getTextBlock(); if (text != null && text.getValue() != null) { Intent data = new Intent(); data.putExtra(TextBlockObject,text.getValue()); setResult(CommonStatusCodes.SUCCESS,data); finish(); } else { Log.d(TAG,"text data is null"); } } else { Log.d(TAG,"no text detected"); } return text != null; }
/** * Called when an activity you launched exits,giving you the requestCode * you started it with,the resultCode it returned,and any additional * data from it. The <var>resultCode</var> will be * {@link #RESULT_CANCELED} if the activity explicitly returned that,* didn't return any result,or crashed during its operation. * <p/> * <p>You will receive this call immediately before onResume() when your * activity is re-starting. * <p/> * * @param requestCode The integer request code originally supplied to * startActivityForResult(),allowing you to identify who this * result came from. * @param resultCode The integer result code returned by the child activity * through its setResult(). * @param data An Intent,which can return result data to the caller * (varIoUs data can be attached to Intent "extras"). * @see #startActivityForResult * @see #createPendingResult * @see #setResult(int) */ @Override protected void onActivityResult(int requestCode,Intent data) { if(requestCode == RC_OCR_CAPTURE) { if (resultCode == CommonStatusCodes.SUCCESS) { if (data != null) { String text = data.getStringExtra(OcrCaptureActivity.TextBlockObject); statusMessage.setText(R.string.ocr_success); textValue.setText(text); Log.d(TAG,"Text read: " + text); } else { statusMessage.setText(R.string.ocr_failure); Log.d(TAG,"No Text captured,intent data is null"); } } else { statusMessage.setText(String.format(getString(R.string.ocr_error),CommonStatusCodes.getStatusCodeString(resultCode))); } } else { super.onActivityResult(requestCode,data); } }
/** * onTap is called to capture the first TextBlock under the tap location and return it to * the Initializing Activity. * * @param rawX - the raw position of the tap * @param rawY - the raw position of the tap. * @return true if the activity is ending. */ private boolean onTap(float rawX,"no text detected"); } return text != null; }
@Override protected void onActivityResult(int requestCode,Intent data) { if (requestCode == BARCODE_READER_REQUEST_CODE) { if (resultCode == CommonStatusCodes.SUCCESS) { if (data != null) { Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject); QRURLParser parser = QRURLParser.getInstance(); String extracted_address = parser.extractAddressFromQrString(barcode.displayValue); if (extracted_address == null) { Toast.makeText(this,R.string.toast_qr_code_no_address,Toast.LENGTH_SHORT).show(); return; } Point[] p = barcode.cornerPoints; toAddresstext.setText(extracted_address); } } else { Log.e("SEND",String.format(getString(R.string.barcode_error_format),CommonStatusCodes.getStatusCodeString(resultCode))); } } else { super.onActivityResult(requestCode,data); } }
private void resolveResult(Status status) { if (status.getStatusCode() == CommonStatusCodes.RESOLUTION_required) { try { //status.startResolutionForResult(mActivity,RC_READ); startIntentSenderForResult(status.getResolution().getIntentSender(),RC_READ,null,null); } catch (IntentSender.SendIntentException e) { e.printstacktrace(); mCredentialsapiclient.disconnect(); mAccountSubject.onError(new Throwable(e.toString())); } } else { // The user must create an account or sign in manually. mCredentialsapiclient.disconnect(); mAccountSubject.onError(new Throwable(getString(R.string.status_canceled_request_credential))); } }
/** * Facebook sign out */ public void signOut(PublishSubject<RxStatus> statusSubject) { LoginManager.getInstance().logout(); // delete current user deleteCurrentUser(); statusSubject.onNext(new RxStatus( CommonStatusCodes.SUCCESS,getString(R.string.status_success_log_out_message) )); statusSubject.onCompleted(); }
private void handleUnsuccessfulNearbyResult(Status status) { Log.v(TAG,"Processing error,status = " + status); if (mResolvingError) { // Already attempting to resolve an error. return; } else if (status.hasResolution()) { try { mResolvingError = true; status.startResolutionForResult(getActivity(),REQUEST_RESOLVE_ERROR); } catch (IntentSender.SendIntentException e) { mResolvingError = false; Log.v(TAG,"Failed to resolve error status.",e); } } else { if (status.getStatusCode() == CommonStatusCodes.NETWORK_ERROR) { Toast.makeText(getActivity(),"No connectivity,cannot proceed. Fix in 'Settings' and try again.",Toast.LENGTH_LONG).show(); } else { // To keep things simple,pop a toast for all other error messages. Toast.makeText(getActivity(),"Unsuccessful: " + status.getStatusMessage(),Toast.LENGTH_LONG).show(); } } }
/** * onTap is called to capture the first TextBlock under the tap location and return it to * the Initializing Activity. * * @param rawX - the raw position of the tap * @param rawY - the raw position of the tap. * @return true if the activity is ending. */ private boolean onTap(float rawX,"no text detected"); } return text != null; }
/** * Called when an activity you launched exits,CommonStatusCodes.getStatusCodeString(resultCode))); } displayStatus(); } else { super.onActivityResult(requestCode,data); } }
@Override public void onFailure(@NonNull Exception e) { // An error occurred while communicating with the service. mResult = null; if (e instanceof ApiException) { // An error with the Google Play Services API contains some additional details. ApiException apiException = (ApiException) e; Log.d(TAG,"Error: " + CommonStatusCodes.getStatusCodeString(apiException.getStatusCode()) + ": " + apiException.getStatusMessage()); } else { // A different,unkNown type of error occurred. Log.d(TAG,"ERROR! " + e.getMessage()); } }
@VisibleForTesting protected void handleUnsuccessfulNearbyResult(Status status) { Log.v(TAG,status = " + status); if (resolvingError) { // Already attempting to resolve an error. return; } else if (status.hasResolution()) { try { resolvingError = true; status.startResolutionForResult(this,REQUEST_RESOLVE_ERROR); } catch (Exception e) { resolvingError = false; Log.v(TAG,e); } } else { if (status.getStatusCode() == CommonStatusCodes.NETWORK_ERROR) { Toast.makeText(this,Toast.LENGTH_LONG).show(); } else { Toast.makeText(this,"Unsuccessful: " + status.getStatusMessage(),Toast.LENGTH_LONG).show(); } } }
/** * onTap is called to capture the oldest barcode currently detected and * return it to the caller. * * @param rawX - the raw position of the tap * @param rawY - the raw position of the tap. * @return true if the activity is ending. */ private boolean onTap(float rawX,float rawY) { //Todo: use the tap position to select the barcode. BarcodeGraphic graphic = mGraphicOverlay.getFirstGraphic(); Barcode barcode = null; if (graphic != null) { barcode = graphic.getBarcode(); if (barcode != null) { Intent data = new Intent(); data.putExtra(BarcodeObject,barcode); setResult(CommonStatusCodes.SUCCESS,"barcode data is null"); } } else { Log.d(TAG,"no barcode detected"); } return barcode != null; }
/** * Called when an activity you launched exits,Intent data) { if (requestCode == RC_BARCODE_CAPTURE) { if (resultCode == CommonStatusCodes.SUCCESS) { if (data != null) { Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject); statusMessage.setText(R.string.barcode_success); barcodeValue.setText(barcode.displayValue); Log.d(TAG,"Barcode read: " + barcode.displayValue); } else { statusMessage.setText(R.string.barcode_failure); Log.d(TAG,"No barcode captured,intent data is null"); } } else { statusMessage.setText(String.format(getString(R.string.barcode_error),data); } }
@Override public void onActivityResult(int requestCode,Intent data) { Log.d(TAG,"onActivityResult"); if (requestCode == RC_BARCODE_CAPTURE) { if (resultCode == CommonStatusCodes.SUCCESS) { if (data != null) { Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject); Log.d(TAG,"Barcode read: " + barcode.displayValue); mPresenter.newEvent(barcode); } else { Log.d(TAG,intent data is null"); } } else { Log.d(TAG,"onActivityResult is not a success"); } } else { super.onActivityResult(requestCode,data); } }
/** * Called when an activity you launched exits,data); } }
@Override public void onConnected(@Nullable Bundle bundle) { googleApi.requestCredentials(new ResultCallback<CredentialRequestResult>() { @Override public void onResult(@NonNull CredentialRequestResult result) { if (result.getStatus().isSuccess()) { onCredentialRetrieved(result.getCredential()); } else if (result.getStatus().getStatusCode() != CommonStatusCodes.SIGN_IN_required && result.getStatus().hasResolution()) { try { result.getStatus().startResolutionForResult(LoginActivity.this,GoogleApiAdapter.RETRIEVE_CREDENTIALS); } catch (IntentSender.SendIntentException e) { Snackbar.make(vLoginForm,R.string.error_smartlock_Failed,Snackbar.LENGTH_LONG); } } } }); }
public static Status zzhO(int paramInt) { String str; switch (paramInt) { default: str = CommonStatusCodes.getStatusCodeString(paramInt); } for (;;) { return new Status(paramInt,str); str = "TARGET_NODE_NOT_CONNECTED"; continue; str = "DUPLICATE_LISTENER"; continue; str = "UNKNowN_LISTENER"; continue; str = "DATA_ITEM_TOO_LARGE"; continue; str = "INVALID_TARGET_NODE"; continue; str = "ASSET_UNAVAILABLE"; } }
/** * onTap is called to capture the first TextBlock under the tap location and return it to * the Initializing Activity. * * @param rawX - the raw position of the tap * @param rawY - the raw position of the tap. * @return true if the activity is ending. */ private boolean onTap(float rawX,"no text detected"); } return text != null; }
/** * Called when an activity you launched exits,data); } }
/** * Called when an activity you launched exits,data); } }
/** * onTap is called to capture the first TextBlock under the tap location and return it to * the Initializing Activity. * * @param rawX - the raw position of the tap * @param rawY - the raw position of the tap. * @return true if the activity is ending. */ private boolean onTap(float rawX,"no text detected"); } return text != null; }
/** * Called when an activity you launched exits,data); } }
private List<String> getCurrentUsersGooglePlusIds() { ArrayList<String> friendGooglePlusIds = new ArrayList<>(); ConnectionResult connectionResult = googleapiclient .blockingConnect(Constants.CONNECTION_TIME_OUT_MS,TimeUnit.MILLISECONDS); if (connectionResult.isSuccess()) { People.LoadPeopleResult peopleData = Plus.PeopleApi.loadVisible(googleapiclient,null).await(); if (peopleData.getStatus().getStatusCode() == CommonStatusCodes.SUCCESS) { PersonBuffer personBuffer = peopleData.getPersonBuffer(); try { int count = personBuffer.getCount(); for (int i = 0; i < count; i++) { friendGooglePlusIds.add(personBuffer.get(i).getId()); } } finally { personBuffer.close(); } } else { Timber.w("Error requesting visible circles: %s",peopleData.getStatus()); } } if (googleapiclient.isConnected()) { googleapiclient.disconnect(); } return friendGooglePlusIds; }
private void addGeofence(GeofencingRequest geofencingRequest,PendingIntent geofencePendingIntent) { if (ActivityCompat.checkSelfPermission(context,Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager .PERMISSION_GRANTED) { return; } LocationServices.GeofencingApi.addGeofences( googleapiclient,geofencingRequest,geofencePendingIntent ).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { switch (status.getStatusCode()) { case CommonStatusCodes.SUCCESS: StatusMessageHandler.showInfoMessage(context,R.string.geofence_enabled,Snackbar.LENGTH_SHORT); } Log.d(GeofenceApiHandler.class,status.toString()); } }); }
private void removeGeofence(Googleapiclient googleapiclient,final String geofenceId) { ArrayList<String> geofenceIds = new ArrayList<>(); geofenceIds.add(geofenceId); LocationServices.GeofencingApi.removeGeofences( googleapiclient,geofenceIds ).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { switch (status.getStatusCode()) { case CommonStatusCodes.SUCCESS: StatusMessageHandler.showInfoMessage(context,R.string.geofence_disabled,status.toString()); } }); // Result processed in onResult(). }
/** * Remove all Geofences from Google Location Api */ public void removeAllGeofences() { LocationServices.GeofencingApi.removeGeofences( googleapiclient,// This is the same pending intent that was used in addGeofence(). getGeofencePendingIntent() ).setResultCallback(new ResultCallback<Status>() { @Override public void onResult(@NonNull Status status) { switch (status.getStatusCode()) { case CommonStatusCodes.SUCCESS: StatusMessageHandler.showInfoMessage(context,R.string.geofences_disabled,Snackbar .LENGTH_LONG); } Log.d(GeofenceApiHandler.class,status.toString()); } }); // Result processed in onResult(). }
@Override protected void onActivityResult(int requestCode,Intent data) { if (requestCode == BARCODE_CAPTURE) { if (resultCode == CommonStatusCodes.SUCCESS) { if (data != null) { Barcode barcode = data.getParcelableExtra(BarcodeCaptureActivity.BarcodeObject); statusMessage.setText("Success!"); barcodeValue.setText(barcode.displayValue); Log.d("BARCODER","Barcode read: " + barcode.displayValue); } else { statusMessage.setText("Fail"); Log.d("BARCODER","No barcode has been captured"); } } else { statusMessage.setText("Error"); } } else { super.onActivityResult(requestCode,data); } }
/** * Begin the process of retrieving a {@link Credential} for the device user. This can have * a few different results: * 1) If the user has auto sign-in enabled and exactly one prevIoUsly saved credential,* {@link SmartLockListener#onCredentialRetrieved(Credential)} will be called and * you can sign the user in immediately. * 2) If the user has multiple saved credentials or one saved credential and has disabled * auto sign-in,you will get the callback {@link SmartLockListener#onShouldShowCredentialPicker()} * at which point you can choose to show the picker dialog to continue. * 3) If the user has no saved credentials or cancels the operation,you will receive the * {@link SmartLockListener#onCredentialRetrievalFailed()} callback. */ public void getCredentials() { CredentialRequest request = buildCredentialRequest(); Auth.CredentialsApi.request(getFragment().getGoogleapiclient(),request) .setResultCallback(new ResultCallback<CredentialRequestResult>() { @Override public void onResult(CredentialRequestResult result) { if (result.getStatus().isSuccess()) { // Single credential,auto sign-in Credential credential = result.getCredential(); getListener().onCredentialRetrieved(credential); } else if (result.getStatus().hasResolution() && result.getStatus().getStatusCode() != CommonStatusCodes.SIGN_IN_required) { // Multiple credentials or auto-sign in disabled. If the status // code is SIGN_IN_required then it is a hint credential,which we // do not want at this point. getListener().onShouldShowCredentialPicker(); } else { // Could not retrieve credentials getListener().onCredentialRetrievalFailed(); } } }); }
private void onError(GoogleSignInResult result) { Status status = result.getStatus(); if (status.getStatusCode() == CommonStatusCodes.INVALID_ACCOUNT) { mGoogleapiclient.stopAutoManage(mActivity); mGoogleapiclient.disconnect(); mGoogleapiclient = new Googleapiclient.Builder(mActivity) .enableAutoManage(mActivity,GoogleApiHelper.getSafeAutoManageId(),this) .addApi(Auth.GOOGLE_SIGN_IN_API,getSignInoptions(null)) .build(); startLogin(mActivity); } else { if (status.getStatusCode() == CommonStatusCodes.DEVELOPER_ERROR) { Log.w(TAG,"Developer error: this application is misconfigured. Check your SHA1 " + " and package name in the Firebase console."); Toast.makeText(mActivity,"Developer error.",Toast.LENGTH_SHORT).show(); } onError(status.getStatusCode() + " " + status.getStatusMessage()); } }
@Override public void onResult(@NonNull CredentialRequestResult result) { Status status = result.getStatus(); if (status.isSuccess()) { // Auto sign-in success handleCredential(result.getCredential()); return; } else { if (status.hasResolution()) { try { if (status.getStatusCode() == CommonStatusCodes.RESOLUTION_required) { startIntentSenderForResult( status.getResolution().getIntentSender(),RC_CREDENTIALS_READ); return; } } catch (IntentSender.SendIntentException e) { Log.e(TAG,"Failed to send Credentials intent.",e); } } else { Log.e(TAG,"Status message:\n" + status.getStatusMessage()); } } startAuthMethodChoice(); }
@Override public void onActivityResult(int requestCode,Intent data) { if (requestCode == REQUEST_CODE_SCAN_iccid) { if (resultCode == CommonStatusCodes.SUCCESS && data != null) { Barcode barcode = data.getParcelableExtra(BarcodeScannerActivity.EXTRA_BARCODE); log.d("Barcode read: " + barcode.displayValue); this.onBarcodeScanningFinished(barcode.displayValue); } else { Toaster.s(this,"No barcode scanned."); } } else { super.onActivityResult(requestCode,data); } }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.person_list_activity); PlusOptions options = PlusOptions.builder().addActivityTypes(MomentUtil.ACTIONS).build(); mGoogleapiclient = new Googleapiclient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API,options) .addScope(Plus.ScopE_PLUS_LOGIN) .build(); mListItems = new ArrayList<String>(); mlistadapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1,mListItems); mPersonListView = (ListView) findViewById(R.id.person_list); mResolvingError = savedInstanceState != null && savedInstanceState.getBoolean(STATE_RESOLVING_ERROR,false); int available = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (available != CommonStatusCodes.SUCCESS) { showDialog(DIALOG_GET_GOOGLE_PLAY_SERVICES); } }
@Override protected Dialog onCreateDialog(int id) { if (id != DIALOG_GET_GOOGLE_PLAY_SERVICES) { return super.onCreateDialog(id); } int available = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (available == CommonStatusCodes.SUCCESS) { return null; } if (GooglePlayServicesUtil.isUserRecoverableError(available)) { return GooglePlayServicesUtil.getErrorDialog( available,this,REQUEST_CODE_GET_GOOGLE_PLAY_SERVICES,this); } return new AlertDialog.Builder(this) .setMessage(R.string.plus_generic_error) .setCancelable(true) .setonCancelListener(this) .create(); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.list_moments_activity); PlusOptions options = PlusOptions.builder().addActivityTypes(MomentUtil.ACTIONS).build(); mGoogleapiclient = new Googleapiclient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API,options) .addScope(Plus.ScopE_PLUS_LOGIN) .build(); mListItems = new ArrayList<Moment>(); mMomentlistadapter = new Momentlistadapter(this,mListItems); mMomentListView = (ListView) findViewById(R.id.moment_list); mMomentListView.setonItemClickListener(this); mResolvingError = savedInstanceState != null && savedInstanceState.getBoolean(STATE_RESOLVING_ERROR,false); int available = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (available != CommonStatusCodes.SUCCESS) { showDialog(DIALOG_GET_GOOGLE_PLAY_SERVICES); } }
@Override protected Dialog onCreateDialog(int id) { if (id != DIALOG_GET_GOOGLE_PLAY_SERVICES) { return super.onCreateDialog(id); } int available = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (available == CommonStatusCodes.SUCCESS) { return null; } if (GooglePlayServicesUtil.isUserRecoverableError(available)) { return GooglePlayServicesUtil.getErrorDialog( available,this); } return new AlertDialog.Builder(this) .setMessage(R.string.plus_generic_error) .setCancelable(true) .setonCancelListener(this) .create(); }
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.multi_moment_activity); PlusOptions options = PlusOptions.builder().addActivityTypes(MomentUtil.ACTIONS).build(); mGoogleapiclient = new Googleapiclient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API,options) .addScope(Plus.ScopE_PLUS_LOGIN) .build(); mlistadapter = new ArrayAdapter<String>( this,MomentUtil.MOMENT_LIST); mMomentListView = (ListView) findViewById(R.id.moment_list); mMomentListView.setonItemClickListener(this); mResolvingError = savedInstanceState != null && savedInstanceState.getBoolean(STATE_RESOLVING_ERROR,false); int available = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (available != CommonStatusCodes.SUCCESS) { showDialog(DIALOG_GET_GOOGLE_PLAY_SERVICES); } }
@Override protected Dialog onCreateDialog(int id) { if (id != DIALOG_GET_GOOGLE_PLAY_SERVICES) { return super.onCreateDialog(id); } int available = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (available == CommonStatusCodes.SUCCESS) { return null; } if (GooglePlayServicesUtil.isUserRecoverableError(available)) { return GooglePlayServicesUtil.getErrorDialog( available,this); } return new AlertDialog.Builder(this) .setMessage(R.string.plus_generic_error) .setCancelable(true) .setonCancelListener(this) .create(); }
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.person_list_activity); PlusOptions options = PlusOptions.builder().addActivityTypes(MomentUtil.ACTIONS).build(); mGoogleapiclient = new Googleapiclient.Builder(this) .addConnectionCallbacks(this) .addOnConnectionFailedListener(this) .addApi(Plus.API,false); int available = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); if (available != CommonStatusCodes.SUCCESS) { showDialog(DIALOG_GET_GOOGLE_PLAY_SERVICES); } }
今天关于Google Guava与Apache Commons的分享就到这里,希望大家有所收获,若想了解更多关于android – 错误“java.lang.NoClassDefFoundError:com.google.repacked.apache.commons.io.FileUtils”、apache-commons commons-pool2整合 commons-net 自定 FTPClient对象池、apache.commons.vfs2与apache.commons.io监听文件的有什么区别、com.google.android.gms.common.api.CommonStatusCodes的实例源码等相关知识,可以在本站进行查询。
本文标签: