Converting my Background Service to Android Oreo 8.0 Compatible - android

I have a service in my App which handles number of things. Sometimes when device is idle, the app crashes. And I know about the new Android 8.0 guidelines but I am not sure If I should convert my service to JobScheduler or take any other correct way. I can use some suggestions on which will be the best way to convert this service. Here is the code
HERE IS THE SERVICE :
public class ConnectionHolderService extends Service {
private static final String LOG_TAG = ConnectionHolderService.class.getSimpleName();
private SensorManager mSensorManager;
private static ConnectionHolderService instance = null;
public static ConnectionHolderService getInstanceIfRunningOrNull() {
return instance;
}
private class IncomingHandler extends Handler {
#Override
public void handleMessage(Message msg) {
//some code
}
}
private Messenger mMessenger = new Messenger(new IncomingHandler());
public ConnectionHolderService() {
}
#Override
public void onCreate() {
super.onCreate();
instance = this;
mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(final Context context, Intent intent) {
//some code
}
#Override
public IBinder onBind(Intent intent) {
return mMessenger.getBinder();
}
private void startListeningForShake() {
mShakeEnabled = true;
startServiceToAvoidStoppingWhenNoClientBound(ACTION_STOP_SHAKE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.CUPCAKE) {
mSensorManager.registerListener(mSensorListener,
mSensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
SensorManager.SENSOR_DELAY_UI);
}
}
private void startServiceToAvoidStoppingWhenNoClientBound(String action) {
registerReceiver(mReceiver, new IntentFilter(action));
startService(new Intent(this, ConnectionHolderService.class));
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
lock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, ":Doze lock");
if (!lock.isHeld()) {
lock.acquire();
}
// When the Shake is active, we should not stop when UI unbinds from this service
startNotification();
}
private Notification getShakeServiceForegroundNotification() {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
if (mShakeEnabled) {
notificationBuilder.addAction(0, getString(R.string.shake_turn_off),
PendingIntent.getBroadcast(this,
REQ_CODE_STAY_ON,
new Intent(ACTION_STOP_SHAKE),
PendingIntent.FLAG_UPDATE_CURRENT));
}
if (mPollingEnabled) {
// notificationBuilder.addAction(0, getString(R.string.stop_smart_home_integration),
// PendingIntent.getBroadcast(this,
// REQ_CODE_STAY_ON,
// new Intent(ACTION_STOP_POLLING_SQS),
// PendingIntent.FLAG_UPDATE_CURRENT));
}
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
notificationBuilder
.setSmallIcon(R.drawable.logo)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setUsesChronometer(true)
.setContentIntent(PendingIntent.getActivity(this, REQ_CODE_STAY_ON, intent, PendingIntent.FLAG_UPDATE_CURRENT))
.setContentTitle(getString(R.string.title_notification_running_background))
.setContentText(getString(R.string.description_running_background));
return notificationBuilder.build();
}
private void stopIfNeeded() {
if (!mShakeEnabled && !mPollingEnabled) {
try {
unregisterReceiver(mReceiver);
} catch (Exception e) {
// It can be IllegalStateException
}
stopNotification();
stopSelf();
if (lock != null && lock.isHeld()) {
lock.release();
}
}
}
public void startNotification() {
if (SqsPollManager.sharedInstance().isConnectInBackground() && !MyApp.sharedInstance().isAppInForeground()) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
startForeground(ID_SHAKE_SERVICE, getShakeServiceForegroundNotification());
}
}
}
public void stopNotification() {
mNotificationManager.cancel(ID_SHAKE_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
stopForeground(true);
}
}
#Override
public void onDestroy() {
super.onDestroy();
mReceiver = null;
Log.i(LOG_TAG, "onDestroy");
mMessenger = null;
mSensorListener = null;
instance = null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
Log.i(LOG_TAG, "onTaskRemoved! Stopping ConnectionHolderService");
try {
unregisterReceiver(mReceiver);
} catch (Exception e) {
}
stopNotification();
stopSelf();
if (lock != null && lock.isHeld()) {
lock.release();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ECLAIR) {
stopForeground(true);
}
stopSelf();
}
}
HERE IS MY APP CLASS:
public class MyApp {
#Override
public void onCreate() {
super.onCreate();
sendMessageToConnectionHolderService("SomeMessage");
}
public void sendMessageToConnectionHolderService(final int what) {
bindService(new Intent(this, ConnectionHolderService.class), new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
Log.i(LOG_TAG, "ConnectionHolderService connected!");
Messenger messenger = new Messenger(service);
Message msg = new Message();
msg.what = what;
try {
messenger.send(msg);
Log.i(LOG_TAG, "Message " + what + " has been sent to the service!");
} catch (RemoteException e) {
Log.e(LOG_TAG, "Error sending message " + msg.what + " to ConnectionHolderService", e);
}
final ServiceConnection conn = this;
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
unbindService(conn);
}
}, 1000);
}
#Override
public void onServiceDisconnected(ComponentName name) {
Log.i(LOG_TAG, "ConnectionHolderService disconnected!");
}
}, Context.BIND_AUTO_CREATE);
}
private Runnable mStartNotificationRunnable = new Runnable() {
#Override
public void run() {
if (SqsPollManager.sharedInstance().isPollingEnabled()
&& SqsPollManager.sharedInstance().isConnectInBackground()
&& !isAppInForeground()) {
if (null != ConnectionHolderService.getInstanceIfRunningOrNull()) {
ConnectionHolderService.getInstanceIfRunningOrNull().startNotification();
}
}
}
};
private Runnable mStopNotificationRunnable = new Runnable() {
#Override
public void run() {
if (null != ConnectionHolderService.getInstanceIfRunningOrNull()) {
ConnectionHolderService.getInstanceIfRunningOrNull().stopNotification();
}
}
};
}
AndroidManifest :
<service
android:name=".ConnectionHolderService"
android:enabled="true"
android:exported="false" />

