3

Tengo la siguiente duda, intento crear una app que cada tanto se conecte a Internet, verifique si hay alguna novedad y en caso de que la halla me dé una notificación, mi idea era usar un servicio, el cual inicia sin problema, al cerrar la aplicación sigue activo pero no hace nada, puse un timer para que cada tanto me dé una notificación para ver si funciona y no lo hace, probé con un Toast y tampoco, les dejo el código de mi servicio, si alguien me puede dar una mano se lo agradeceré enormemente.

import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.net.Uri;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;

import java.util.Timer;
import java.util.TimerTask;

import static android.content.ContentValues.TAG;


public class notifServise extends Service {
    TimerTask timerTask;
    NotificationManager notificationManager;
    int notification_id = 1234;
    int n=0;

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

    @Override
    public void onCreate() {
        notificationManager= (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Log.d("NTF S", "Servicio creado...");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("NTF S", "Servicio iniciado...");



        final NotificationCompat.Builder builder= new NotificationCompat.Builder(this)
                .setSmallIcon(android.R.drawable.ic_dialog_alert)
                .setContentTitle("titulo");

        Timer timer = new Timer();

        timerTask = new TimerTask() {
            @Override
            public void run() {
                Log.d("NTF S", "timer tic");
                notificationManager.cancel(notification_id);
                notificationManager.notify(notification_id,builder.build());
                n++;
            }
        };

        timer.scheduleAtFixedRate(timerTask, 10000, 10000);

        return START_NOT_STICKY;
    }


    @Override
    public void onDestroy() {
        Log.d("NTF S", "Servicio destruido...");
    }
}

1 respuesta 1

1

Aqui le dejo el codigo para ejecutar un servicio que actualiza las coordenadas. si la aplicacion esta abierta las coordenadas se muestran en un toast, si esta cerrada se actualizan las coordenadas en el icono de notificacion. Saludos.

Cree una nueva aplicación que contenga:

MainActivity.java

import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.location.Location;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.provider.Settings;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity implements
    SharedPreferences.OnSharedPreferenceChangeListener {
private static final String TAG = MainActivity.class.getSimpleName();

private static final int REQUEST_PERMISSIONS_REQUEST_CODE = 34;

private MyReceiver myReceiver;

private LocationUpdatesService mService = null;

private boolean mBound = false;

private Button mRequestLocationUpdatesButton;
private Button mRemoveLocationUpdatesButton;


private final ServiceConnection mServiceConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        LocationUpdatesService.LocalBinder binder = (LocationUpdatesService.LocalBinder) service;
        mService = binder.getService();
        mBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {
        mService = null;
        mBound = false;
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    myReceiver = new MyReceiver();
    setContentView(R.layout.activity_main);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setTitle(R.string.menuRegistros);

    // Check that the user hasn't revoked permissions by going to Settings.
    if (Utils.requestingLocationUpdates(this)) {
        if (!checkPermissions()) {
            requestPermissions();
        }
    }
}

@Override
protected void onStart() {
    super.onStart();
    PreferenceManager.getDefaultSharedPreferences(this)
            .registerOnSharedPreferenceChangeListener(this);

    mRequestLocationUpdatesButton = (Button) findViewById(R.id.btnSolicitud);
    mRemoveLocationUpdatesButton = (Button) findViewById(R.id.btnRemover);

    mRequestLocationUpdatesButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if (!checkPermissions()) {
                requestPermissions();
            } else {
                mService.requestLocationUpdates();
            }
        }
    });

    mRemoveLocationUpdatesButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mService.removeLocationUpdates();
        }
    });


    setButtonsState(Utils.requestingLocationUpdates(this));

    bindService(new Intent(this, LocationUpdatesService.class), mServiceConnection,
            Context.BIND_AUTO_CREATE);
}

@Override
protected void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(this).registerReceiver(myReceiver,
            new IntentFilter(LocationUpdatesService.ACTION_BROADCAST));
}

@Override
protected void onPause() {
    LocalBroadcastManager.getInstance(this).unregisterReceiver(myReceiver);
    super.onPause();
}

@Override
protected void onStop() {
    if (mBound) {
        // Unbind from the service. This signals to the service that this activity is no longer
        // in the foreground, and the service can respond by promoting itself to a foreground
        // service.
        unbindService(mServiceConnection);
        mBound = false;
    }
    PreferenceManager.getDefaultSharedPreferences(this)
            .unregisterOnSharedPreferenceChangeListener(this);
    super.onStop();
}

