在activity的onResume()方法启动服务,直接“很抱歉,已停止运行”
protected void onResume() {
super.onResume();
if(isNetworkAvailable())
{
Log.e("login_resume", "+++++++++++++++++++++++");
Intent service = new Intent(this, GetMsgService.class);
startService(service);
}else {
toast(this);
}
我的service是下面的内容,主要是通过一个client启动读写线程,用于socket的传输:
import com.example.client.Client;
import com.example.client.ClientInputThread;
import com.example.client.MessageListener;
import com.example.tran.bean.TranObject;
import com.example.util.Constants;
import com.example.util.SharedPreferencesUtil;
import android.app.Application;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class GetMsgService extends Service{
private MyApplication myApplication;
private SharedPreferencesUtil util;
private Client client;
private Context context = this;
private boolean isStart = false;// 是否与服务器连接上
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
myApplication = (MyApplication) this.getApplicationContext();
client = myApplication.getClient();
Log.e("service_oncreate", "++++++++++++++++++++");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
super.onStartCommand(intent, flags, startId);
isStart = client.start();
myApplication.setClientStart(isStart);
System.out.print(isStart);
Log.e("service", "+++++++++++++++++++++++++++++");
if(isStart)
{
ClientInputThread inputThread = client.getClientInputThread();
inputThread.setMessageListener(new MessageListener() {
@Override
public void Message(TranObject tranObject) {
// TODO Auto-generated method stub
Intent broadcast = new Intent();
broadcast.setAction(Constants.ACTION);
broadcast.putExtra(Constants.MSGKEY, tranObject);
sendBroadcast(broadcast);
}
});
}
return START_REDELIVER_INTENT;
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}