![](/img/trans.png)
[英]How to check why job gets killed on Google Dataflow ( possible OOM )
[英]How to check the process status after it is killed, or is this even possible?
一些有意引入空指针异常的代码如下:
// access modifiers omitted for brevity
class MyApplication extends Application {
String name;
String getName() {
return name;
}
void setName(String name) {
this.name = name;
}
}
// ====================================
// access modifiers omitted for brevity
class WhatIsYourNameActivity extends Activity {
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.writing);
// Just assume that in the real app we would really ask it!
MyApplication app = (MyApplication) getApplication();
app.setName("Developer Phil");
startActivity(new Intent(this, GreetLoudlyActivity.class));
}
}
// ================================================ ======
// access modifiers omitted for brevity
class GreetLoudlyActivity extends Activity {
TextView textview;
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.reading);
textview = (TextView) findViewById(R.id.message);
}
void onResume() {
super.onResume();
MyApplication app = (MyApplication) getApplication();
textview.setText("HELLO " + app.getName().toUpperCase());
}
}
用户启动应用程序。 在WhatIsYourNameActivity中,您要求输入用户的名称并将其存储在MyApplication中。 在GreetLoudlyActivity中,您从MyApplication对象中获取用户名并显示它。 用户使用主页按钮离开应用程序。 几个小时后,Android默默杀死应用程序以回收一些内存。
到现在为止还挺好!
但这里出现了崩溃的部分......
用户重新打开应用程序。 Android创建一个新的MyApplication实例并恢复GreetLoudlyActivity。 GreetLoudlyActivity获取用户的名称,该名称现在为null,并且使用NullPointerException崩溃。
发生崩溃是因为Application对象是全新的,因此name变量为null,当我们在其上调用String#toUpperCase()时会导致NullPointerException。
命令行,当您在模拟器或root电话上运行时:启动应用程序,然后:
adb shell ps
在设备和命令行上按home:
adb shell ps | grep com.crashy.package
和:
adb shell kill <PID from above step>
现在,我们尝试使用最新的应用程序选项卡从后台恢复应用程序,并按预期崩溃。 问题是如何列出与进程一起被杀死的所有对象的状态 - 或者杀死进程是否会杀死所有关联的对象? 有没有办法分叉这个过程?
“......或者杀死一个进程会杀死所有相关对象吗?”
这正是发生的事情。 当一个进程被终止时,操作系统将回收它所有拥有的内存 - 如果没有发生这种情况,每次进程死机并且操作系统最终会耗尽内存时会出现内存泄漏。
一旦进程/应用程序终止,您将丢失未保存到永久存储器的所有内容。
问题是你试图用一个简单的变量来模拟持久存储。 为了更好地理解,我将调查Android Activity的生命周期,以了解应用程序被“杀死”的方式和时间http://developer.android.com/training/basics/activity-lifecycle/index.html
现在找到一个解决方案,我建议使用共享首选项管理器。(您的数据看起来不够大,无法证明sqlLite数据库的合理性)
在您的存储活动中,使用此名称保存名称
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this)
Preferences.Editor edit = preferences.edit();
edit.putString('name', 'someName');
edit.commit();
并在其他活动中检索它
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this)
preferences.getString('name');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.