直接贴代码了
SharedActivity.java类
package com.org.ruizi;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.KeyEvent;
import android.widget.TextView;
import android.widget.Toast;
public class SharedActivity extends Activity {
private TextView tv = null;
private boolean mb = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView)findViewById(R.id.tv);
SharedPreferences settings = getSharedPreferences("mb2", 0);
mb = settings.getBoolean("mb2", false);
if(mb)
{
tv.setText("开了");
Toast.makeText(this, "true", Toast.LENGTH_SHORT).show();
}
else
{
tv.setText("关了");
Toast.makeText(this, "false", Toast.LENGTH_SHORT).show();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if(keyCode==KeyEvent.KEYCODE_BACK)
{
SharedPreferences usState = getSharedPreferences("mb2", 0);
SharedPreferences.Editor editor = usState.edit();
editor.putBoolean("mb2", mb);
editor.commit();
startActivity(new Intent().setClass(SharedActivity.this, Activity2.class));
this.finish();
}
return true;
}
@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_DOWN:
tv.setText("关了");
mb = false;
break;
case KeyEvent.KEYCODE_DPAD_UP:
tv.setText("开了");
mb = true;
break;
default:
break;
}
return true;
}
}
Activity2.java类
package com.org.ruizi;
import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.widget.Toast;
public class Activity2 extends Activity {
private boolean mb = false;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
SharedPreferences settings = getSharedPreferences("mb2", 0);
mb = settings.getBoolean("mb2", false);
Toast.makeText(this, ""+mb, Toast.LENGTH_LONG).show();
}
}
对应的布局文件是就只有TextView 控件我就不写了