/**
 * Returns the current state of the permissions needed.
 */
private boolean checkPermissions() {
    return  PackageManager.PERMISSION_GRANTED == ActivityCompat.checkSelfPermission(this,
            Manifest.permission.ACCESS_FINE_LOCATION);
}

private void requestPermissions() {
    boolean shouldProvideRationale =
            ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.ACCESS_FINE_LOCATION);

    // Provide an additional rationale to the user. This would happen if the user denied the
    // request previously, but didn't check the "Don't ask again" checkbox.
    if (shouldProvideRationale) {
        Log.i(TAG, "Displaying permission rationale to provide additional context.");
        Snackbar.make(
                findViewById(R.id.activity_main),
                R.string.permission_rationale,
                Snackbar.LENGTH_INDEFINITE)
                .setAction(R.string.ok, new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        // Request permission
                        ActivityCompat.requestPermissions(MainActivity.this,
                                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                REQUEST_PERMISSIONS_REQUEST_CODE);
                    }
                })
                .show();
    } else {
        Log.i(TAG, "Requesting permission");
        // Request permission. It's possible this can be auto answered if device policy
        // sets the permission in a given state or the user denied the permission
        // previously and checked "Never ask again".
        ActivityCompat.requestPermissions(MainActivity.this,
                new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                REQUEST_PERMISSIONS_REQUEST_CODE);
    }
}

/**
 * Callback received when a permissions request has been completed.
 */
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    Log.i(TAG, "onRequestPermissionResult");
    if (requestCode == REQUEST_PERMISSIONS_REQUEST_CODE) {
        if (grantResults.length <= 0) {
            // If user interaction was interrupted, the permission request is cancelled and you
            // receive empty arrays.
            Log.i(TAG, "User interaction was cancelled.");
        } else if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            // Permission was granted.
            mService.requestLocationUpdates();
        } else {
            // Permission denied.
            setButtonsState(false);
            Snackbar.make(
                    findViewById(R.id.activity_main),
                    R.string.permission_denied_explanation,
                    Snackbar.LENGTH_INDEFINITE)
                    .setAction(R.string.settings, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            // Build intent that displays the App settings screen.
                            Intent intent = new Intent();
                            intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
                            Uri uri = Uri.fromParts("package", BuildConfig.APPLICATION_ID, null);
                            intent.setData(uri);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            startActivity(intent);
                        }
                    })
                    .show();
        }
    }
}

/**
 * Receiver for broadcasts sent by {@link LocationUpdatesService}.
 */
private class MyReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Location location = intent.getParcelableExtra(LocationUpdatesService.EXTRA_LOCATION);
        if (location != null) {
            Toast.makeText(MainActivity.this, Utils.getLocationText(location),Toast.LENGTH_SHORT).show();
        }
    }
}

@Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String s) {
    // Update the buttons state depending on whether location updates are being requested.
    if (s.equals(Utils.KEY_REQUESTING_LOCATION_UPDATES)) {
        setButtonsState(sharedPreferences.getBoolean(Utils.KEY_REQUESTING_LOCATION_UPDATES,false));
    }
}

private void setButtonsState(boolean requestingLocationUpdates) {
    if (requestingLocationUpdates) {
        mRequestLocationUpdatesButton.setEnabled(false);
        mRemoveLocationUpdatesButton.setEnabled(true);
    } else {
        mRequestLocationUpdatesButton.setEnabled(true);
        mRemoveLocationUpdatesButton.setEnabled(false);
    }
}



@Override
public void onBackPressed() {
    finish();
}

}

Cree un servicio llamado MiServicio

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.location.Location;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;