You should consider using WorkManager. There are a lot of resources on how to use it, including samples, code-labs and blogs.
And if you are interested in JobScheduler in particular because of the Android 8.0 guidelines, I wrote a blog post that provides insights.

Related

Android service not working with bindService()

Actually I want to do speech to text continuously in the background so actually I am using the solution which is given in the below link but i m not getting how can i implement it.
link
I have done this so far but still my service is not running and i am not getting any output
So I think that i have done something wrong in its implementation.Please help me and correct my code in order to run service and get my output
This is my mainactivity.java
public class MainActivity extends AppCompatActivity {
private int mBindFlag ;
private Messenger mServiceMessenger ;
private Button btStartService;
private TextView tvText;
#Override
protected void onStart() {
super.onStart();
Log.d("check", "onStart: ");
bindService(new Intent(getApplicationContext(), MyService.class), mServiceConnection, mBindFlag);
}
#Override
protected void onStop() {
super.onStop();
if (mServiceMessenger != null) {
unbindService(mServiceConnection);
mServiceMessenger = null;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent service = new Intent(this, MyService.class);
this.startService(service);
mBindFlag = Context.BIND_ABOVE_CLIENT;
Log.d("check", "onCreate: "+mBindFlag);
btStartService = (Button) findViewById(R.id.btStartService);
tvText = (TextView) findViewById(R.id.tvText);
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {
Manifest.permission.RECORD_AUDIO
};
if (!hasPermissions(this, PERMISSIONS)) {
ActivityCompat.requestPermissions(this, PERMISSIONS, PERMISSION_ALL);
}
}
public static boolean hasPermissions(Context context, String... permissions) {
if (context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
private final ServiceConnection mServiceConnection = new ServiceConnection()
{
#Override
public void onServiceConnected(ComponentName name, IBinder service)
{
if (DEBUG) {
Log.d("check", "onServiceConnected");} //$NON-NLS-1$
mServiceMessenger = new Messenger(service);
Message msg = new Message();
msg.what = MyService.MSG_RECOGNIZER_START_LISTENING;
try
{
mServiceMessenger.send(msg);
}
catch (RemoteException e)
{
e.printStackTrace();
}
}
#Override
public void onServiceDisconnected(ComponentName name)
{
if (DEBUG) {Log.d("check", "onServiceDisconnected");} //$NON-NLS-1$
mServiceMessenger = null;
}
};
}
This is the code for my background service
public class MyService extends Service
{
protected AudioManager mAudioManager;
protected SpeechRecognizer mSpeechRecognizer;
protected Intent mSpeechRecognizerIntent;
protected final Messenger mServerMessenger = new Messenger(new IncomingHandler(this));
protected boolean mIsListening;
protected volatile boolean mIsCountDownOn;
static final int MSG_RECOGNIZER_START_LISTENING = 1;
static final int MSG_RECOGNIZER_CANCEL = 2;
#Override
public void onCreate()
{
super.onCreate();
mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
mSpeechRecognizer = SpeechRecognizer.createSpeechRecognizer(this);
mSpeechRecognizer.setRecognitionListener(new SpeechRecognitionListener());
mSpeechRecognizerIntent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
mSpeechRecognizerIntent.putExtra(RecognizerIntent.EXTRA_CALLING_PACKAGE,
this.getPackageName());
Log.d("check", "onCreate: "+"service");
}
protected static class IncomingHandler extends Handler
{
private WeakReference<MyService> mtarget;
IncomingHandler(MyService target)
{
mtarget = new WeakReference<MyService>(target);
}
#Override
public void handleMessage(Message msg)
{
final MyService target = mtarget.get();
switch (msg.what)
{
case MSG_RECOGNIZER_START_LISTENING:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
// turn off beep sound
target.mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, true);
}
if (!target.mIsListening)
{
target.mSpeechRecognizer.startListening(target.mSpeechRecognizerIntent);
target.mIsListening = true;
Log.d("check", "message start listening"); //$NON-NLS-1$
}
break;
case MSG_RECOGNIZER_CANCEL:
target.mSpeechRecognizer.cancel();
target.mIsListening = false;
Log.d("check", "message canceled recognizer"); //$NON-NLS-1$
break;
}
}
}
// Count down timer for Jelly Bean work around
protected CountDownTimer mNoSpeechCountDown = new CountDownTimer(5000, 5000)
{
#Override
public void onTick(long millisUntilFinished)
{
// TODO Auto-generated method stub
}
#Override
public void onFinish()
{
mIsCountDownOn = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_CANCEL);
try
{
mServerMessenger.send(message);
message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
}
};
#Override
public void onDestroy()
{
super.onDestroy();
if (mIsCountDownOn)
{
mNoSpeechCountDown.cancel();
}
if (mSpeechRecognizer != null)
{
mSpeechRecognizer.destroy();
}
}
protected class SpeechRecognitionListener implements RecognitionListener
{
private static final String TAG = "check";
#Override
public void onBeginningOfSpeech()
{
// speech input will be processed, so there is no need for count down anymore
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
//Log.d(TAG, "onBeginingOfSpeech"); //$NON-NLS-1$
}
#Override
public void onBufferReceived(byte[] buffer)
{
}
#Override
public void onEndOfSpeech()
{
//Log.d(TAG, "onEndOfSpeech"); //$NON-NLS-1$
}
#Override
public void onError(int error)
{
if (mIsCountDownOn)
{
mIsCountDownOn = false;
mNoSpeechCountDown.cancel();
}
mIsListening = false;
Message message = Message.obtain(null, MSG_RECOGNIZER_START_LISTENING);
try
{
mServerMessenger.send(message);
}
catch (RemoteException e)
{
}
//Log.d(TAG, "error = " + error); //$NON-NLS-1$
}
#Override
public void onEvent(int eventType, Bundle params)
{
}
#Override
public void onPartialResults(Bundle partialResults)
{
}
#Override
public void onReadyForSpeech(Bundle params)
{
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN)
{
mIsCountDownOn = true;
mNoSpeechCountDown.start();
mAudioManager.setStreamMute(AudioManager.STREAM_SYSTEM, false);
}
Log.d("check", "onReadyForSpeech");
}
#Override
public void onResults(Bundle results)
{
Toast.makeText(getApplicationContext(),results.toString(),Toast.LENGTH_LONG).show();
}
#Override
public void onRmsChanged(float rmsdB)
{
}
}
#Override
public IBinder onBind(Intent arg0) {
return mServerMessenger.getBinder();
}
}
I got my answer I have not enabled the service from the manifest

