First of all: I am bigger in Android programming
I have created simple TCP Socket using Service.
The client connects to server when the button in MainActivity is triggered.
Now i want to create PrintWriter object in MainActivity using Socket object of Service.
I got to know it is possible to pass objects from Service to Activity using JSON.
I searched over Internet but couldn't get an idea how I can pass it.
Please give me simple code example to pass the object.
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 need a clear & complete code for both MyService.java (how to pass object I.e. in this case Socket object clientsocket )and MainActivity.java (how to retreive passed object I.e. clientsocket and use it to create PrintWriter object)