import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;


 public class MiServicio extends Service implements GoogleApiClient.ConnectionCallbacks,
    GoogleApiClient.OnConnectionFailedListener, LocationListener {

private static final String PACKAGE_NAME = "com.example.fragmants.locationupdatesforegroundservice";

private static final String TAG = MiServicio.class.getSimpleName();

static final String ACTION_BROADCAST = PACKAGE_NAME + ".broadcast";

static final String EXTRA_LOCATION = PACKAGE_NAME + ".location";
private static final String EXTRA_STARTED_FROM_NOTIFICATION = PACKAGE_NAME + ".started_from_notification";

private final IBinder mBinder = new LocalBinder();


private static final long UPDATE_INTERVAL_IN_MILLISECONDS = 10000;


private static final long FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS = UPDATE_INTERVAL_IN_MILLISECONDS / 2;


private static final int NOTIFICATION_ID = 12345678;


private boolean mChangingConfiguration = false;

private NotificationManager mNotificationManager;


private GoogleApiClient mGoogleApiClient;


private LocationRequest mLocationRequest;

private Handler mServiceHandler;


private Location mLocation;

public MiServicio() {
}

@Override
public void onCreate() {
    mGoogleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    mGoogleApiClient.connect();
    createLocationRequest();

    HandlerThread handlerThread = new HandlerThread(TAG);
    handlerThread.start();
    mServiceHandler = new Handler(handlerThread.getLooper());
    mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.i(TAG, "Service started");
    boolean startedFromNotification = intent.getBooleanExtra(EXTRA_STARTED_FROM_NOTIFICATION,
            false);


    if (startedFromNotification) {
        removeLocationUpdates();
        stopSelf();
    }

    return START_NOT_STICKY;
}

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    mChangingConfiguration = true;
}

@Override
public IBinder onBind(Intent intent) {
      Log.i(TAG, "in onBind()");
    stopForeground(true);
    mChangingConfiguration = false;
    return mBinder;
}

@Override
public void onRebind(Intent intent) {
    Log.i(TAG, "in onRebind()");
    stopForeground(true);
    mChangingConfiguration = false;
    super.onRebind(intent);
}

@Override
public boolean onUnbind(Intent intent) {
    Log.i(TAG, "Last client unbound from service");
   if (!mChangingConfiguration && Utils.requestingLocationUpdates(this)) {
        Log.i(TAG, "Starting foreground service");

        startForeground(NOTIFICATION_ID, getNotification());
    }
    return true;
}

@Override
public void onDestroy() {
    mServiceHandler.removeCallbacksAndMessages(null);
    mGoogleApiClient.disconnect();
}


public void requestLocationUpdates() {
    Log.i(TAG, "Requesting location updates");
    Utils.setRequestingLocationUpdates(this, true);
    startService(new Intent(getApplicationContext(), MiServicio.class));
    try {
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, MiServicio.this);
    } catch (SecurityException unlikely) {
        Utils.setRequestingLocationUpdates(this, false);
        Log.e(TAG, "Lost location permission. Could not request updates. " + unlikely);
    }
}


public void removeLocationUpdates() {
    Log.i(TAG, "Removing location updates");
    try {
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, MiServicio.this);
        Utils.setRequestingLocationUpdates(this, false);
        stopSelf();
    } catch (SecurityException unlikely) {
        Utils.setRequestingLocationUpdates(this, true);
        Log.e(TAG, "Lost location permission. Could not remove updates. " + unlikely);
    }
}


private Notification getNotification() {
    Intent intent = new Intent(this, MiServicio.class);

    CharSequence text = Utils.getLocationText(mLocation);

    intent.putExtra(EXTRA_STARTED_FROM_NOTIFICATION, true);

    PendingIntent servicePendingIntent = PendingIntent.getService(this, 0, intent,
            PendingIntent.FLAG_UPDATE_CURRENT);

    PendingIntent activityPendingIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, MainActivity.class), 0);

    return new NotificationCompat.Builder(this)
            .addAction(R.drawable.gps, getString(R.string.launch_activity),
                    activityPendingIntent)
            .addAction(R.drawable.gps, getString(R.string.remove_location_updates),
                    servicePendingIntent)
            .setContentText(text)
            .setContentTitle(Utils.getLocationTitle(this))
            .setOngoing(true)
            .setPriority(Notification.PRIORITY_HIGH)
            .setSmallIcon(R.drawable.gps)
            .setTicker(text)
            .setWhen(System.currentTimeMillis()).build();
}

@Override
public void onConnected(@Nullable Bundle bundle) {
    Log.i(TAG, "GoogleApiClient connected");
    try {
        mLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
    } catch (SecurityException unlikely) {
        Log.e(TAG, "Lost location permission." + unlikely);
    }
}

@Override
public void onConnectionSuspended(int i) {
    Log.e(TAG, "GoogleApiClient connection suspended.");
}

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    Log.e(TAG, "GoogleApiClient connection failed.");
}