Flutter Unable to stop Activity

I have a Flutter Application and use Services on native Android.
Now when I Stop the Application by pressing the Switch-Apps Button my Application crashes with this error:
java.lang.RuntimeException: Unable to stop activity {de.karlw.time_management/de.karlw.time_management.MainActivity}: java.lang.IllegalArgumentException: Service not registered: de.karlw.time_management.MainActivity$1#f404173
E/AndroidRuntime( 8660): at android.app.ActivityThread.callActivityOnStop(ActivityThread.java:4861)
E/AndroidRuntime( 8660): at android.app.ActivityThread.performStopActivityInner(ActivityThread.java:4826)
E/AndroidRuntime( 8660): at android.app.ActivityThread.handleStopActivity(ActivityThread.java:4906)
E/AndroidRuntime( 8660): at android.app.servertransaction.StopActivityItem.execute(StopActivityItem.java:41)
E/AndroidRuntime( 8660): at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
This is my MainActivity:
public class MainActivity extends FlutterActivity implements MethodChannel.MethodCallHandler {
static final String TAG = "rest";
static final String CHANNEL = "de.karlw.time_management/service";
AppService appService;
boolean serviceConnected = false;
MethodChannel.Result keepResult = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GeneratedPluginRegistrant.registerWith(this);
new MethodChannel(getFlutterView(), CHANNEL).setMethodCallHandler(this::onMethodCall);
}
#Override
public void onMethodCall(MethodCall call, MethodChannel.Result result) {
try {
if (call.method.equals("connect")) {
connectToService();
keepResult = result;
} else if (serviceConnected) {
if (call.method.equals("start")) {
appService.startTimer();
result.success(null);
} else if (call.method.equals("stop")) {
appService.stopTimer();
result.success(null);
} else if (call.method.equals("getCurrentSeconds")) {
int sec = appService.getCurrentSeconds();
result.success(sec);
}
} else {
result.error(null, "App not connected to service", null);
}
} catch (Exception e) {
result.error(null, e.getMessage(), null);
}
}
private ServiceConnection connection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName className,
IBinder service) {
AppService.AppServiceBinder binder = (AppService.AppServiceBinder) service;
appService = binder.getService();
serviceConnected = true;
Log.i(TAG, "Service connected");
if (keepResult != null) {
keepResult.success(null);
keepResult = null;
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
serviceConnected = false;
Log.i(TAG, "Service disconnected");
}
};
private void connectToService() {
if (!serviceConnected) {
Intent service = new Intent(this, AppService.class);
startService(service);
getApplicationContext().bindService(service, connection, Context.BIND_AUTO_CREATE);
} else {
Log.i(TAG, "Service already connected");
if (keepResult != null) {
keepResult.success(null);
keepResult = null;
}
}
}
#Override
protected void onStop() {
super.onStop();
getApplicationContext().unbindService(connection);
serviceConnected = false;
}
}
I don't know why this happens. But I suggest the error is somehow the Service I use. But I have no clue why it happens.
Thanks for your help.

