判断应用被强杀
在Application中定义一个静态变量,给一个初始值,然后在闪屏页面为这个变量重新赋值,接下来闪屏页面会跳转到主页面,我们在主页面对这个值进行判断,如果变量的值是初始值,则说明应用被强杀了,接下来看看相关代码
public class MyApp extends Application {
public static int CODE = -1;
public MyApp app;
@Override
public void onCreate() {
super.onCreate();
app = this;
}
}
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApp.CODE = 1;
setContentView(R.layout.activity_splash);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startActivity(new Intent(SplashActivity.this,MainActivity.class));
finish();
}
},2000);
}
}
public class MainActivity extends AppCompatActivity {
private TextView textView;
private int code;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
code = MyApp.CODE;
if(code == -1){
//应用被强杀了
}
}
}
如何模拟应用在后台被强杀呢,很简单,我们把应用切换到后台,
空指针问题
接下来演示一个应用在后台被强制杀死后重新启动出现空指针的问题,代码如下
public class MyApp extends Application {
public static int CODE = -1;
public MyApp app;
//集合,用于保存数据
public static ArrayList<String> list;
@Override
public void onCreate() {
super.onCreate();
app = this;
}
}
我们在Application中定义了一个集合,然后在闪屏页面为它初始化并赋值,
public class SplashActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MyApp.CODE = 1;
setContentView(R.layout.activity_splash);
MyApp.list = new ArrayList();
MyApp.list.add("你好");
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
startActivity(new Intent(SplashActivity.this,MainActivity.class));
finish();
}
},2000);
}
}
public class MainActivity extends AppCompatActivity {
private TextView textView;
private int code;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.textview);
code = MyApp.CODE;
if(code == -1){
//重新走一遍启动流程,保证数据初始化
startActivity(new Intent(this,SplashActivity.class));
}
//注意,应用如果在后台被强制杀死,此处会出现空指针
if(MyApp.list!=null){
textView.setText(MyApp.list.get(0));
}
}
}
当应用在后台被杀死的时候,闪屏页面并不会走,这时候集合就未进行初始化,我们需要判断一下,或者我们对CODE进行判断,如果强杀了我们重新走一遍启动流程,这样就能保证集合用于不为空了。