【发布时间】:2016-02-18 11:46:32
【问题描述】:
我有一个Activity 和一个Service。该活动用于搜索,该服务用于在所有屏幕上显示一个悬停小部件,就像 Facebook 聊天头一样。
当用户像按返回键一样离开活动时,我会启动一项服务,并且小部件开始悬停。单击悬停小部件时,活动将再次使用FLAG_ACTIVITY_NEW_TASK 从服务中重新启动。但是,当我的活动与其他应用程序活动重叠时,onStop() 和 onPause() 都不会被调用。当onStop() 上面的活动被调用时,onStop() 被调用。
有人可以解释为什么会这样吗?提前致谢。
活动代码:
public class CouponSearchActivity extends AppCompatActivity {
public static final String TAG = CouponSearchActivity.class.getSimpleName();
public static final String BROADCAST_ACTION_ACTIVITY_STARTED =
"activity_created";
public static final String BROADCAST_ACTION_ACTIVITY_STOPPED = "activity_stopped";
public static void startActivity(Context context){
Intent intent = new Intent(context, CouponSearchActivity.class);
context.startActivity(intent);
}
public static void startActivityFromService(Context context){
Intent intent = new Intent(context, CouponSearchActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("TAG",": onCreate()");
setContentView(R.layout.activity_coupon_search);
CouponWidgetService.stopService(this);
if(savedInstanceState == null){
initCouponSearchFragment();
}
}
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
Log.d("TAG",": onNewIntent()");
}
private void initCouponSearchFragment(){
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.container, CouponSearchFragment.newInstance()).commit();
}
private void sendBroadcast(){
Intent intent = new Intent();
intent.setAction(BROADCAST_ACTION_ACTIVITY_STARTED);
sendBroadcast(intent);
Log.d("Broadcast sent", action = " +BROADCAST_ACTION_ACTIVITY_STARTED);
}
@Override
protected void onResume() {
super.onResume();
Log.d("TAG","onResume()");
sendBroadcast();
CouponWidgetService.stopService(this);
}
@Override
protected void onPause() {
super.onPause();
Log.d("TAG + "onPause()");
}
@Override
protected void onStop() {
super.onStop();
Intent intent = new Intent();
intent.setAction(BROADCAST_ACTION_ACTIVITY_STOPPED);
sendBroadcast(intent);
Log.d("TAG", "onStop()");
Log.d("Broadcast sent", action = " + BROADCAST_ACTION_ACTIVITY_STOPPED);
CouponWidgetService.startService(this, StoreCoupons.getStoreCouponsResponse(), StoreCoupons.getSelectedCategories());
}
@Override
public void onBackPressed() {
Log.d("onBackPressed()");
//CouponWidgetService.startService(this, StoreCoupons.getStoreCouponsResponse(), StoreCoupons.getSelectedCategories());
super.onBackPressed();
}
【问题讨论】:
-
你怎么知道 onStop() 和 onPause() 没有被调用?你在记录这些方法吗?
-
@barq 是的。但是当它上面的活动停止时,我的活动的 onStop() 就会被调用。
-
onPause() 将在您的活动进入后台时被调用。也许您可以展示您的代码以获取更多信息?
标签: android activity-lifecycle