安卓页面切换时与服务器的连接就断开了
与服务器的连接方式是用socket有人提议用后台服务,但试过了没有成功,求助哪里错误。
service代码:
public class MyService extends Service {
private static final String TAG = "TestService";
public static Socket socket= null;//声明套接字类
public IBinder onBind(Intent i) {
Log.e(TAG, "============> MyService.onBind");
return null;
}
//service创建时调用
public void onCreate() {
super.onCreate();
new Thread(){
@Override
public void run(){
//连接到服务器
try {
socket= new Socket("10.200.181.237",1230);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();//打印异常
}
finally{
try{
if(socket != null){
socket.close();
socket= null;
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
}.start();
}
public void onStart(Intent intent,int startId){
Log.e(TAG, "============> MyService.onStart");
super.onStart(intent, startId);
}
public void onDestroy() {
Log.e(TAG, "============> TestService.onDestroy");
super.onDestroy();
}
}
页面代码:
public class MainActivity extends Activity{
public static EditText username =null;//声明用户名编辑框,用于用户输入用户名
private EditText password =null;//声明密码编辑框,用于用户输入密码
CheckBox cb = null;//记住密码
private String string="";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button loginbutton=(Button)findViewById(R.id.button1);
cb = (CheckBox)findViewById(R.id.checkBox1);
username=(EditText)findViewById(R.id.editText1);
password=(EditText)findViewById(R.id.editText2);
loginbutton.setOnClickListener(startListener);
}
private OnClickListener startListener=new OnClickListener()
{
@Override
public void onClick(View v)
{
Intent intent = new Intent();
intent.setAction(".Myservice");
startService(intent);
String editUid = username.getText().toString();
String editPwd = password.getText().toString();
DataOutputStream dout = null;
DataInputStream din = null;
//连接到服务器
try {
dout = new DataOutputStream(MyService.socket.getOutputStream());//向服务器发送消息
din = new DataInputStream(MyService.socket.getInputStream()); //接收服务器消息
dout.writeUTF("Login,"+username.getText().toString()+","+password.getText().toString());
String msg = din.readUTF();//msg用于保存来自服务器的消息
Intent intent1 = new Intent();
intent1.setClass(MainActivity.this, Login_Ok.class);
}
catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();//打印异常
}
finally{
try{
if(din != null){
din.close();
din = null;
}
}
catch(Exception e){
e.printStackTrace();
}
try{
if(dout != null){
dout.close();
dout = null;
}
}
catch(Exception e){
e.printStackTrace();
}
}
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
Android 服务器 service 求助
补充:移动开发 , Android