How to fix extreme battery drain with NotificationListener service

I need to check the current unread notifications for my app and I was using a notification listener service to do this. However this solution seems to continually check for notifications in the background causing huge battery drain issues, 23% background drain overnight to be precise. Is there a way for me to get the active notifications only when the phone is in a certain state (specifically the lock screen)
public class NotificationListener extends NotificationListenerService {
class CancelNotificationReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
String action;
if (intent != null && intent.getAction() != null) {
action = intent.getAction();
if (action.equals(ACTION_NLS_CONTROL)) {
String command = intent.getStringExtra("command");
if (TextUtils.equals(command, "cancel_last")) {
if (mCurrentNotifications != null && mCurrentNotificationsCounts >= 1) {
StatusBarNotification sbnn = getCurrentNotifications()[mCurrentNotificationsCounts - 1];
cancelNotification(sbnn.getPackageName(), sbnn.getTag(), sbnn.getId());
}
} else if (TextUtils.equals(command, "cancel_all")) {
cancelAllNotifications();
}
}
}
}
}
#Override
public void onCreate() {
super.onCreate();
logNLS("onCreate...");
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_NLS_CONTROL);
registerReceiver(mReceiver, filter);
mMonitorHandler.sendMessage(mMonitorHandler.obtainMessage(EVENT_UPDATE_CURRENT_NOS));
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
#Override
public IBinder onBind(Intent intent) {
// a.equals("b");
logNLS("onBind...");
return super.onBind(intent);
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
updateCurrentNotifications();
logNLS("onNotificationPosted...");
logNLS("have " + mCurrentNotificationsCounts + " active notifications");
mPostedNotification = sbn;
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
updateCurrentNotifications();
logNLS("removed...");
logNLS("have " + mCurrentNotificationsCounts + " active notifications");
mRemovedNotification = sbn;
}
private void updateCurrentNotifications() {
try {
StatusBarNotification[] activeNos = getActiveNotifications();
if (mCurrentNotifications.size() == 0) {
mCurrentNotifications.add(null);
}
mCurrentNotifications.set(0, activeNos);
mCurrentNotificationsCounts = activeNos.length;
} catch (Exception e) {
logNLS("Should not be here!!");
e.printStackTrace();
}
}
public static StatusBarNotification[] getCurrentNotifications() {
if (mCurrentNotifications.size() == 0) {
logNLS("mCurrentNotifications size is ZERO!!");
return null;
}
return mCurrentNotifications.get(0);
}
}

