Socket in android service

  • Replies:0
Maro Z
  • Forum posts: 1

May 9, 2015, 11:34:37 AM via Website

I need to make a service that connects to a server with Socket, and when it recieves certain string, it sends a notification.
This is what i tried to make:

package com.hackathon.homealert;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.PrintStream;
import java.net.Socket;

public class SmokeChecker extends Service {

Socket SOCK;
@override
public int onStartCommand(Intent intent, int flags, int startId){

String MESSAGE = "";

try {
PrintStream PS = new PrintStream(SOCK.getOutputStream());
PS.println("Hello from client: " + Build.MANUFACTURER + " " + Build.MODEL);

InputStreamReader IR = new InputStreamReader(SOCK.getInputStream());
BufferedReader BR = new BufferedReader(IR);

MESSAGE = BR.readLine();
}
catch (Exception e){
System.out.println(e.getMessage());
}

if(MESSAGE.equals("s")) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setContentText("Fire alert, smoke detected!")
.setContentTitle("Attention!");
NotificationManager manager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build()); //notifikacija
//omoguci stiskanje tipke "Call"
}
if(MESSAGE.equals("g")) {
NotificationCompat.Builder builder2 = new NotificationCompat.Builder(this)
.setContentText("Fire alert, gas detected!")
.setContentTitle("Attention!");
NotificationManager manager2 = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
manager2.notify(0, builder2.build()); //notifikacija
//omoguci stiskanje tipke "Call"
}
return START_STICKY;
}

@override
public IBinder onBind(Intent intent){
return null;
}

@override
public void onCreate(){
try {
Socket SOCK = new Socket("localhost", 7777);
}catch (Exception e){
System.out.println(e.getMessage());
}
super.onCreate();
}

@override
public void onDestroy(){
super.onDestroy();
Toast.makeText(this, "Lost connection to server.", Toast.LENGTH_LONG).show();
}
}

Is this right way to do it? I get an error with throws Exception part.
Or should I do it in onBind method?
I'm really new to both services and networking...

Reply