我试图将compileSDKVersion更新为27,所以我也将支持库更改为27.1.1。
现在,我的应用程序将像往常一样启动,但是当我尝试启动新活动时,该应用程序冻结。 在后台模式下恢复时,它也会冻结。
某些代码:
家庭活动
这是第一个有效的活动,仅在后台运行后恢复冻结
public class HomeActivity extends BaseActivity implements SharedPreferences.OnSharedPreferenceChangeListener,
FirebaseUpdaterController.Listener{
private static final String TAG = "HomeActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
if (savedInstanceState == null) { // first opened
savedInstanceState = getIntent().getExtras();
}
if (savedInstanceState != null && savedInstanceState.getString(COUPLE_UID) != null) {
Utility.saveStringPreference(getApplicationContext(), SharedPrefKeys.PARTNER_UID, savedInstanceState.getString(PARTNER_UID));
Utility.saveStringPreference(getApplicationContext(), SharedPrefKeys.PARTNER_USERNAME, savedInstanceState.getString(PARTNER_USERNAME));
Utility.saveStringPreference(getApplicationContext(), SharedPrefKeys.PARTNER_IMAGE_URI, savedInstanceState.getString(PARTNER_IMAGE_URI));
Utility.saveStringPreference(getApplicationContext(), SharedPrefKeys.COUPLE_UID, savedInstanceState.getString(COUPLE_UID));
super.updateRepositories();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.home_activity);
Utility.askStoragePermission(this);
if (getIntent().getExtras() != null && getIntent().getExtras().getBoolean(MULTI_COUPLE_NOTIFICATIONS)) {
BottomSheetDialogFragment bottomSheetDialogFragment = new ChangeCoupleBottomSheetDialogFragment();
//show it
bottomSheetDialogFragment.show(getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
}
mToolbar = (Toolbar) findViewById(R.id.home_toolbar);
mToolbar.getBackground().setAlpha(0);
mToolbar.getLayoutParams().height = UtilisGraphic.getStatusBarHeight(this) + (int) getResources().getDimension(R.dimen.app_bar_height);
mToolbar.setPadding(0, UtilisGraphic.getStatusBarHeight(this), 0, 0);
mToolbar.requestLayout();
setSupportActionBar(mToolbar);
mFirebaseSuggestionsController = new FirebaseSuggestionsController(
mUserUid,
Utility.getStringPreference(getApplicationContext(), SharedPrefKeys.USERNAME),
Utility.getStringPreference(getApplicationContext(), SharedPrefKeys.DEBUG)
);
mFirebaseUpdaterController = new FirebaseUpdaterController(
mUserUid,
Utility.getStringPreference(getApplicationContext(), SharedPrefKeys.DEBUG)
);
mFirebaseUpdaterController.setListener(this);
mDialog =
new MaterialDialog.Builder(this)
.iconRes(R.drawable.suggestions_icon)
.limitIconToDefaultSize()
.title(R.string.questioner_dialog_title)
.customView(R.layout.custom_dialog_suggestions, true)
.positiveText(R.string.affermative_suggestions_dialog)
.negativeText(R.string.negative_suggestions_dialog)
.onPositive(new MaterialDialog.SingleButtonCallback() {
@Override
public void onClick(MaterialDialog dialog, DialogAction which) {
suggestionText = suggestionInput.getText().toString();
sendSuggestions(selectedRadio, suggestionText);
Utility.saveBooleanPreference(getApplicationContext(), SharedPrefKeys.SUGGESTION_SENT, true);
mMenu.findItem(R.id.menu_suggestions).setVisible(false);
}
})
.build();
positiveActionSuggestion = mDialog.getActionButton(DialogAction.POSITIVE);
suggestionInput = (EditText) mDialog.getCustomView().findViewById(R.id.suggestion_input_edittex);
suggestionInput.setVisibility(View.GONE);
suggestionInput.addTextChangedListener(
new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
positiveActionSuggestion.setEnabled(s.toString().trim().length() > 5);
}
@Override
public void afterTextChanged(Editable s) {}
});
RadioGroup radioGroup = (RadioGroup) mDialog.getCustomView().findViewById(R.id.myRadioGroup);
radioGroup.check(R.id.radio_0);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener(){
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch(checkedId)
{
case R.id.radio_0:
selectedRadio = 0;
suggestionInput.setVisibility(View.GONE);
suggestionInput.clearFocus();
break;
case R.id.radio_1:
selectedRadio = 1;
suggestionInput.setVisibility(View.GONE);
suggestionInput.clearFocus();
break;
case R.id.radio_2:
selectedRadio = 2;
suggestionInput.setVisibility(View.GONE);
suggestionInput.clearFocus();
break;
case R.id.radio_other:
selectedRadio = 3;
suggestionInput.setVisibility(View.VISIBLE);
suggestionInput.requestFocus();
if(suggestionInput.getText().length() < 6) {
positiveActionSuggestion.setEnabled(false);
}
break;
}
}
});
mView = (HomeFragment) getSupportFragmentManager()
.findFragmentById(R.id.home_fragment_container);
if (mView == null) {
mView = HomeFragment.newInstance(getIntent().getExtras());
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.add(R.id.home_fragment_container, mView);
transaction.commit();
}
}
@Override
protected void onResume() {
super.onResume();
PreferenceManager.getDefaultSharedPreferences(this)
.registerOnSharedPreferenceChangeListener(this);
Intent intent = getIntent();
if(intent.getStringExtra(URI) != null){
mUri = Uri.parse(intent.getStringExtra(URI));
ChatRepository.getInstance(getApplicationContext()).setUriImportWa(mUri);
intent.removeExtra(URI);
//changePageTo(DashboardPagerAdapter.HOME_TAB);
}
}}
BaseActivity
所有活动都扩展了该基类
public class BaseActivity extends AppCompatActivity implements
GoogleApiClient.OnConnectionFailedListener,
SharedPreferences.OnSharedPreferenceChangeListener,
GoogleApiClient.ConnectionCallbacks,
ForceUpdateChecker.OnUpdateNeededListener{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final FirebaseRemoteConfig firebaseRemoteConfig = FirebaseRemoteConfig.getInstance();
// set in-app defaults
Map<String, Object> remoteConfigDefaults = new HashMap();
remoteConfigDefaults.put(ForceUpdateChecker.KEY_UPDATE_REQUIRED, false);
remoteConfigDefaults.put(ForceUpdateChecker.KEY_CURRENT_VERSION, "1.0.0");
remoteConfigDefaults.put(ForceUpdateChecker.KEY_UPDATE_URL,
"https://google.com");
firebaseRemoteConfig.setDefaults(remoteConfigDefaults);
firebaseRemoteConfig.fetch(MINUTE_TO_FETCH) // fetch every minutes
.addOnCompleteListener(new OnCompleteListener<Void>() {
@Override
public void onComplete(@NonNull Task<Void> task) {
if (task.isSuccessful()) {
Log.d(BASE_TAG, "remote config is fetched.");
firebaseRemoteConfig.activateFetched();
}
}
});
// Getting utils data for all activity
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
if(sp.getBoolean(SharedPrefKeys.USER_RELATIONSHIP_STATUS_CHANGED, false)){
checkUserRelationshipStatus();
}
mUserUid = sp.getString(SharedPrefKeys.USER_UID, SharedPrefKeys.DEFAULT_VALUE);
mCoupleUid = sp.getString(SharedPrefKeys.COUPLE_UID, mUserUid);
if(MainActivity.apiServiceAmazon == null){
Gson gson = new GsonBuilder()
.setLenient()
.create();
Retrofit retrofitAmazon = new Retrofit.Builder()
.baseUrl(BASE_URL_AMAZON_EB)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
MainActivity.apiServiceAmazon = retrofitAmazon.create(ServerApiAmazonInterface.class);
Retrofit retrofitCloud = new Retrofit.Builder()
.baseUrl(BASE_URL_CLOUD_FUNCTION)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();
MainActivity.apiServiceCloud = retrofitCloud.create(ServerApiCloudFunctionInterface.class);
}
if (MainActivity.db == null) {
MainActivity.db = Room.databaseBuilder(getApplicationContext(),
SweetieDatabase.class, "DB").fallbackToDestructiveMigration().build();
}
/* Setup the Google API object to allow Google logins */
GoogleSignInOptions gso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
.requestIdToken(getString(R.string.server_client_ID))
.requestEmail()
.build();
/* Setup the Google API object to allow Google+ logins */
mGoogleApiClient = new GoogleApiClient.Builder(getApplicationContext())
.enableAutoManage(this, this /* OnConnectionFailedListener */)
.addConnectionCallbacks(this)
.addApi(Auth.GOOGLE_SIGN_IN_API, gso)
.addApi(LocationServices.API)
.build();
mFirebaseAuth = FirebaseAuth.getInstance();
}
HomeFragment
我在其中启动冻结应用程序的其他活动的片段。
public class HomeFragment extends Fragment implements LifecycleOwner, SweetboxCardAdapter.SweetboxCardAdapterListener, SweetBoxReadScanner.onCounter, ChooseCoupleAdapter.ChooseCoupleAdapterListener {
public static HomeFragment newInstance(Bundle bundle) {
HomeFragment newHomeFragment = new HomeFragment();
newHomeFragment.setArguments(bundle);
return newHomeFragment;
}
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mLifecycleRegistry = new LifecycleRegistry(this);
mLifecycleRegistry.markState(Lifecycle.State.CREATED);
mAnimShow = AnimationUtils.loadAnimation( getContext(), R.anim.slide_in_left);
mAnimShowFadeIn = AnimationUtils.loadAnimation( getContext(), R.anim.fade_in);
mAnimscaleIn = AnimationUtils.loadAnimation(getContext(),R.anim.scale_up);
}
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
root = inflater.inflate(R.layout.home_layout_scrollable, container, false);
mCustomView = inflater.inflate(R.layout.import_progress_dialog_view,null);
mCompleteImportCustomView = inflater.inflate(R.layout.import_complete_dialog_view, null);
mCompleteImportCustomView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
mCompleteImportDialog.dismiss();
}
});
mTitleTextView = (EmojiconTextView) root.findViewById(R.id.action_item_title);
mDiaryDescription = (TextView) root.findViewById(R.id.sweetbox_card_description_view);
mDescriptionTextView = (EmojiconTextView) root.findViewById(R.id.action_item_subtitle);
mDateTextView = (TextView) root.findViewById(R.id.action_item_date);
mAppBarImageView = (CircleImageView) root.findViewById(R.id.app_bar_image_view);
mAppBarImageView.setVisibility(View.GONE);
mNoAppBarImageTextView = (TextView) root.findViewById(R.id.app_bar_no_image_text);
mNoAppBarImageTextView.setVisibility(View.GONE);
mHeartOff = root.findViewById(R.id.sweetbox_card_heart_off);
mFullHeart = root.findViewById(R.id.sweetbox_card_full_heart);
mAppBarExtension = root.findViewById(R.id.toolbar);
mAppBarExtension.getLayoutParams().height =(int) UtilisGraphic.dpToPx(50, getContext()) + UtilisGraphic.getStatusBarHeight(getContext());
mAppBarExtension.requestLayout();
mAvatarImageView = (ImageView) root.findViewById(R.id.image_action_list_item);
mNoImageTextView = (TextView) root.findViewById(R.id.action_no_image_text);
mTypeIcon = (ImageView) root.findViewById(R.id.action_item_type);
mNotificCounter = (TextView) root.findViewById(R.id.action_item_notification_counter);
avatarClickZone = (View) root.findViewById(R.id.avatar_click_zone);
actionClickZone = (View) root.findViewById(R.id.action_click_zone);
mChangeCoupleFab = (FloatingActionButton) root.findViewById(R.id.change_couple_fab);
mChangeCoupleFab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
BottomSheetDialogFragment bottomSheetDialogFragment = ChangeCoupleBottomSheetDialogFragment.getInstance(getActivity());
//show it
bottomSheetDialogFragment.show(getActivity().getSupportFragmentManager(), bottomSheetDialogFragment.getTag());
}
});
mDiaryCard = (CardView) root.findViewById(R.id.diary_card_view);
mDiaryCard.setVisibility(View.GONE);
mChatCard = (CardView) root.findViewById(R.id.chat_card_view);
mChatCard.setVisibility(View.GONE);
mCardStackView = (SwipeFlingAdapterView) root.findViewById(R.id.home_sweetbox_recycler_view);
mArrayList = new ArrayList<MessageVM>();
mSweetboxAdapter = new SweetboxCardAdapter(getContext());
mCardStackView.setAdapter(mSweetboxAdapter);
mSweetboxAdapter.setListener(this);
mCardStackView.setFlingListener(new SwipeFlingAdapterView.onFlingListener() {
@Override
public void removeFirstObjectInAdapter() {
}
@Override
public void onLeftCardExit(Object dataObject) {
mHeartOff.startAnimation(mAnimscaleIn);
MessageVM messageVM = (MessageVM) dataObject;
ChatRepository.getInstance(getContext()).discardMessage(messageVM, MessageVM.TEXT_MSG);
}
@Override
public void onRightCardExit(Object dataObject) {
mFullHeart.startAnimation(mAnimscaleIn);
MessageVM messageVM = (MessageVM) dataObject;
messageVM.setBookmarked(true);
ChatRepository.getInstance(getContext()).bookmarkMessage(messageVM, MessageVM.TEXT_MSG);
}
@Override
public void onAdapterAboutToEmpty(int itemsInAdapter) {
// Ask for more data here
}
@Override
public void onScroll(float v) {
}
});
mHomeViewModel = ViewModelProviders.of(this).get(HomeViewModel.class);
createObservers();
setupAppBar();
setupChatCard();
setupDiaryCard();
return root;
}
@Override
public void onResume() {
super.onResume();
if(ChatRepository.getInstance(getContext()).isImportWa()){
mUri = ChatRepository.getInstance(getContext()).getUriImportWa();
mFileName = "cache_file.txt";
try {
mTextFileStream = new DataInputStream(getContext().getContentResolver().openInputStream(mUri));
File file = new File(getContext().getCacheDir(), mFileName);
OutputStream output = new FileOutputStream(file);
try {
byte[] buffer = new byte[1024]; // or other buffer size
int read;
while ((read = mTextFileStream.read(buffer)) != -1) {
output.write(buffer, 0, read);
}
output.flush();
} finally {
output.close();
mTextFileStream.close();
}
}
catch (IOException e) {
e.printStackTrace();
}
if(mTextFileStream != null) {
mUri = null;
((HomeActivity)getActivity()).clearUri();
ChatRepository.getInstance(getContext()).clearUriImportWa();
mDialog = new MaterialDialog.Builder(getContext())
.title(R.string.where_import)
// second parameter is an optional layout manager. Must be a LinearLayoutManager or GridLayoutManager.
.adapter(new ChooseCoupleAdapter(getContext(),this), new GridLayoutManager(getActivity(),3))
.build();
mDialog.show();
} else {
Log.d(TAG, "Can't open the uri");
}
}
}
private void setupChatCard() {
final String coupleUid = Utility.getStringPreference(getContext(), SharedPrefKeys.COUPLE_UID);
String userUid = Utility.getStringPreference(getContext(), SharedPrefKeys.USER_UID);
mTitleText = getString(R.string.personal_messages);
if(!userUid.equals(coupleUid)){
mTitleText = Utility.getStringPreference(getContext(),SharedPrefKeys.PARTNER_USERNAME);
}
mTitleTextView.setText(mTitleText);
mHomeViewModel.getMainChatDate(getContext(), Utility.getStringPreference(getContext(), SharedPrefKeys.COUPLE_UID)).observe(this, mChatDateObserver);
mHomeViewModel.getMainChatDescription(getContext(), Utility.getStringPreference(getContext(), SharedPrefKeys.COUPLE_UID)).observe(this, mChatDescriptionObserver);
mHomeViewModel.getMainChatImage(getContext(), Utility.getStringPreference(getContext(), SharedPrefKeys.COUPLE_UID)).observe(this, mChatImageObserver);
mHomeViewModel.getMainChatNotificCounter(getContext(), Utility.getStringPreference(getContext(), SharedPrefKeys.COUPLE_UID)).observe(this, mChatNotificCounterObserver);
avatarClickZone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
//if in couples
if(coupleUid != null && !coupleUid.equals(Utility.getStringPreference( getContext(),SharedPrefKeys.USER_UID))){
startActivity(new Intent(getActivity(), CoupleDetailsActivity.class));
}else{
Intent intent = new Intent(getActivity(), ChatActivity.class);
intent.putExtra(ChatActivity.ACTION_DATABASE_KEY, coupleUid);
startActivity(intent);
}
}
});
actionClickZone.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent intent = new Intent(getActivity(), ChatActivity.class);
intent.putExtra(ChatActivity.ACTION_DATABASE_KEY, coupleUid);
animateChatIntent(mChatCard, intent);
}
});
mChatCard.setVisibility(View.VISIBLE);
mChatCard.startAnimation(mAnimShow);
}
清单
<application
android:name=".MyApplication"
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<!-- activity -->
<activity android:name=".MainActivity"
android:theme="@style/AppTheme"
android:launchMode="singleTask"
android:screenOrientation="sensorPortrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/*" />
<data android:mimeType="*/*"/>
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.SEND_MULTIPLE" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="text/*" />
<data android:mimeType="*/*"/>
</intent-filter>
</activity>
<activity android:name=".tutorial.InitTutorialActivity"
android:theme="@style/ChatTheme"
android:screenOrientation="sensorPortrait"/>
<activity android:name=".login.LoginActivity"
android:theme="@style/ChatTheme"
android:screenOrientation="sensorPortrait"/>
<activity android:name=".registration.RegistrationActivity"
android:theme="@style/ChatTheme"
android:screenOrientation="sensorPortrait"/>
<activity android:name=".pairing.PairingActivity"
android:parentActivityName=".home.HomeActivity"
android:theme="@style/AppTheme"
android:screenOrientation="sensorPortrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".home.HomeActivity"/>
</activity>
<activity android:name=".chatMVVM.ChatActivity"
android:parentActivityName=".home.HomeActivity"
android:theme="@style/ChatTheme"
android:windowSoftInputMode="adjustResize"
android:screenOrientation="sensorPortrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".home.HomeActivity"/>
<intent-filter>
<action android:name="open_chat_intent_filter" />
</intent-filter>
</activity>
<activity android:name=".couple.CoupleActivity"
android:parentActivityName=".home.HomeActivity"
android:noHistory="true"
android:theme="@style/AppTheme"
android:screenOrientation="sensorPortrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".home.HomeActivity"/>
</activity>
<activity android:name=".couple.CoupleDetailsActivity"
android:theme="@style/AppTheme"
android:screenOrientation="sensorPortrait"/>
<activity android:name=".settings.SettingsActivity"
android:parentActivityName=".home.HomeActivity"
android:theme="@style/AppTheme"
android:screenOrientation="sensorPortrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".home.HomeActivity"/>
</activity>
<activity android:name=".chatMVVM.ChatInfoActivity"
android:parentActivityName=".chatMVVM.ChatActivity"
android:theme="@style/AppTheme"
android:screenOrientation="sensorPortrait">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value=".chatMVVM.ChatActivity"/>
</activity>
<activity android:name=".home.HomeActivity"
android:theme="@style/HomeTheme"
android:screenOrientation="sensorPortrait"/>
<activity android:name=".diaryMVVM.DiaryActivity"
android:theme="@style/AppTheme"
android:screenOrientation="sensorPortrait"/>