关于Android Activity 调用onDestroy 后可以接收KeyEvent 吗?为啥 mapLayout 为空?
Posted
技术标签:
【中文标题】关于Android Activity 调用onDestroy 后可以接收KeyEvent 吗?为啥 mapLayout 为空?【英文标题】:Can receive KeyEvent after onDestroy called about Android Activity? Why mapLayout is null?关于Android Activity 调用onDestroy 后可以接收KeyEvent 吗?为什么 mapLayout 为空? 【发布时间】:2017-04-04 16:13:08 【问题描述】:mapLayout
在onCreate
初始化并在onDestroy
释放。为什么mapLayout
是null
而onNewIntent
和dispatchKeyEvent
?
onNewIntent
有NullPointException
java.lang.NullPointerException: Attempt to invoke virtual method 'void MapLayout.clearFocusedOverlay()' on a null object reference
at com.xxx.activity.MainActivity.onNewIntent(MainActivity.java:486)
at android.app.Instrumentation.callActivityOnNewIntent(Instrumentation.java:1210)
at android.app.ActivityThread.deliverNewIntents(ActivityThread.java:2438)
这是堆栈跟踪。
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean MapLayout.hasFocusedOverlay()' on a null object reference
at com.xxx.activity.MainActivity.dispatchKeyEvent(MainActivity.java:794)
at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchKeyEvent(PhoneWindow.java:2389)
at ...
这是我的代码
public class MainActivity extends Activity
private static MapLayout mapLayout;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mapLayout = (MapLayout) findViewById(R.id.map_container);
@Override
protected void onNewIntent(Intent intent)
super.onNewIntent(intent);
setIntent(intent);
mapLayout.clearFocusedOverlay()
@Override
protected void onDestroy()
Log.i(TAG, "onDestroy");
mapLayout = null;
super.onDestroy();
@Override
public boolean dispatchKeyEvent(KeyEvent event)
Log.i(TAG, "dispatchKeyEvent: "+event);
if (event.getAction() == KeyEvent.ACTION_DOWN
&& event.getKeyCode() == KeyEvent.KEYCODE_BACK)
if (mapLayout.hasFocusedOverlay())
mapLayout.clearFocusedOverlay();
mapLayout.mapView.invalidate();
else
Intent i = new Intent();
i.setAction(Intent.ACTION_MAIN);
i.addCategory(Intent.CATEGORY_HOME);
startActivity(i);
return true;
return super.dispatchKeyEvent(event);
【问题讨论】:
【参考方案1】:因为 私有静态 MapLayout mapLayout; 当 'MainActivity' 有多个实例时。如果 'MainActivity' 的一个实例销毁,则 'mapLayout' 变为 'null'。
所以当 'MainActivity' 的其他实例使用 'mapLayout' 时会导致 NullPointException。
【讨论】:
以上是关于关于Android Activity 调用onDestroy 后可以接收KeyEvent 吗?为啥 mapLayout 为空?的主要内容,如果未能解决你的问题,请参考以下文章
如何从Xamarin Android Activity中调用MvxViewModel?
关于android编程中service和activity的区别