Check for new chat messages at background, Android

I'm developing a application when which every 4,5 seconds the client checks whether the server responds "OK".
It's even working, But if I turn on/off the internet sometimes it stops working, it is inconsistent and I need to check the messages accurately.
And service stop like in example I gave and it re-operate outside the specified range of seconds (4.5)
I'm developing a chat, and I need to know this precisely, I need to be professional.
Start.java
public class Start extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
Intent serviceIntent = new Intent(getBaseContext(), BackExec.class);
getBaseContext().startService(serviceIntent);
}
#Override
protected void onResume()
{
super.onResume();
Intent serviceIntent = new Intent(getApplicationContext(), BackExec.class);
startService(serviceIntent);
}}
BackExec.java
public class BackExec extends Service {
static Timer t;
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
String r = getData();
if(r != null){
if(r.equals("OK")){
NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
b.setSmallIcon(R.drawable.ic_ex);
b.setContentText("YOU HAVE NOTIFICATONS, CLICK.");
b.setContentTitle("TITLE APP:");
b.setOngoing(false);
b.setPriority(Notification.PRIORITY_MAX); //TALVEZ FUNCIONE
NotificationManager m = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
m.notify(0, b.build());
}
}
}
}, 1, 4500);
}
public int onStartCommand(Intent intent, int flags, int startId) {
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
String r = getData();
if(r != null){
if(r.equals("OK")){
NotificationCompat.Builder b = new NotificationCompat.Builder(getApplicationContext());
b.setSmallIcon(R.drawable.ic_ex);
b.setContentText("YOU HAVE NOTIFICATONS, CLICK.");
b.setContentTitle("TITLE APP:");
b.setOngoing(false);
b.setPriority(Notification.PRIORITY_MAX); //TALVEZ FUNCIONE
NotificationManager m = (NotificationManager) getApplicationContext().getSystemService(NOTIFICATION_SERVICE);
m.notify(0, b.build());
}
}
}
}, 1, 4500);
return START_STICKY;
}
public static String getData(){
URL site = null;
try {
site = new URL("http://192.168.0.10:8080/example/server.php");
URLConnection urlConn = site.openConnection();
urlConn.setRequestProperty("Cookie", CookieManager.getInstance().getCookie("http://192.168.0.10:8080/example"));
urlConn.setDoOutput(true);
PrintStream enviarInfos = new PrintStream(urlConn.getOutputStream());
enviarInfos.print("pac=pac");
urlConn.getInputStream();
BufferedReader in = new BufferedReader(new InputStreamReader(urlConn.getInputStream()));
String inputLine;
String out = "";
while ((inputLine = in.readLine()) != null)
out = out + inputLine;
in.close();
return out;
} catch (MalformedURLException e) {
return null;
} catch (IOException e) {
return null;
}
}
public void onStart(Intent intent, int startId) { } // TO DO
public IBinder onUnBind(Intent arg0) {
return null;
}
public void onStop() {}
public void onPause() {}
#Override
public void onDestroy() {}
#Override
public void onLowMemory() {} }

