How to get context for TimerTask in Service [duplicate] - android

This question already has answers here:
Get Context in a Service
(7 answers)
Closed 5 years ago.
I need to get ComplexPreferences within a Service
Code
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
sendRequestToServer();
}
private void sendRequestToServer() {
// How to get context here to initialize ctx ?
ComplexPreferences complexPreferences =
ComplexPreferences.getComplexPreferences( ctx , "App_Settings", 0);
}
How to do it?
Full code of class
public class gps_service extends Service {
private static final String TAG = "MyService";
private LocationListener listener;
private LocationManager locationManager;
private Timer timer = new Timer();
private DLocation dLocation;
private final Object lock = new Object();
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
sendRequestToServer();
}
private void sendRequestToServer() {
synchronized (lock) {
try{
if(dLocation == null) return;
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences( context , "App_Settings", 0);
AppSettings appSettings = complexPreferences.getObject("App_Settings", AppSettings.class);
if(appSettings != null)
{
}
DLocation tempDL = dLocation;
LocationItem locationItem = new LocationItem();
locationItem.DeviceID = tempDL.DeviceID;
locationItem.Latitude = tempDL.Latitude;
locationItem.Longitude = tempDL.Longitude;
locationItem.TimeOfRequest = tempDL.TimeOfRequest;
Gson gson = new Gson();
String requestObject = gson.toJson(locationItem);
String url = "http://XXXXXXX";
makeRequest(url, requestObject);
}
catch (Exception ex)
{
}
}
}
}, 0, 1*60*1000); //1 Minutes

Try this
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences( YourService.this , "App_Settings", 0);
Or this
Context context = this;
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences( context, "App_Settings", 0);
EDIT
public class gps_service extends Service {
private static final String TAG = "MyService";
private LocationListener listener;
private LocationManager locationManager;
private Timer timer = new Timer();
private DLocation dLocation;
private final Object lock = new Object();
Context context ;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
context = this;
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
sendRequestToServer();
}
private void sendRequestToServer() {
synchronized (lock) {
try{
if(dLocation == null) return;
ComplexPreferences complexPreferences = ComplexPreferences.getComplexPreferences( context , "App_Settings", 0);
AppSettings appSettings = complexPreferences.getObject("App_Settings", AppSettings.class);
if(appSettings != null)
{
}
DLocation tempDL = dLocation;
LocationItem locationItem = new LocationItem();
locationItem.DeviceID = tempDL.DeviceID;
locationItem.Latitude = tempDL.Latitude;
locationItem.Longitude = tempDL.Longitude;
locationItem.TimeOfRequest = tempDL.TimeOfRequest;
Gson gson = new Gson();
String requestObject = gson.toJson(locationItem);
String url = "http://XXXXXXX";
makeRequest(url, requestObject);
}
catch (Exception ex)
{
}
}
}
}, 0, 1*60*1000); //1 Minutes

Related

i want to call an api function continously 24*7 with the timer of 1 minute in background , it works fine in intial time ,after 15 minutes it stops

