Notificaciones con soket

21 views
Skip to first unread message

Christian Gurdian

unread,
Nov 21, 2020, 3:37:05 AM11/21/20
to desarrolladores-android
Hola estoy usando soket con android Java, es mi primera ves utilizándola y estoy buscando que me llegue notificaciones en tiempo real, es por eso que cree un servicio usando lo siguiente

public class ServicioPermanente extends BroadcastReceiver {

private FirebaseAuth mAuth;
private String CHANNEL_ID = "0";
private int notificacionID = 48654;

private Thread thread2;
private boolean startTyping = false;
private int time = 2;

public static String uniqueId;
private String Username, Imagen, proveedorSucursal = "0", nombre, precio;

private String TAG = "MyBroadcastReceiver";

private NotificationCompat.Builder builder;

private Socket mSocket;
{
try {
mSocket = IO.socket("http://127.0.0.1:5700");
} catch (URISyntaxException e) {}
}

@SuppressLint("HandlerLeak")
Handler handler2=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Log.i(TAG, "handleMessage: typing stopped " + startTyping);
if(time == 0){
Log.i(TAG, "handleMessage: typing stopped time is " + time);
startTyping = false;
time = 2;
}
}
};

public ServicioPermanente() {
super();
mAuth = FirebaseAuth.getInstance();
uniqueId = mAuth.getUid();
Username = mAuth.getCurrentUser().getEmail();
Log.i(TAG, "onCreate: " + uniqueId);
}

private void ejecutarTocket(Context context){
if(!mSocket.connected()){
mSocket.connect();
Log.i(TAG, "onCreate: mSocket.connect()");
mSocket.on("new product", new Emitter.Listener() {
@Override
public void call(Object... args) {
builder.setContentTitle(context.getString(R.string.TileNotProduc))
.setContentText(context.getString(R.string.TileNotProducDesc))
.setStyle(new NotificationCompat.BigTextStyle().bigText(context.getString(R.string.TileNotProducDesc)));

NotificationManager nm = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
nm.notify(notificacionID,builder.build());
}
});
mSocket.on("new promotion", new Emitter.Listener() {
@Override
public void call(Object... args) {
builder.setContentTitle(context.getString(R.string.TileNotPromon))
.setContentText(context.getString(R.string.TileNotPromonDesc))
.setStyle(new NotificationCompat.BigTextStyle().bigText(context.getString(R.string.TileNotPromonDesc)));

NotificationManager nm = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
nm.notify(notificacionID,builder.build());
}
});
mSocket.on("new message", new Emitter.Listener() {
@Override
public void call(Object... args) {
Log.i(TAG, "run: onNotificationMens");
JSONObject data = (JSONObject) args[0];
String username, message, id, room = ""; int IDProveedor = 0;

try {
room = data.getString("room");
} catch (JSONException e) {
e.printStackTrace();
}

if(room == mAuth.getCurrentUser().getEmail()){
builder.setContentTitle(context.getString(R.string.TileNotMensaj))
.setContentText(context.getString(R.string.TileNotMensajDesc))
.setStyle(new NotificationCompat.BigTextStyle().bigText(context.getString(R.string.TileNotPromonDesc)));

NotificationManager nm = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
nm.notify(notificacionID,builder.build());
}
else{
Boolean valor = false;

if(valor){
builder.setContentTitle(context.getString(R.string.TileNotMensaj_admon))
.setContentText(context.getString(R.string.TileNotMensajDesc_admon))
.setStyle(new NotificationCompat.BigTextStyle().bigText(context.getString(R.string.TileNotPromonDesc)));

NotificationManager nm = (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);
nm.notify(notificacionID,builder.build());
}

}
}
});
}
}

@Override
protected void finalize() throws Throwable {
super.finalize();
mSocket.off("new product");
mSocket.off("new promotion");
mSocket.off("new message");
mSocket.disconnect();
}

@Override
public void onReceive(Context context, Intent intent) {

if(intent.ACTION_BOOT_COMPLETED.equals(intent.getAction())){
Toast.makeText(context, "ACTION_BOOT_COMPLETED BroadcastReceiver", Toast.LENGTH_SHORT).show();
context.startService(new Intent(context, SoketService.class));
}
if(ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())){
boolean noConetion = intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);

if(noConetion){
Toast.makeText(context, "CONNECTIVITY_ACTION BroadcastReceiver FALSE", Toast.LENGTH_SHORT).show();
context.stopService(new Intent(context, SoketService.class));
}else{
Toast.makeText(context, "CONNECTIVITY_ACTION BroadcastReceiver TRUE", Toast.LENGTH_SHORT).show();
context.startService(new Intent(context, SoketService.class));
}

}

if(intent.ACTION_INPUT_METHOD_CHANGED.equals(intent.getAction())){
Toast.makeText(context, "INPUT_METHOD_CHANGED BroadcastReceiver", Toast.LENGTH_SHORT).show();
}

}

}

Este código funciona pero solo cuando estoy dentro de la aplicación pero lo necesito cuando también esta fuera de la misma

David Faerman

unread,
Nov 21, 2020, 4:15:05 AM11/21/20
to desarrollad...@googlegroups.com
Sockets no es para eso....
deberías usar el servicio de push notifications de firebase... fijate que cuando la app esté distribuida no vas a saber la ip de cada uno y aparte alguno puede estar con datos en vez de wifi o en otra red...
pero suponiendo que tenga sentido hacerlo con sockets tenes que hacer un background service, un servicio que corra cuando la app esté o no ejecutandose. 
cuando digo hacer un servicio es Service no un broadcast receiver.... en todo caso el broadcast receiver lo podes usar para iniciar el servicio en boot o lo que sea.

--
Para participar es necesario que leas detenidamente las normas del grupo: https://goo.gl/xeTRQm
---
Has recibido este mensaje porque estás suscrito al grupo "desarrolladores-android" de Grupos de Google.
Para cancelar la suscripción a este grupo y dejar de recibir sus mensajes, envía un correo electrónico a desarrolladores-a...@googlegroups.com.
Para ver esta conversación en el sitio web, visita https://groups.google.com/d/msgid/desarrolladores-android/718af6af-a03b-41ca-a97c-01d19d236154n%40googlegroups.com.


--
 (\__/)
(='.'=)This is Bunny. Copy and paste bunny into your
(")_(")signature to help him gain world domination.
Reply all
Reply to author
Forward
0 new messages