#android
#Android
Вопрос:
Я новичок в Android, и я немного понимаю, что такое websocket с (socket.io ), У меня есть вопрос и проблема, что происходит, так это то, что я хотел бы знать, как я могу использовать (socket.ввод-вывод) в фоновом режиме, чтобы иметь возможность отправлять сообщения вне приложения, у меня есть этот код, который я создал в своей MainActivity, и он отлично работает, он подключается к моему сокету.сервер ввода-вывода и отправляет данные GPS, но он работает только на переднем плане, когда я выхожу из приложения, он перестает отправлять сообщения, я надеюсь, вы сможете мне помочь, большое вам спасибо.
вот код..
private String mensaje;
private static final String TAG = "MainActivity";
private GoogleApiClient mGoogleApiClient;
private Location mLocation;
private LocationManager mLocationManager;
private LocationRequest mLocationRequest;
private com.google.android.gms.location.LocationListener listener;
private long UPDATE_INTERVAL = 2 * 200; /* 10 secs */
private long FASTEST_INTERVAL = 1000; /* 2 sec */
private LocationManager locationManager;
///// SOCKET.IO /////////
public static String uniqueId;
private String Username = "ale";
private Boolean hasConnection = false;
private int time = 2;
private boolean startTyping = false;
private Socket mSocket;
{
try {
mSocket = IO.socket("https://stbuses.herokuapp.com/");
} catch (URISyntaxException e) {}
}
@SuppressLint("HandlerLeak")
Handler handler2=new Handler(){
@Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
if(time == 0){
setTitle("SocketIO");
Log.i(TAG, "handleMessage: typing stopped time is " time);
startTyping = false;
time = 2;
}
}
};
///////////////////////////////////////////
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView= (ListView) findViewById(R.id.listamensajes);
editText= (EditText) findViewById(R.id.editexmensaje);
textView= (TextView) findViewById(R.id.enviar);
//////////// SOCKET.IO :::::::::::::::::
uniqueId = UUID.randomUUID().toString();
if(savedInstanceState != null){
hasConnection = savedInstanceState.getBoolean("hasConnection");
}
if(hasConnection){
}else {
mSocket.connect();
mSocket.on("connect user", onNewUser);
JSONObject userId = new JSONObject();
try {
userId.put("username", Username " Connected");
mSocket.emit("connect user", userId);
} catch (JSONException e) {
e.printStackTrace();
}
}
hasConnection = true;
/////////////////////////////
mensajeAdapter = new MensajeAdapter();
listView.setAdapter(mensajeAdapter);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationManager = (LocationManager)this.getSystemService(Context.LOCATION_SERVICE);
}
/////////// SOCKET.IO ::::::::::::::::::::::::::
Emitter.Listener onNewUser = new Emitter.Listener() {
@Override
public void call(final Object... args) {
runOnUiThread(new Runnable() {
@Override
public void run() {
int length = args.length;
if(length == 0){
return;
}
//Here i'm getting weird error..................///////run :1 and run: 0
String username =args[0].toString();
try {
JSONObject object = new JSONObject(username);
username = object.getString("username");
} catch (JSONException e) {
e.printStackTrace();
}
Toast.makeText(MainActivity.this, username, Toast.LENGTH_SHORT).show();
}
});
}
};
///////////////////////////
@Override
public void onConnected(@Nullable Bundle bundle) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED amp;amp; ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
startLocationUpdates();
mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
if(mLocation == null){
startLocationUpdates();
}
if (mLocation != null) {
Toast.makeText(MainActivity.this, "bienvenido", Toast.LENGTH_SHORT).show();
} else {
//Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
}
}
@Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " connectionResult.getErrorCode());
}
@Override
protected void onStart() {
super.onStart();
if (mGoogleApiClient != null) {
mGoogleApiClient.connect();
}
}
@Override
public void onLocationChanged(Location location) {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("HH:mm:ss");
String currentDateandTime = simpleDateFormat.format(new Date());
String msg =
"linea2" "," "16" ","
Double.toString(location.getLatitude()) ","
Double.toString(location.getLongitude());
String message = msg;
JSONObject jsonObject2 = new JSONObject();
try {
jsonObject2.put("message", message);
jsonObject2.put("username", Username);
jsonObject2.put("uniqueId", uniqueId);
} catch (JSONException e) {
e.printStackTrace();
}
mSocket.emit("chat message", jsonObject2);
Toast.makeText(MainActivity.this, msg, Toast.LENGTH_SHORT).show();
if (!msg.isEmpty())
{
//webSocket.send(msg);
//mSocket.emit("chat message", msg);
editText.setText("");
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("mensaje",msg " " currentDateandTime);
jsonObject.put("byServer",false);
mensajeAdapter.addlista(jsonObject);
}catch (JSONException e)
{
e.printStackTrace();
}
}
}
protected void startLocationUpdates() {
// Create the location request
mLocationRequest = LocationRequest.create()
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
.setInterval(UPDATE_INTERVAL)
.setFastestInterval(FASTEST_INTERVAL);
// Request location updates
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED amp;amp; ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient,
mLocationRequest, this);
Log.d("reque", "--->>>>");
}