please help i am new to Android , I want to call this API background continuously 24*7(all time),
but this code runs few minutes and then it stops working, is there any other solution to work this code continuously(non-stop) background with timer?. here I'm using foreground service but no use.
SmsForegroundService.class
public class SmsForegroundService extends Service{
Context mContext;
private BroadcastReceiver receiver;
private static final String SENT = "SMS_SENT";
private static final String TAG = "TEST123";
private APIInterface apiInterface;
public static Handler handler;
public static Runnable myRunnable;
private SMSReceiver smsReceiver;
private AppPreferences appPreferences;
private IntentFilter mIntentFilter;
String responseTimer = "1";
private int j = 1 ;
private Runnable runnable;
private static final String TAGs = SmsForegroundService.class.getSimpleName();
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate: ");
handler = new Handler();
appPreferences = new AppPreferences(this);
apiInterface = APIClient.getClient().create(APIInterface.class);
handler = new Handler();
runnable = new Runnable() {
public void run() {
Toast.makeText(getApplicationContext(), "Service is still running",
Toast.LENGTH_LONG).show();
callKeepAliveNotifyApi();
}
};
handler.postDelayed(runnable, 0);
}
#Override
public void onDestroy() {
Log.d(TAG, "onDestroy: service destroyed");
super.onDestroy();
handler.removeCallbacks(myRunnable);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG ,"service running");
final String CHANNEL_ID = "foreground Service ID";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
CHANNEL_ID,
NotificationManager.IMPORTANCE_HIGH
);
getSystemService(NotificationManager.class).createNotificationChannel(channel);
Notification.Builder notification = new Notification.Builder(this,CHANNEL_ID)
.setContentText("Service is running")
.setContentTitle("Service is enabled")
.setSmallIcon(R.drawable.alert);
startForeground(1001, notification.build());
}
return START_STICKY;
}
private void callKeepAliveNotifyApi() {
try{
String token = appPreferences.getRegisterToken();
System.out.println("token "+token);
Call<KeepAliveResponse> response = apiInterface.KeepAliveNotification(token);
response.enqueue(new Callback<KeepAliveResponse>() {
#RequiresApi(api = Build.VERSION_CODES.P)
#Override
public void onResponse(#NonNull Call<KeepAliveResponse> call, #NonNull Response<KeepAliveResponse> response) {
if (response.code() == 200) {
KeepAliveResponse resObj = response.body();
assert resObj != null;
if(resObj.getStatus().equals("success"))
{
Toast.makeText(getApplicationContext(), "keep-alive " + j, Toast.LENGTH_SHORT).show();
System.out.println( "delay : " + j);
j++;
appPreferences.setTimer(resObj.getTimeInterval());
int correctTimer = Integer.parseInt(appPreferences.getTimer());
correctTimer = correctTimer * 60000;
handler.postDelayed(runnable, correctTimer);
System.out.println("timer :"+appPreferences.getTimer());
}else {
Toast.makeText(getApplicationContext(), resObj.getStatusMessage(), Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(getApplicationContext(), "response error", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onFailure(#NonNull Call<KeepAliveResponse> call, #NonNull Throwable t)
{
Log.d("Response", "fail");
call.clone().enqueue(this);
}
});
System.out.println( "sdsd" +appPreferences.getTimer());
}
catch(Exception e)
{
e.printStackTrace();
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind: ");
return null;
}
}
in Mainactivity.class here I added code to call that foreground service class.
public class MainActivity extends AppCompatActivity {
private LinearLayout notification,settings,exitApp;
private ImageView backButton,logoutButton;
private TextView ScreenTitle;
private AppPreferences appPreferences;
private Context context;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
appPreferences = new AppPreferences(this);
Intent serviceIntent = new Intent(this, SmsForegroundService.class);
ContextCompat.startForegroundService(this,serviceIntent);
}
inside Manifest file added this foreground class.
<service
android:name="com.xyz.app.services.SmsForegroundService"
android:enabled="true"
android:exported="false" />

Service still running despite the App is killed

I am trying to understand the difference bwtettn STICKY and NOT_STICKY intent of a service in onStartCommand().
I created the MainActivity and the Service shown in the code below. I expected when I press the button mBtnStopApp, the onDestroy() wil be called and then
I should receive this log ** Log.w(TAG, SubTag.bullet("++++++++ SERVICE IS NOT RUNNING ++++++++")); **
because onStartCommand() returns NOT_STICKY intnet which means, when the App is killed, the service should also be stopped
but that never happens.
what happens is, when i press the button mBtnStopApp, the App is finished but i receive the following log:
** Log.w(TAG, SubTag.bullet("++++++++ SERVICE IS RUNNING ++++++++")); **
please let me know why the service is still running despite it returns START_NOT_STICKY and the App was killed
MainActivity
public class MainActivity extends AppCompatActivity {
private static final String TAG = MainActivity.class.getSimpleName();
private TextView mTv = null;
private Button mBtnStartStickyService = null;
private Button mBtnStartNonStickyService = null;
private Button mBtnStopApp = null;
private Button mBtnStopNonStickyService = null;
private Button mBtnStopStickyService = null;
private ServicesUtils mServiceUtils = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.w(TAG, SubTag.bullet("#onCreate"));
this.mServiceUtils = new ServicesUtils(this);
this.mBtnStartNonStickyService = (Button) findViewById(R.id.btnNonStickyService);
this.mBtnStartStickyService = (Button) findViewById(R.id.btnStickyService);
this.mBtnStopApp = (Button) findViewById(R.id.btnStopApp);
this.mBtnStopNonStickyService = (Button) findViewById(R.id.btnStopNonStickyService);
this.mBtnStopStickyService = (Button) findViewById(R.id.btnStopStickyService);
this.mTv = (TextView) findViewById(R.id.tv);
this.mBtnStartNonStickyService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ComponentName componentName = startService(setRunningStateForService(NonStickyService.class, "start"));
Log.i(TAG, "#mBtnStartNonStickyService: componentName: " + componentName);
}
});
this.mBtnStopNonStickyService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ComponentName componentName = startService(setRunningStateForService(NonStickyService.class, "stop"));
Log.i(TAG, "#mBtnStopNonStickyService: componentName: " + componentName);
}
});
this.mBtnStopApp.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
private Intent setRunningStateForService(Class<NonStickyService> serviceClass, String state) {
Log.w(TAG, SubTag.bullet("#setRunningStateForService"));
Intent intent = new Intent(this, serviceClass);
intent.putExtra("running", state);
return intent;
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.w(TAG, SubTag.bullet("#onDestroy"));
if (this.isNonStickyServiceRunning()) {
Log.w(TAG, SubTag.bullet("++++++++ SERVICE IS RUNNING ++++++++"));
} else {
Log.w(TAG, SubTag.bullet("++++++++ SERVICE IS NOT RUNNING ++++++++"));
}
}
private boolean isNonStickyServiceRunning() {
ActivityManager manager = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (NonStickyService.class.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
}
code:
public class NonStickyService extends Service {
private static final String TAG = NonStickyService.class.getSimpleName();
private HeavyWorkRunnable mHeavyWorkRunnable = null;
private String running = null;
#Override
public void onCreate() {
super.onCreate();
Log.w(TAG, SubTag.bullet("#onCreate"));
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.w(TAG, SubTag.bullet("#onStartCommand"));
running = intent.getStringExtra("running");
if (running != null && !running.isEmpty() && running.equals("start")) {
this.StartHeavyWorkThread();
}
return Service.START_NOT_STICKY;
}
private void StartHeavyWorkThread() {
Log.w(TAG, SubTag.bullet("#StartHeavyWorkThread"));
this.mHeavyWorkRunnable = new HeavyWorkRunnable();
new Thread(this.mHeavyWorkRunnable).start();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.w(TAG, SubTag.bullet("#onBind"));
return null;
}
#Override
public void onDestroy() {
Log.w(TAG, SubTag.bullet("#onDestroy"));
super.onDestroy();
this.running = "stop";
}
class HeavyWorkRunnable implements Runnable {
int counter = 0;
private Bundle b = null;
public void run() {
Log.w(TAG,SubTag.bullet("#HeavyWorkRunnable"));
while(running.equals("start")) {
b = new Bundle();
b.putInt("what", ++counter);
Log.w(TAG,SubTag.bullet("#HeavyWorkRunnable: counter: " + counter));
Log.w(TAG,SubTag.bullet("#HeavyWorkRunnable: b.getInt('what'): " + b.getInt("what")));
Message msg = handler.obtainMessage();
msg.setData(b);
handler.sendMessage(msg);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Log.i(TAG,SubTag.bullet("NonStickyService will Stop"));
stopSelf();
}
}
android.os.Handler handler = new android.os.Handler() {
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
int what = msg.getData().getInt("what");
Log.w(TAG,SubTag.bullet("#handler: what: " + what));
}
};
}

how to continuously Run Service in Bankground above Lollipop?

i have created one TimerTask and one Service.i want to check continuously current foreground App Name. But When My App get closed after 1 or 2 minute service is Not Active.How can i run my Service continuously.
In emulator it's working fine but in Real Device service stop after sometime
BackgroundService.java
public class BackgroundService extends Service {
private Timer mTimer;
public BackgroundService() {
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
private void startTimer() {
if (mTimer == null) {
mTimer = new Timer();
AppLockTimerTask lockTask = new AppLockTimerTask(this);
mTimer.schedule(lockTask, 0L, 1000L);
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
startTimer();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
mTimer.cancel();
mTimer.purge();
mTimer = null;
super.onDestroy();
Intent bootCompleteReceiver = new Intent("com.android.background");
sendBroadcast(bootCompleteReceiver);
}
#Override
public void onTaskRemoved(Intent rootIntent) {
mTimer.cancel();
mTimer.purge();
mTimer = null;
super.onDestroy();
Intent bootCompleteReceiver = new Intent("com.android.background");
sendBroadcast(bootCompleteReceiver);
}}
AppLockTimerTask.java
public class AppLockTimerTask extends TimerTask {
private static final String TAG = "AppLockTimerTask";
private MySharedPreferences mySharedPreferences;
private DBHelper dbHelper;
private Context mContext;
public AppLockTimerTask(Context context) {
mContext = context;
dbHelper = new DBHelper(mContext);
mySharedPreferences = MySharedPreferences.getInstance(mContext);
}
#Override
public void run() {
printForegroundTask();
}
private void printForegroundTask() {
String currentApp = "NULL";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
UsageStatsManager usm = (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE);
long time = System.currentTimeMillis();
List<UsageStats> appList = usm.queryUsageStats(UsageStatsManager.INTERVAL_DAILY, time - 1000 * 1000, time);
if (appList != null && appList.size() > 0) {
SortedMap<Long, UsageStats> mySortedMap = new TreeMap<Long, UsageStats>();
for (UsageStats usageStats : appList) {
mySortedMap.put(usageStats.getLastTimeUsed(), usageStats);
}
if (mySortedMap != null && !mySortedMap.isEmpty()) {
currentApp = mySortedMap.get(mySortedMap.lastKey()).getPackageName();
}
}
} else {
ActivityManager am = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> tasks = am.getRunningAppProcesses();
currentApp = tasks.get(0).processName;
}
Log.e(TAG, "Current App in foreground is: " + currentApp);
getNewCurrentApp(currentApp);
}
private void getNewCurrentApp(String currentApp) {
if (!currentApp.equals("com.dharmendra.applock_timerbase")) {
String previousApp = mySharedPreferences.getData(Constant.previousOpenAppName);
if (previousApp.equals("")) {
mySharedPreferences.saveData(Constant.previousOpenAppName, currentApp);
} else {
if (previousApp.equals(currentApp)) {
Log.d(TAG, "App Not Change ==>" + currentApp);
} else {
Log.d(TAG, "App Change ==>" + currentApp);
HashMap<String, String> map = dbHelper.selectFromLI(currentApp);
if (map.size() > 0) {
if (map.get("type").equals("p")) {
Intent i = new Intent();
i.setClassName("com.dharmendra.applock_timerbase", "com.dharmendra.applock_timerbase.OpenPatternLock");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("previousApp", previousApp);
i.putExtra("currentApp", currentApp);
i.putExtra("type", "p");
mContext.startActivity(i);
} else {
Log.d(TAG, "Timmer Lock");
}
} else {
mySharedPreferences.saveData(Constant.previousOpenAppName, currentApp);
}
}
}
}
}}
You can run a long background service above Android 5.0 to Android 7 by using:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
On Android 8 onwards you must use Firebse JobDispatcher, GCMNetworkmanager etc.

make service unkilled even when app clossed

I m working pedometer app and i have one service class which extends service class .
public class StepService extends Service {
private static final String TAG = "name.bagi.levente.pedometer.StepService";
private SharedPreferences mSettings;
private PedometerSettings mPedometerSettings;
private SharedPreferences mState;
private SharedPreferences.Editor mStateEditor;
private Utils mUtils;
private SensorManager mSensorManager;
private Sensor mSensor;
private StepDetector mStepDetector;
// private StepBuzzer mStepBuzzer; // used for debugging
private StepDisplayer mStepDisplayer;
private PaceNotifier mPaceNotifier;
private DistanceNotifier mDistanceNotifier;
private SpeedNotifier mSpeedNotifier;
private CaloriesNotifier mCaloriesNotifier;
private SpeakingTimer mSpeakingTimer;
private PowerManager.WakeLock wakeLock;
private NotificationManager mNM;
private int mSteps;
private int mPace;
private float mDistance;
private float mSpeed;
private float mCalories;
/**
* Class for clients to access. Because we know this service always
* runs in the same process as its clients, we don't need to deal with
* IPC.
*/
public class StepBinder extends Binder {
StepService getService() {
return StepService.this;
}
}
#Override
public void onCreate() {
// Log.i(TAG, "[SERVICE] onCreate");
super.onCreate();
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
showNotification();
// Load settings
mSettings = PreferenceManager.getDefaultSharedPreferences(this);
mPedometerSettings = new PedometerSettings(mSettings);
mState = getSharedPreferences("state", 0);
mUtils = Utils.getInstance();
mUtils.setService(this);
mUtils.initTTS();
acquireWakeLock();
// Start detecting
mStepDetector = new StepDetector();
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
registerDetector();
// Register our receiver for the ACTION_SCREEN_OFF action. This will make our receiver
// code be called whenever the phone enters standby mode.
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
registerReceiver(mReceiver, filter);
mStepDisplayer = new StepDisplayer(mPedometerSettings, mUtils);
mStepDisplayer.setSteps(mSteps = mState.getInt("steps", 0));
mStepDisplayer.addListener(mStepListener);
mStepDetector.addStepListener(mStepDisplayer);
mPaceNotifier = new PaceNotifier(mPedometerSettings, mUtils);
mPaceNotifier.setPace(mPace = mState.getInt("pace", 0));
mPaceNotifier.addListener(mPaceListener);
mStepDetector.addStepListener(mPaceNotifier);
mDistanceNotifier = new DistanceNotifier(mDistanceListener, mPedometerSettings, mUtils);
mDistanceNotifier.setDistance(mDistance = mState.getFloat("distance", 0));
mStepDetector.addStepListener(mDistanceNotifier);
mSpeedNotifier = new SpeedNotifier(mSpeedListener, mPedometerSettings, mUtils);
mSpeedNotifier.setSpeed(mSpeed = mState.getFloat("speed", 0));
mPaceNotifier.addListener(mSpeedNotifier);
mCaloriesNotifier = new CaloriesNotifier(mCaloriesListener, mPedometerSettings, mUtils);
mCaloriesNotifier.setCalories(mCalories = mState.getFloat("calories", 0));
mStepDetector.addStepListener(mCaloriesNotifier);
mSpeakingTimer = new SpeakingTimer(mPedometerSettings, mUtils);
mSpeakingTimer.addListener(mStepDisplayer);
mSpeakingTimer.addListener(mPaceNotifier);
mSpeakingTimer.addListener(mDistanceNotifier);
mSpeakingTimer.addListener(mSpeedNotifier);
mSpeakingTimer.addListener(mCaloriesNotifier);
mStepDetector.addStepListener(mSpeakingTimer);
// Used when debugging:
// mStepBuzzer = new StepBuzzer(this);
// mStepDetector.addStepListener(mStepBuzzer);
// Start voice
reloadSettings();
// Tell the user we started.
Toast.makeText(this, getText(R.string.started), Toast.LENGTH_SHORT).show();
}
#Override
public void onStart(Intent intent, int startId) {
// Log.i(TAG, "[SERVICE] onStart");
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
// Log.i(TAG, "[SERVICE] onDestroy");
mUtils.shutdownTTS();
// Unregister our receiver.
unregisterReceiver(mReceiver);
unregisterDetector();
mStateEditor = mState.edit();
mStateEditor.putInt("steps", mSteps);
mStateEditor.putInt("pace", mPace);
mStateEditor.putFloat("distance", mDistance);
mStateEditor.putFloat("speed", mSpeed);
mStateEditor.putFloat("calories", mCalories);
mStateEditor.commit();
mNM.cancel(R.string.app_name);
wakeLock.release();
super.onDestroy();
// Stop detecting
mSensorManager.unregisterListener(mStepDetector);
// Tell the user we stopped.
Toast.makeText(this, getText(R.string.stopped), Toast.LENGTH_SHORT).show();
}
private void registerDetector() {
mSensor = mSensorManager.getDefaultSensor(
Sensor.TYPE_ACCELEROMETER /*|
Sensor.TYPE_MAGNETIC_FIELD |
Sensor.TYPE_ORIENTATION*/);
mSensorManager.registerListener(mStepDetector,
mSensor,
SensorManager.SENSOR_DELAY_FASTEST);
}
private void unregisterDetector() {
mSensorManager.unregisterListener(mStepDetector);
}
#Override
public IBinder onBind(Intent intent) {
// Log.i(TAG, "[SERVICE] onBind");
return mBinder;
}
/**
* Receives messages from activity.
*/
private final IBinder mBinder = new StepBinder();
public interface ICallback {
public void stepsChanged(int value);
public void paceChanged(int value);
public void distanceChanged(float value);
public void speedChanged(float value);
public void caloriesChanged(float value);
}
private ICallback mCallback;
public void registerCallback(ICallback cb) {
mCallback = cb;
//mStepDisplayer.passValue();
//mPaceListener.passValue();
}
private int mDesiredPace;
private float mDesiredSpeed;
/**
* Called by activity to pass the desired pace value,
* whenever it is modified by the user.
* #param desiredPace
*/
public void setDesiredPace(int desiredPace) {
mDesiredPace = desiredPace;
if (mPaceNotifier != null) {
mPaceNotifier.setDesiredPace(mDesiredPace);
}
}
/**
* Called by activity to pass the desired speed value,
* whenever it is modified by the user.
* #param desiredSpeed
*/
public void setDesiredSpeed(float desiredSpeed) {
mDesiredSpeed = desiredSpeed;
if (mSpeedNotifier != null) {
mSpeedNotifier.setDesiredSpeed(mDesiredSpeed);
}
}
public void reloadSettings() {
mSettings = PreferenceManager.getDefaultSharedPreferences(this);
if (mStepDetector != null) {
mStepDetector.setSensitivity(
Float.valueOf(mSettings.getString("sensitivity", "10"))
);
}
if (mStepDisplayer != null) mStepDisplayer.reloadSettings();
if (mPaceNotifier != null) mPaceNotifier.reloadSettings();
if (mDistanceNotifier != null) mDistanceNotifier.reloadSettings();
if (mSpeedNotifier != null) mSpeedNotifier.reloadSettings();
if (mCaloriesNotifier != null) mCaloriesNotifier.reloadSettings();
if (mSpeakingTimer != null) mSpeakingTimer.reloadSettings();
}
public void resetValues() {
mStepDisplayer.setSteps(0);
mPaceNotifier.setPace(0);
mDistanceNotifier.setDistance(0);
mSpeedNotifier.setSpeed(0);
mCaloriesNotifier.setCalories(0);
}
/**
* Forwards pace values from PaceNotifier to the activity.
*/
private StepDisplayer.Listener mStepListener = new StepDisplayer.Listener() {
public void stepsChanged(int value) {
mSteps = value;
passValue();
}
public void passValue() {
if (mCallback != null) {
mCallback.stepsChanged(mSteps);
}
}
};
/**
* Forwards pace values from PaceNotifier to the activity.
*/
private PaceNotifier.Listener mPaceListener = new PaceNotifier.Listener() {
public void paceChanged(int value) {
mPace = value;
passValue();
}
public void passValue() {
if (mCallback != null) {
mCallback.paceChanged(mPace);
}
}
};
/**
* Forwards distance values from DistanceNotifier to the activity.
*/
private DistanceNotifier.Listener mDistanceListener = new DistanceNotifier.Listener() {
public void valueChanged(float value) {
mDistance = value;
passValue();
}
public void passValue() {
if (mCallback != null) {
mCallback.distanceChanged(mDistance);
}
}
};
/**
* Forwards speed values from SpeedNotifier to the activity.
*/
private SpeedNotifier.Listener mSpeedListener = new SpeedNotifier.Listener() {
public void valueChanged(float value) {
mSpeed = value;
passValue();
}
public void passValue() {
if (mCallback != null) {
mCallback.speedChanged(mSpeed);
}
}
};
/**
* Forwards calories values from CaloriesNotifier to the activity.
*/
private CaloriesNotifier.Listener mCaloriesListener = new CaloriesNotifier.Listener() {
public void valueChanged(float value) {
mCalories = value;
passValue();
}
public void passValue() {
if (mCallback != null) {
mCallback.caloriesChanged(mCalories);
}
}
};
/**
* Show a notification while this service is running.
*/
private void showNotification() {
CharSequence text = getText(R.string.app_name);
Notification notification = new Notification(R.drawable.ic_notification, null,
System.currentTimeMillis());
notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT;
Intent pedometerIntent = new Intent();
pedometerIntent.setComponent(new ComponentName(this, Pedometer.class));
pedometerIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
pedometerIntent, 0);
/* notification.setLatestEventInfo(this, text,
getText(R.string.notification_subtitle), contentIntent);
mNM.notify(R.string.app_name, notification);*/
}
// BroadcastReceiver for handling ACTION_SCREEN_OFF.
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Check action just to be on the safe side.
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// Unregisters the listener and registers it again.
StepService.this.unregisterDetector();
StepService.this.registerDetector();
if (mPedometerSettings.wakeAggressively()) {
wakeLock.release();
acquireWakeLock();
}
}
}
};
private void acquireWakeLock() {
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
int wakeFlags;
if (mPedometerSettings.wakeAggressively()) {
wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP;
}
else if (mPedometerSettings.keepScreenOn()) {
wakeFlags = PowerManager.SCREEN_DIM_WAKE_LOCK;
}
else {
wakeFlags = PowerManager.PARTIAL_WAKE_LOCK;
}
wakeLock = pm.newWakeLock(wakeFlags, TAG);
wakeLock.acquire();
}
}
ho to make this service live even when app killed also I have to count footstep even when app killed.
I m calling service like this.
startService(new Intent(Pedometer.this,
StepService.class));
#Override
public void onTaskRemoved(Intent rootIntent)
{
super.onTaskRemoved(rootIntent);
startStepService();
}
private void startStepService()
{
startService(new Intent(this,StepService.class));
}