@Override
public void onLocationChanged(Location location) {
    Log.i(TAG, "New location: " + location);

    mLocation = location;

    Intent intent = new Intent(ACTION_BROADCAST);
    intent.putExtra(EXTRA_LOCATION, location);
    LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);


    if (serviceIsRunningInForeground(this)) {
        mNotificationManager.notify(NOTIFICATION_ID, getNotification());
    }
}


private void createLocationRequest() {
    mLocationRequest = new LocationRequest();
    mLocationRequest.setInterval(UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setFastestInterval(FASTEST_UPDATE_INTERVAL_IN_MILLISECONDS);
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}


public class LocalBinder extends Binder {
    MiServicio getService() {
        return MiServicio.this;
    }
}


public boolean serviceIsRunningInForeground(Context context) {
    ActivityManager manager = (ActivityManager) context.getSystemService(
            Context.ACTIVITY_SERVICE);
    for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(
            Integer.MAX_VALUE)) {
        if (getClass().getName().equals(service.service.getClassName())) {
            if (service.foreground) {
                return true;
            }
        }
    }
    return false;
}

}

Cree una clase Utils.java

    import android.content.Context;
    import android.location.Location;
    import android.preference.PreferenceManager;

    import java.text.DateFormat;
    import java.util.Date;

 class Utils {

static final String KEY_REQUESTING_LOCATION_UPDATES = "requesting_locaction_updates";


static boolean requestingLocationUpdates(Context context) {
    return PreferenceManager.getDefaultSharedPreferences(context)
            .getBoolean(KEY_REQUESTING_LOCATION_UPDATES, false);
}


static void setRequestingLocationUpdates(Context context, boolean requestingLocationUpdates) {
    PreferenceManager.getDefaultSharedPreferences(context)
            .edit()
            .putBoolean(KEY_REQUESTING_LOCATION_UPDATES, requestingLocationUpdates)
            .apply();
}


static String getLocationText(Location location) {
    return location == null ? "Locacion desconocida" :
            "(" + location.getLatitude() + ", " + location.getLongitude() + ")";
}

static String getLocationTitle(Context context) {
    return context.getString(R.string.location_updated,
            DateFormat.getDateTimeInstance().format(new Date()));
}

}

Agregue a strings.xml

<resources>
    <string name="app_name">My Application</string>
    <string name="location_updated">Location Updated: %1$s</string>
    <string name="launch_activity">Actividad de lanzamiento</string>
    <string name="location_unknown">Ubicación desconocida</string>
    <string name="location_updates_label">Actualizaciones de la ubicación</string>
    <string name="ok">OK</string>
    <string name="request_location_updates">Solicitar actualizaciones de ubicación</string>
    <string name="remove_location_updates">Eliminar actualizaciones de ubicación</string>
    <string name="menuRegistros">Menu Registros</string>
    <string name="permission_rationale">El permiso de ubicación es necesario para la funcionalidad básica</string>
    <string name="permission_denied_explanation">El permiso fue denegado, pero es necesario
    Funcionalidad.</string>
    <string name="settings">Settings</string>

</resources>

Agregue a build.gradle(Module:app)

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '25.0.1'
    defaultConfig {
        applicationId "com.example.gustavo.myapplication"
        minSdkVersion 15
        versionCode 1
        versionName "1.0"
         testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'),  'proguard-rules.pro'
    }
}
productFlavors {
}
 }

 dependencies {
     compile 'com.android.support:gridlayout-v7:25.1.0'
     compile 'com.android.support:appcompat-v7:25.1.0'
     compile 'com.android.support:palette-v7:25.1.0'
     compile 'com.android.support:design:25.1.0'
     compile 'org.jetbrains:annotations-java5:15.0'
     compile 'com.google.android.gms:play-services-gcm:10.2.4'
     compile 'com.google.android.gms:play-services-location:10.2.4'
     compile 'com.google.android.gms:play-services-maps:10.2.4'
  }

En el archivo Manifest agregue lo siguiente:

<?xml version="1.0" encoding="utf-8"?>
 <manifest xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.example.gustavo.myapplication" >


      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
      <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

     <application
         android:allowBackup="true"
         android:icon="@mipmap/ic_launcher"
         android:label="@string/app_name"
         android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
         android:theme="@style/AppTheme" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <service
        android:name=".MiServicio"
        android:enabled="true"
        android:exported="true" />


</application>



 </manifest>

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.