I have created a TCP socket connection using Android service. The activity starts when the button is clicked in the MainActivity. And it works properly and closes the connection when the Activity is destroyed. MyService.java
public class MyService extends Service{
public static Socket clientsocket;
public static PrintWriter printer;
SendMessage sender;
@Override
public void onCreate() {
Toast.makeText(this, "Created", Toast.LENGTH_LONG).show();
super.onCreate();
}
@Override
public void onDestroy() {
Toast.makeText(this, "Stoped", Toast.LENGTH_LONG).show();
if(clientsocket!=null){
try{
clientsocket.close();
Toast.makeText(this, "Socket Closed", Toast.LENGTH_LONG).show();
}catch(IOException e){
e.printStackTrace();
}
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Running", Toast.LENGTH_LONG).show();
SendMessage sender=new SendMessage();
sender.execute();
return super.onStartCommand(intent, flags, startId);
}
@Override
public IBinder onBind(Intent arg0) {
return null;
}
class SendMessage extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... params) {
try {
clientsocket = new Socket("192.168.237.1", 6666);
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
if(clientsocket!=null){
Toast.makeText(MyService.this, "Connected", Toast.LENGTH_LONG).show();
}else{
Toast.makeText(MyService.this, "Lost Connection", Toast.LENGTH_LONG).show();
}
super.onPostExecute(result);
}
}
}
MainActivity.java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void start(View v){
startService(new Intent(this,MyService.class));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class PrintMessage extends AsyncTask<Void, Void, Void>{
@Override
protected Void doInBackground(Void... arg0) {
return null;
}
}
@Override
protected void onDestroy() {
stopService(new Intent(this,MyService.class));
super.onDestroy();
}
}
Now I have some questions:
- Is it possible to create
PrintWriter
objects in MainActivity usingSocket
object (clientsocket
) of service? - Is it possible to pass values from MainActivity to service(i.e is IP address and port)?
- Is it possible to check socket connection in MainActivity(i.e
socket.isConnected
)?
Please help .