how to call service from receiver

In my application I want to call service from Receiver.
This is my NotificationReceiver.java
public class NotificationReceiver extends BroadcastReceiver {
NotificationReceiver _this = this;
private static Context _context;
public static final String ACTION_REFRESH_SCHEDULE_ALARM = "com.example.receiver.ACTION_REFRESH_SCHEDULE_ALARM";
String SERVER_URL = "http://192.168.1.7:8080";
#Override
public void onReceive(final Context context, Intent intent) {
_context = context;
initClient();
SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(_context);
if (settings.getString("userId",null) != null){
gotNotification(new ClientListener(){
#Override
public void onSuccess(String response) {
try {
JSONObject object = new JSONObject(response);
System.out.println("Service object = "+ object);
} catch (JSONException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
}
#Override
public void onFail(int error) {
}
#Override
public void onCancel() {
}
},settings.getString("userId",null));
}
}
private void initClient(){
NotifierRestClient.init(SERVER_URL + "/api");
}
private void gotNotification (final ClientListener clientListener, final String uId) {
new Thread() {
#Override
public void run() {
try {
final String responseText = NotifierRestClient.getUserNotifications(uId,null);
if (clientListener != null) {
clientListener.onSuccess(responseText);
}
} catch (final Exception e) {
e.printStackTrace();
if (clientListener != null) {
clientListener.onFail(505);
}
}
}
}.start();
}
}
And this is my NotifiactionService.java
public class NotificationService extends Service {
private AlarmManager alarmManagerPositioning;
private PendingIntent pendingIntent;
#Override
public void onCreate() {
super.onCreate();
alarmManagerPositioning = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
final Intent intentToNotificate = new Intent(NotificationReceiver.ACTION_REFRESH_SCHEDULE_ALARM);
pendingIntent = PendingIntent.getBroadcast(this, 0, intentToNotificate, 0);
}
#Override
public void onStart(Intent intent, int startId) {
try {
long notificationInterval = 5002;
alarmManagerPositioning.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), notificationInterval, pendingIntent);
} catch (NumberFormatException e) {
Toast.makeText(this, "error running services: " + e.getMessage(), Toast.LENGTH_SHORT).show();
} catch (Exception e) {
Toast.makeText(this, "error running services: " + e.getMessage(), Toast.LENGTH_SHORT).show();
}
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onDestroy() {
this.alarmManagerPositioning.cancel(pendingIntent);
}
}
My question is how to call NotificationService in NotificationReceiver and change interval? Any help will be useful Thanks
Start Service in your receiver using
Intent in = new Intent(context,NotificationService.class);
in.putExtra("interval",5001);
context.startService(in);
In your service code,
long notificationInterval = intent.getLongExtra("interval", defaultValue)
to get Data from your receiver, Please use onStartCommand(Intent intent, int flags, int startId), onStart has been deprecated.

Categories

Resources