MQTT Android Client Call CalBackListener Problems

I code a service to subscribe message from mqtt server. Service auto reconnect when internet connection on/off.
This code:
public class NotificationService extends Service{
private Handler connectBrokerHandler;
private ConnectBrokerTimerTask connectBrokerTimerTask;
private Timer connectBrokerTimer;
private MqttAndroidClient androidClient;
private MqttConnectOptions connectOptions;
private MemoryPersistence memPer;
private IMqttToken connectToken;
private CustomActionListener customActionListener;
private Context context;
private String CLIENT_STATUS = CLIENT_INIT;
private static final String TAG = "NotificationService";
private static final String USER_NAME = "chuxuanhy";
private static final String PASS_WORD = "0936160721";
private static final String URL_BROKER = "tcp://ntm.diyoracle.com:1883";
private static final String TOPIC_STAFF = "PROSHIP_STAFF";
private static final String DEVICE_ID = "FUCKYOU_002";
private static final int CONNECTION_TIMEOUT = 60;
private static final int KEEP_ALIVE_INTERVAL = 60*60;
private static final int TRY_CONNECTION_DELAY = 30; //seconds
private static final String CLIENT_INIT = "CLIENT_INIT";
private static final String CLIENT_CONNECTION_BROKER_START = "CLIENT_CONNECTION_BROKER_START";
private static final String CLIENT_CONNECTION_BROKER_FAIL = "CLIENT_CONNECTION_BROKER_FAIL";
private static final String CLIENT_CONNECTION_BROKER_SUCCESS = "CLIENT_CONNECTION_BROKER_SUCCESS";
private static final String CLIENT_LOST_CONNECTION = "CLIENT_LOST_CONNECTION";
private static final String CLIENT_SUBSCRIBE_TOPIC_START = "CLIENT_SUBSCRIBE_TOPIC_START";
private static final String CLIENT_SUBSCRIBE_TOPIC_FAIL = "CLIENT_SUBSCRIBE_TOPIC_FAIL";
private static final String CLIENT_SUBSCRIBE_TOPIC_SUCCESS = "CLIENT_SUBSCRIBE_TOPIC_SUCCESS";
private IntentFilter FilterNetwork;
private BroadcastReceiver ReceiverCheckInternet = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if(isOnline()){
if(CLIENT_STATUS == CLIENT_LOST_CONNECTION || CLIENT_STATUS == CLIENT_CONNECTION_BROKER_FAIL || CLIENT_STATUS == CLIENT_SUBSCRIBE_TOPIC_FAIL) {
ConnectBroker();
}
}
}
};
private class ConnectBrokerTimerTask extends TimerTask{
#Override
public void run() {
connectBrokerHandler.post(ConnectBrokerRunable);
}
}
private Runnable ConnectBrokerRunable = new Runnable() {
#Override
public void run() {
ConnectBroker();
}
};
public boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = cm.getActiveNetworkInfo();
return netInfo != null && netInfo.isConnectedOrConnecting();
}
public void RestartNotificationService(){
Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
restartServiceIntent.setPackage(getPackageName());
PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + 1000, restartServicePendingIntent);
}
public void createNotification(String title, String body) {
Intent intent = new Intent(this, NotificationReceiver.class);
PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(getApplicationContext());
Notification notification = mBuilder.setSmallIcon(R.drawable.train).setTicker(title).setWhen(0)
.setAutoCancel(true)
.setContentTitle(title)
.setStyle(new NotificationCompat.BigTextStyle().bigText(body))
.setContentIntent(pIntent)
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
.setVibrate(new long[]{1000, 1000})
.setLargeIcon(BitmapFactory.decodeResource(getApplicationContext().getResources(), R.mipmap.ic_launcher))
.setContentText(body).build();
Random random = new Random();
int m = random.nextInt(9999 - 1000) + 1000;
NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(m, notification);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
try{
RestartNotificationService();
}catch (Exception e){
e.printStackTrace();
}
super.onTaskRemoved(rootIntent);
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(ReceiverCheckInternet);
Log.e(TAG, "onDestroy");
try{
if(androidClient.isConnected()){
this.androidClient.unsubscribe(TOPIC_STAFF);
this.androidClient.disconnect();
this.androidClient = null;
}
}catch (Exception e){
e.printStackTrace();
}
}
private void ConnectBroker(){
try {
CLIENT_STATUS = CLIENT_CONNECTION_BROKER_START;
connectToken = this.androidClient.connect(connectOptions,null,customActionListener);
}catch (Exception e){
//e.printStackTrace();
Log.e(TAG, "ConnectBroker Fail Exception");
}
}
private void SubscribeBrokerTopic(String topic){
try {
CLIENT_STATUS = CLIENT_SUBSCRIBE_TOPIC_START;
androidClient.subscribe(topic, 0, null, customActionListener);
} catch (Exception e) {
//e.printStackTrace();
Log.e(TAG, "SubscribeBrokerTopic Fail Exception");
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("NOTIFI","CALL ME onStartCommand");
this.connectBrokerHandler = new Handler();
this.connectBrokerTimer = new Timer();
this.connectBrokerTimerTask = new ConnectBrokerTimerTask();
this.customActionListener = new CustomActionListener();
this.memPer = new MemoryPersistence();
this.connectOptions = new MqttConnectOptions();
this.connectOptions.setCleanSession(true);
this.connectOptions.setUserName(USER_NAME);
this.connectOptions.setPassword(PASS_WORD.toCharArray());
this.connectOptions.setConnectionTimeout(CONNECTION_TIMEOUT);
this.connectOptions.setKeepAliveInterval(KEEP_ALIVE_INTERVAL);
this.androidClient = new MqttAndroidClient(getApplicationContext(),URL_BROKER,DEVICE_ID,memPer);
this.androidClient.setCallback(new CustomCallBack());
this.androidClient.setTraceCallback(new CustomTraceHandler());
//this.androidClient.
this.FilterNetwork = new IntentFilter();
this.FilterNetwork.addAction("android.net.conn.CONNECTIVITY_CHANGE");
registerReceiver(ReceiverCheckInternet, FilterNetwork);
//this.androidClient.registerResources(getApplicationContext());
ConnectBroker();
return START_NOT_STICKY;
}
private class CustomTraceHandler implements MqttTraceHandler{
#Override
public void traceDebug(String source, String message) {
Log.e(TAG,"CustomConnectHandler - traceDebug\n"+source+" - "+message);
}
#Override
public void traceError(String source, String message) {
Log.e(TAG, "CustomConnectHandler - traceError\n" + source + " - " + message);
}
#Override
public void traceException(String source, String message, Exception e) {
Log.e(TAG, "CustomConnectHandler - traceException\n" + source + " - " + message);
e.printStackTrace();
}
}
private class CustomCallBack implements MqttCallback{
#Override
public void connectionLost(Throwable throwable) {
CLIENT_STATUS = CLIENT_LOST_CONNECTION;
if(!isOnline()){
Log.e(TAG, "ConnectCallBack connectionLost - No Internet Connection ");
}else {
//throwable.printStackTrace();
}
}
#Override
public void messageArrived(String s, MqttMessage mqttMessage) throws Exception {
Log.e(TAG,"ConnectCallBack messageArrived\n"+s+" - "+mqttMessage.toString());
createNotification(s, mqttMessage.toString());
}
#Override
public void deliveryComplete(IMqttDeliveryToken iMqttDeliveryToken) {
Log.e(TAG, "ConnectCallBack deliveryComplete");
}
}
private class CustomActionListener implements IMqttActionListener {
#Override
public void onSuccess(IMqttToken iMqttToken) {
if (CLIENT_STATUS == CLIENT_CONNECTION_BROKER_START) {
CLIENT_STATUS = CLIENT_CONNECTION_BROKER_SUCCESS;
if (iMqttToken.getTopics() == null) {
SubscribeBrokerTopic(TOPIC_STAFF);
}
Log.e(TAG, "CustomActionListener - CONNECT BROKER onSuccess");
} else if (CLIENT_STATUS == CLIENT_SUBSCRIBE_TOPIC_START) {
CLIENT_STATUS = CLIENT_SUBSCRIBE_TOPIC_SUCCESS;
Log.e(TAG, "CustomActionListener - SUBSCRIBE TOPIC onSuccess");
}
}
#Override
public void onFailure(IMqttToken iMqttToken, Throwable throwable) {
if (CLIENT_STATUS == CLIENT_CONNECTION_BROKER_START) {
CLIENT_STATUS = CLIENT_CONNECTION_BROKER_FAIL;
Log.e(TAG, "CustomActionListener - CONNECT BROKER onFailure ");
} else if (CLIENT_STATUS == CLIENT_SUBSCRIBE_TOPIC_START) {
CLIENT_STATUS = CLIENT_SUBSCRIBE_TOPIC_FAIL;
Log.e(TAG, "CustomActionListener - SUBSCRIBE TOPIC onFailure ");
}
if (isOnline()) {
throwable.printStackTrace();
//connectBrokerTimer.scheduleAtFixedRate(connectBrokerTimerTask, 5000, TRY_CONNECTION_DELAY * 1000);
}else {
Log.e(TAG, "CustomActionListener onFailure - No Internet Connection ");
}
}
}
}
But i have a problem, every time internet connection lost, i reconnect server, callback call again.
Example:
Log.e(TAG, "ConnectCallBack connectionLost - No Internet Connection ");
call twice, 3 time, 4 time every disconnect internet
Sorry my english not good, thank for help.
Don't handle the re-connection manually, newer version of paho has option to auto reconnect in MqttConnectOptions class.
compile 'org.eclipse.paho:org.eclipse.paho.client.mqttv3:1.1.1'
compile 'org.eclipse.paho:org.eclipse.paho.android.service:1.1.1'

Categories

Resources