从片段中调用非父 activity 的方法
Call non parent activity's method from fragment
我有一个登录 activity,我使用 google 登录。成功登录后,我将转到主屏幕。有导航抽屉。现在从片段列表中,我想使用其中一个片段从 google 注销。我怎样才能做到这一点。下面是我的代码:
LoginActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Session Manager
session = new SessionManager(getApplicationContext());
initUi();
setupListeners();
}
protected void onStart() {
super.onStart();
}
protected void onStop() {
super.onStop();
if (MyApplication.mGoogleApiClient.isConnected()) {
MyApplication.mGoogleApiClient.disconnect();
}
}
private void initUi(){
llGoogle = (LinearLayout)findViewById(R.id.activity_login_llsignin_google);
}
private void setupListeners(){
llGoogle.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (session.isConnected()) {
getProfileInformation();
} else {
}
}
});
}
private void resolveSignInError() {
if (MyApplication.mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
MyApplication.mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
MyApplication.mGoogleApiClient.connect();
}
}
}
private void googlePlusLogin() {
MyApplication.googlePlusLogin();
resolveSignInError();
}
MyApplication.java
public class MyApplication extends Application implements
ConnectionCallbacks, OnConnectionFailedListener,
ResultCallback<People.LoadPeopleResult>{
public static Typeface app_medium;
public static Typeface app_regular;
public static Typeface app_bold;
public static final String TAG = MyApplication.class.getSimpleName();
private static SharedPreferences Pref;
private static MyApplication mInstance;
private static final int RC_SIGN_IN = 0;
// Google client to communicate with Google
public static GoogleApiClient mGoogleApiClient;
public boolean mIntentInProgress;
public static boolean signedInUser;
public static ConnectionResult mConnectionResult;
@SuppressWarnings("unused")
public void onCreate() {
super.onCreate();
mInstance = this;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, Plus.PlusOptions.builder().build())
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
Pref = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
checkFBKey();
app_regular = Typeface.createFromAsset(getAssets(),
"fonts/dax_regular.ttf");
app_medium = Typeface.createFromAsset(getAssets(),
"fonts/dax_medium.ttf");
app_bold = Typeface.createFromAsset(getAssets(),
"fonts/dax_bold.ttf");
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
/**
* set user login
* */
// public static void setUserFBLogin() {
// // TODO Auto-generated method stub
// Editor edit_login_detail = Pref.edit();
// edit_login_detail.putBoolean(GeneralClass.temp_iUserFaceBookBLOGIN,
// true);
// edit_login_detail.commit();
// }
public void checkFBKey() {
PackageInfo info;
try {
info = getPackageManager().getPackageInfo(getPackageName(),
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
// String something = new
// String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
}
public static void googlePlusLogin() {
if (!mGoogleApiClient.isConnecting()) {
signedInUser = true;
}
}
public static void googlePlusLogout() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
// updateProfile(false);
}
}
public static void revokeGplusAccess() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status arg0) {
Log.e("LOGIN", "User access revoked!");
mGoogleApiClient.connect();
}
});
}
}
@Override
public void onLowMemory() {
// TODO Auto-generated method stub
super.onLowMemory();
}
@Override
public void onResult(LoadPeopleResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
if (!arg0.hasResolution()) {
return;
}
if (!mIntentInProgress) {
// store mConnectionResult
MyApplication.mConnectionResult = arg0;
if (signedInUser) {
}
}
}
@Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
Log.e("APPLICATION", "CONNECTED");
}
@Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
mGoogleApiClient.connect();
}
}
现在,我想在我的片段中使用 googlePlusLogout() 方法。我该怎么做呢?
您应该在 Application
class 中实现所有全局凭证和方法,以便您可以从任何 Activity
或 Fragment
class.
在应用程序 class 中声明将您的 LoginActivity 设置为 CurrentActivity 并使用 instanceOf
从应用程序 onConnected()
方法调用 LoginActivity
的 loginSuccessful 方法。您可以从 Application
class.
的片段调用 logOut 方法
选中跟随示例。
/**
* @author AA-Sk
*
*/
public class MyApplication extends Application {
private Activity mCurrentActivity;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onConnected(Bundle mBundle) {
Activity mActivity = getmCurrentActivity();
if (mActivity != null) {
if (mActivity instanceof LoginActivity) {
LoginActivity mLoginActivity = (LoginActivity) mActivity;
mLoginActivity.loginSuccessfull(mBundle);
}
}
}
private void googleLogout() {
}
public void setmCurrentActivity(Activity mCurrentActivity) {
this.mCurrentActivity = mCurrentActivity;
}
public Activity getmCurrentActivity() {
return mCurrentActivity;
}
/**
* @author AA-Sk
*
*/
public class LoginActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((MyApplication) getApplication()).setmCurrentActivity(LoginActivity.this);
}
private void loginSuccessfull(Bundle mBundle) {
// Store Data from bundle and call another activity as user is successfully logged in.
}
}
/**
* @author AA-Sk
*
*/
public class SampleActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
/**
* @author AA-Sk
*
*/
public class logout extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
public logout() {
((MyApplication) getActivity().getApplication()).googleLogout();
}
}
}
我有一个登录 activity,我使用 google 登录。成功登录后,我将转到主屏幕。有导航抽屉。现在从片段列表中,我想使用其中一个片段从 google 注销。我怎样才能做到这一点。下面是我的代码:
LoginActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
// Session Manager
session = new SessionManager(getApplicationContext());
initUi();
setupListeners();
}
protected void onStart() {
super.onStart();
}
protected void onStop() {
super.onStop();
if (MyApplication.mGoogleApiClient.isConnected()) {
MyApplication.mGoogleApiClient.disconnect();
}
}
private void initUi(){
llGoogle = (LinearLayout)findViewById(R.id.activity_login_llsignin_google);
}
private void setupListeners(){
llGoogle.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (session.isConnected()) {
getProfileInformation();
} else {
}
}
});
}
private void resolveSignInError() {
if (MyApplication.mConnectionResult.hasResolution()) {
try {
mIntentInProgress = true;
MyApplication.mConnectionResult.startResolutionForResult(this, RC_SIGN_IN);
} catch (SendIntentException e) {
mIntentInProgress = false;
MyApplication.mGoogleApiClient.connect();
}
}
}
private void googlePlusLogin() {
MyApplication.googlePlusLogin();
resolveSignInError();
}
MyApplication.java
public class MyApplication extends Application implements
ConnectionCallbacks, OnConnectionFailedListener,
ResultCallback<People.LoadPeopleResult>{
public static Typeface app_medium;
public static Typeface app_regular;
public static Typeface app_bold;
public static final String TAG = MyApplication.class.getSimpleName();
private static SharedPreferences Pref;
private static MyApplication mInstance;
private static final int RC_SIGN_IN = 0;
// Google client to communicate with Google
public static GoogleApiClient mGoogleApiClient;
public boolean mIntentInProgress;
public static boolean signedInUser;
public static ConnectionResult mConnectionResult;
@SuppressWarnings("unused")
public void onCreate() {
super.onCreate();
mInstance = this;
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(Plus.API, Plus.PlusOptions.builder().build())
.addScope(Plus.SCOPE_PLUS_LOGIN).build();
Pref = PreferenceManager
.getDefaultSharedPreferences(getApplicationContext());
checkFBKey();
app_regular = Typeface.createFromAsset(getAssets(),
"fonts/dax_regular.ttf");
app_medium = Typeface.createFromAsset(getAssets(),
"fonts/dax_medium.ttf");
app_bold = Typeface.createFromAsset(getAssets(),
"fonts/dax_bold.ttf");
}
public static synchronized MyApplication getInstance() {
return mInstance;
}
/**
* set user login
* */
// public static void setUserFBLogin() {
// // TODO Auto-generated method stub
// Editor edit_login_detail = Pref.edit();
// edit_login_detail.putBoolean(GeneralClass.temp_iUserFaceBookBLOGIN,
// true);
// edit_login_detail.commit();
// }
public void checkFBKey() {
PackageInfo info;
try {
info = getPackageManager().getPackageInfo(getPackageName(),
PackageManager.GET_SIGNATURES);
for (Signature signature : info.signatures) {
MessageDigest md;
md = MessageDigest.getInstance("SHA");
md.update(signature.toByteArray());
String something = new String(Base64.encode(md.digest(), 0));
// String something = new
// String(Base64.encodeBytes(md.digest()));
Log.e("hash key", something);
}
} catch (NameNotFoundException e1) {
Log.e("name not found", e1.toString());
} catch (NoSuchAlgorithmException e) {
Log.e("no such an algorithm", e.toString());
} catch (Exception e) {
Log.e("exception", e.toString());
}
}
public static void googlePlusLogin() {
if (!mGoogleApiClient.isConnecting()) {
signedInUser = true;
}
}
public static void googlePlusLogout() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
mGoogleApiClient.disconnect();
mGoogleApiClient.connect();
// updateProfile(false);
}
}
public static void revokeGplusAccess() {
if (mGoogleApiClient.isConnected()) {
Plus.AccountApi.clearDefaultAccount(mGoogleApiClient);
Plus.AccountApi.revokeAccessAndDisconnect(mGoogleApiClient)
.setResultCallback(new ResultCallback<Status>() {
@Override
public void onResult(Status arg0) {
Log.e("LOGIN", "User access revoked!");
mGoogleApiClient.connect();
}
});
}
}
@Override
public void onLowMemory() {
// TODO Auto-generated method stub
super.onLowMemory();
}
@Override
public void onResult(LoadPeopleResult arg0) {
// TODO Auto-generated method stub
}
@Override
public void onConnectionFailed(ConnectionResult arg0) {
// TODO Auto-generated method stub
if (!arg0.hasResolution()) {
return;
}
if (!mIntentInProgress) {
// store mConnectionResult
MyApplication.mConnectionResult = arg0;
if (signedInUser) {
}
}
}
@Override
public void onConnected(Bundle arg0) {
// TODO Auto-generated method stub
Log.e("APPLICATION", "CONNECTED");
}
@Override
public void onConnectionSuspended(int arg0) {
// TODO Auto-generated method stub
mGoogleApiClient.connect();
}
}
现在,我想在我的片段中使用 googlePlusLogout() 方法。我该怎么做呢?
您应该在 Application
class 中实现所有全局凭证和方法,以便您可以从任何 Activity
或 Fragment
class.
在应用程序 class 中声明将您的 LoginActivity 设置为 CurrentActivity 并使用 instanceOf
从应用程序 onConnected()
方法调用 LoginActivity
的 loginSuccessful 方法。您可以从 Application
class.
选中跟随示例。
/**
* @author AA-Sk
*
*/
public class MyApplication extends Application {
private Activity mCurrentActivity;
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onConnected(Bundle mBundle) {
Activity mActivity = getmCurrentActivity();
if (mActivity != null) {
if (mActivity instanceof LoginActivity) {
LoginActivity mLoginActivity = (LoginActivity) mActivity;
mLoginActivity.loginSuccessfull(mBundle);
}
}
}
private void googleLogout() {
}
public void setmCurrentActivity(Activity mCurrentActivity) {
this.mCurrentActivity = mCurrentActivity;
}
public Activity getmCurrentActivity() {
return mCurrentActivity;
}
/**
* @author AA-Sk
*
*/
public class LoginActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((MyApplication) getApplication()).setmCurrentActivity(LoginActivity.this);
}
private void loginSuccessfull(Bundle mBundle) {
// Store Data from bundle and call another activity as user is successfully logged in.
}
}
/**
* @author AA-Sk
*
*/
public class SampleActivity extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
/**
* @author AA-Sk
*
*/
public class logout extends Fragment {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return super.onCreateView(inflater, container, savedInstanceState);
}
public logout() {
((MyApplication) getActivity().getApplication()).googleLogout();
}
}
}