I need to execute some tasks when my application is closed.
I have made a service for do this and tried many things, but i don't have the good result.
If someone have a tutorial or some path to follow, it would be great
This is my service:
public class TrackersImporter extends Service {
private static TrackersImporter instance;
private static long refreshDelay = 1; // Minutes
private Looper mServiceLooper;
private ServiceHandler mServiceHandler;
private boolean isInit = false;
public ArrayList<Tracker> trackers = new ArrayList<>();
public static TrackersImporter getInstance(){
if (instance == null)
instance = new TrackersImporter();
return instance;
}
#Override
public void onCreate() {
HandlerThread thread = new HandlerThread("TrackersImporter",
Process.THREAD_PRIORITY_BACKGROUND);
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
try {
Toast.makeText(this, "onStartCommand", Toast.LENGTH_SHORT).show();
Message message = mServiceHandler.obtainMessage();
message.arg1 = startId;
mServiceHandler.sendMessage(message);
} catch (Exception e) {
Log.w("TrackersImporter", e.getMessage());
}
return START_STICKY;
}
public void addTracker(Tracker tracker) {
trackers.add(tracker);
}
protected void showToast(final String msg){
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
}
});
}
// Object responsible for
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
#Override
public void handleMessage(Message msg) {
addTracker(Runkeeper.getInstance(MainActivity.getActivity()));
addTracker(Strava.getInstance(MainActivity.getActivity()));
startImport(MainActivity.getActivity().getBaseContext(), MainActivity.getActivity().getAppUser(), trackers);
stopSelf(msg.arg1);
}
/**
* Perform data imports.
* Imports are performed only 1 time.
* Additional calls to this method are equivalent to no-op.
* Call init() then performImport() for each TrackerImportable
* #param user user receiving the datas
*/
public void startImport(Context context, User user, ArrayList<Tracker> trackers) {
Context ctx = MainActivity.getActivity().getApplicationContext();
LocalDateTime now = new LocalDateTime();
if (Preferences.getPref(ctx, "tracker_import_date") == "")
Preferences.setPref(ctx, "tracker_import_date", now.toString());
LocalDateTime past = LocalDateTime.parse(Preferences.getPref(ctx, "tracker_import_date"));
long duration = new Duration(past.toDateTime(), now.toDateTime()).getStandardMinutes();
if (isInit)
return;
if (duration > refreshDelay) {
Preferences.setPref(ctx, "tracker_import_date", now.toString());
for (Tracker tracker : trackers) {
if (tracker.isEnabled() && Tracker.isUserEnabled(context, tracker.getName())) {
tracker.init();
tracker.performImport(user);
}
}
}
isInit = true;
}
}
}
This is my mainActivity
public class MainActivity extends BaseActivity {
...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
...
if (ConnectivityUtil.isConnected(this.getApplicationContext())) {
initGoogleFit();
initTrackers(appUser);
}
}
private void initTrackers(User user) {
Intent trackersIntentService = new Intent(this, TrackersImporter.class);
trackersIntentService.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
this.startService(trackersIntentService);
}
#Override
protected void onResume() {
...
if (ConnectivityUtil.isConnected(this.getApplicationContext())) {
initTrackers(appUser);
}
}
}
First Create one launcher Activity which is like your Main Activity.
In Activity "onCreate" Method you need to start Service and Do Some thing if you wont in Service "onStartCommand" Method.
public class MainActivity extends Activity {
ArrayList<Integer> list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(MainActivity.this,TrackersImporter.class);
}
public class TrackersImporter extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// do something
Log.v(TAG ,"Service is started");
}
}
And also Register this Service at manifest.xml like this.
<service android:name=".TrackersImporter"></service>
if you like stop service
stopService(new Intent(MainActivity.this,TrackersImporter.class);
Related
I require a service to send messages to the Cloud while receiving data from the device as a result I have the following code:
public class MessageService extends Service {
private int mAlert = 0;
private PanicReceiver mPanicReceiver;
#Override
public void onCreate() {
super.onCreate();
mPanicReceiver = new PanicReceiver();
IntentFilter panicFilter = new IntentFilter();
panicFilter.addAction(Constants.PANIC_ON_RECEIVER_ACTION);
panicFilter.addAction(Constants.PANIC_OFF_RECEIVER_ACTION);
registerReceiver(mPanicReceiver, panicFilter);
}
#Override
public void onDestroy() {
unregisterReceiver(mPanicReceiver);
super.onDestroy();
}
private class PanicReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case Constants.PANIC_ON_RECEIVER_ACTION:
mAlert = 2;
break;
case Constants.PANIC_OFF_RECEIVER_ACTION:
mAlert = 0;
break;
}
}
}
}
I would like to seperate the broadcast receiver to a seperate file. How can you do that?
MessageService.class
public class MessageService extends Service {
private PanicReceiver mPanicReceiver;
#Override
public void onCreate() {
super.onCreate();
mPanicReceiver = new PanicReceiver();
IntentFilter panicFilter = new IntentFilter();
panicFilter.addAction(Constants.PANIC_ON_RECEIVER_ACTION);
panicFilter.addAction(Constants.PANIC_OFF_RECEIVER_ACTION);
registerReceiver(mPanicReceiver, panicFilter);
}
#Override
public void onDestroy() {
unregisterReceiver(mPanicReceiver);
super.onDestroy();
}
private int getAlert() {
return mPanicReceiver.getAlert();
}
}
PanicReceiver.java
private class PanicReceiver extends BroadcastReceiver {
private int mAlert = 0;
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case Constants.PANIC_ON_RECEIVER_ACTION:
this.setAlert(2);
break;
case Constants.PANIC_OFF_RECEIVER_ACTION:
this.setAlert(0);
break;
}
}
public int getAlert() {
return mAlert;
}
public void setAlert(int mAlert) {
this.mAlert = mAlert;
}
}
Just move mAlert from MessageService to PanicReceiver, than you can use the IDE to assist you to refactor out the class pressing F6 with the cursor upside the class name, or with a right click:
I am using JobScheduler which uses AsyncTask for its JobService. In the class MJobExecutor which extends AsyncTask uses MediaPlayer which needs getApplicationContext() as argument is not working. It shows cannot resolve method.
public class MJobExecutor extends AsyncTask<Void,Void,String> {
ValueExchange value;
MediaPlayer player;
#Override
protected String doInBackground(Void... params) {
value = new ValueExchange();
Calendar cal = Calendar.getInstance();
Date date=cal.getTime();
DateFormat dateFormat = new SimpleDateFormat("hh:mm a");
String formattedDate=dateFormat.format(date);
if(formattedDate.equals(value.getString())){
}
return "Long running task finishes." + value.getString();
}
private void play(){
if(player == null){
player = MediaPlayer.create(getApplicationContext(),R.raw.bensoundfunkyelement);
//In the above code getApplicationContext() not working-
//Cannot resolve method getApplicationContext()
//i have used this as context not working.
//getBaseActivity() not working.
//getActivity().getApplicationContext() also not working.
player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
stopPlayer();
}
});
}
player.start();
}
private void stop(){
stopPlayer();
}
private void stopPlayer(){
if(player != null){
player.release();
player = null;
}
}
}
Below is the MainActivity file. There is no problem in this file.
public class MainActivity extends AppCompatActivity {
private static final int JOB_ID = 101;
JobScheduler jobScheduler;
JobInfo jobInfo;
TextView textTime;
ImageButton ibLeft,ibRight,ibTop,ibBottom;
TextClock textClock;
String alarmTime = "12:00 AM";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textTime = (TextView)findViewById(R.id.textView);
ibLeft = (ImageButton)findViewById(R.id.left);
ibRight = (ImageButton)findViewById(R.id.right);
ibTop = (ImageButton)findViewById(R.id.top);
ibBottom = (ImageButton)findViewById(R.id.bottom);
textClock.setPadding(0,250,0,0);
ComponentName componentName = new ComponentName(this,MJobScheduler.class);
PersistableBundle bundle = new PersistableBundle();
bundle.putString("alarmTime",alarmTime);
JobInfo.Builder builder = new JobInfo.Builder(JOB_ID,componentName);
builder.setExtras(bundle);
builder.setPeriodic(5000);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
builder.setPersisted(true);
jobInfo = builder.build();
jobScheduler = (JobScheduler) getSystemService(JOB_SCHEDULER_SERVICE);
}
public void Start(View view) {
jobScheduler.schedule(jobInfo);
Toast.makeText(this,"Job Started...",Toast.LENGTH_LONG).show();
}
public void Stop(View view) {
jobScheduler.cancel(JOB_ID);
Toast.makeText(this,"Job Cancelled...",Toast.LENGTH_LONG).show();
}
}
Below is MjobExecutor class which extends JobService calls MJobExecutor class which extends AsyncTask. It seems there is also no problem in this class.
public class MJobScheduler extends JobService {
MJobExecutor mJobExecutor;
String alarmTime;
ValueExchange value;
#Override
public boolean onStartJob(final JobParameters params) {
alarmTime = params.getExtras().getString("alarmTime");
value = new ValueExchange();
value.setString(alarmTime);
mJobExecutor = new MJobExecutor(){
#Override
protected void onPostExecute(String s) {
Toast.makeText(getApplicationContext(),alarmTime+" "+s,Toast.LENGTH_LONG).show();
jobFinished(params,false);
}
};
mJobExecutor.execute();
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
mJobExecutor.cancel(false);
return false;
}
}
You cannot call getApplicationContext() from inside an AsyncTask because that method is defined in the Context class and not in the class AsyncTask. FYI, you can use this method from Activity or Service or their subclasses because those classes are subclasses of Context.
In order to solve your problem, you will need to pass a Context object or a MediaPlayer object in your AsyncTask via constructor or setter.
For example:
public class YourTask extends AsyncTask<Void, Void, String> {
private MediaPlayer player;
public YourTask(MediaPlayer player) {
this.player = player;
}
#Override
protected String doInBackground(Void... voids) {
// todo
return null;
}
}
The AsyncTask class MJobExecutor should have constructor which passes context or media player object
public class MJobExecuter extends AsyncTask<Void, Void, String> {
private Context context;
public YourTask(Context context) {
this.context = context;
}
#Override
protected String doInBackground(Void... voids) {
// todo
return null;
}
}
And then in the class MJobScheduler which extends service which calls AsyncTask should pass the Context as shown.
public class MJobScheduler extends JobService {
MJobExecutor mJobExecutor;
String alarmTime;
ValueExchange value;
#Override
public boolean onStartJob(final JobParameters params) {
alarmTime = params.getExtras().getString("alarmTime");
value = new ValueExchange();
value.setString(alarmTime);
mJobExecutor = new MJobExecutor(getApplicationonContext()){//pass context here..
#Override
protected void onPostExecute(String s) {
Toast.makeText(getApplicationContext(),alarmTime+" "+s,Toast.LENGTH_LONG).show();
jobFinished(params,false);
}
};
mJobExecutor.execute();
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
mJobExecutor.cancel(false);
return false;
}
}
I've a task to running service every 3 second, the service will execute asynctask to checking sqlite and sending data into server
Code of myService.class
/* import foo.foo.foo */
public class myService extends Service {
public Runnable mRunnable = null;
private boolean mRunning = false;
Handler mHandler = new Handler();
IBinder mBinder = new LocalBinder();
#Override
public IBinder onBind(Intent intent) {
return mBinder;
}
public class LocalBinder extends Binder {
public myService getServerInstance() {
return myService.this;
}
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("Service"," onstart kepanggil ga?");
mRunnable = new Runnable() {
#Override
public void run() {
Log.d("Service","SERVICE RUN");
SharedPreferences pref = getSharedPreferences("wit_player_shared_preferences", MODE_PRIVATE);
String servcheck = pref.getString("serviceChecker", null);
DatabaseHandler db = new DatabaseHandler(getApplicationContext());
int countFlagAuditID = db.getCountFlagAuditID();
int countNeedToSend = db.getCountContact();
if (countNeedToSend > 0){
Log.d("countNeedToSend : ", String.valueOf(countNeedToSend));
sending a = new sending();
try {
if(servcheck.equals("no")){
Log.d("Service","SERVICE TRY CALL SENDING");
a.execute().get();
}
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
if (countFlagAuditID > 0){
Log.d("countFlagAuditID : ", String.valueOf(countFlagAuditID));
if(servcheck.equals("no")){
Log.d("Service","SERVICE TRY CALL SENDGET");
sendget b = new sendget();
b.execute();
}
}
db.close();
mHandler.postDelayed(mRunnable, 3 * 1000);
}
};
mHandler.postDelayed(mRunnable, 3 * 1000);
return START_STICKY;
}
//async task
private class sending extends AsyncTask<Void, Void, String >
{
#Override
protected void onPreExecute() {
Log.i("SENDING", "start sending");
SharedPreferences pref = getSharedPreferences("wit_player_shared_preferences", MODE_PRIVATE);
pref.edit().putString("serviceChecker", "yes").commit();
if (serv.equals("yes")){
Log.i("stop service", "service di stop");
stopSelf();
}
}
#Override
protected String doInBackground(Void... params) {
//send data to server
}
#Override
protected void onPostExecute(String result) {
SharedPreferences pref = getSharedPreferences("wit_player_shared_preferences", MODE_PRIVATE);
pref.edit().putString("serviceChecker", "no").commit();
}
}
private class sendget extends AsyncTask<Void, Void, String >
{
//execute post to server
}
}
I've a list of question about the code above:
to let my service run every 3sec I need to declare twice of mHandler.postDelayed(mRunnable, 3 * 1000);, if I'm declare the code just one, the service will run once, why it can be like that?
on sending asynctask I've add stopSelf() on onPreExecute() that mean the service will stop, but why doInBackground() task keep run?
Try to use timer instead of handler
private final Timer mTimer = new Timer();
mTimer.scheduleAtFixedRate(new LocationUpdateTask(), 0, 3000);
private class LocationUpdateTask extends TimerTask {
#Override
public void run() {
try {
//Do your stuff
} catch (Exception e) {
// TODO: handle exception
} catch (ExceptionInInitializerError in) {
}
}
}
Hello i had implement code of Music service i want to create demo of music player but it not start automatically from onCreate() i want to start player automatically when activity open. here below i put code for Activity and service please help me any help will be appreciate.
public class MainActivity extends Activity {
private ArrayList<Song> songList;
private ListView songView;
private MusicService musicSrv;
private Intent playIntent;
private boolean musicBound = false;
private MusicController controller;
private boolean paused = false, playbackPaused = false;
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
musicSrv = binder.getService();
musicSrv.setList(songList);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songView = (ListView) findViewById(R.id.song_list);
songList = new ArrayList<Song>();
getSongList();
Collections.sort(songList, new Comparator<Song>() {
public int compare(Song a, Song b) {
return a.getTitle().compareTo(b.getTitle());
}
});
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
songPicked();
}
#Override
protected void onStart() {
super.onStart();
if (playIntent == null) {
playIntent = new Intent(this, MusicService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
public void songPicked() {
musicSrv.setSong(0);
musicSrv.playSong();
}
#Override
protected void onPause() {
super.onPause();
paused = true;
}
#Override
protected void onResume() {
super.onResume();
if (paused) {
paused = false;
}
}
#Override
protected void onStop() {
controller.hide();
super.onStop();
}
#Override
protected void onDestroy() {
stopService(playIntent);
musicSrv = null;
super.onDestroy();
}
}
Here below i put service code also.
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
private final IBinder musicBind = new MusicBinder();
private MediaPlayer player;
private ArrayList<Song> songs;
private int songPosn;
private String songTitle = "";
private Random rand;
public void onCreate() {
super.onCreate();
songPosn = 0;
rand = new Random();
player = new MediaPlayer();
initMusicPlayer();
}
public void initMusicPlayer() {
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<Song> theSongs) {
songs = theSongs;
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent) {
player.stop();
player.release();
return false;
}
public void playSong() {
player.reset();
Song playSong = songs.get(0);
songTitle = playSong.getTitle();
long currSong = playSong.getID();
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
try {
player.setDataSource(getApplicationContext(), trackUri);
} catch (Exception e) {
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
public void setSong(int songIndex) {
songPosn = songIndex;
}
#Override
public void onCompletion(MediaPlayer mp) {
if (player.getCurrentPosition() > 0) {
mp.reset();
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
mp.start();
playSong();
}
#Override
public void onDestroy() {
stopForeground(true);
}
public class MusicBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
}
I just want to start player when application start automatically without any click. but it display unfortunately stopped with null object reference of Media player. I had never work with service also with music player.
Null pointer exception throws because music service object returns null so.
Finally solved as per #vladMatvienko answer thanks for your support man.
private ServiceConnection musicConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicService.MusicBinder binder = (MusicService.MusicBinder) service;
musicSrv = binder.getService();
musicSrv.setList(songList);
musicBound = true;
songPicked();
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
I'm trying to run a background service in React-Native. From what I've heard I need to write it in native Java and connect it to the react-native code. When I try to emit an event I get an error:
Tried to access a JS module before the React instance was fully set up. Calls to should only happen once initialize() has been called on your native module.
So I added a check to see if the Module is running:
if (reactContext.getLifecycleState() == LifecycleState.RESUMED)
But it always returns false. The lifecycle is stuck on BEFORE_CREATE. How should I emit my event.
Service:
public class TestService extends Service {
double distance = 0.0;
ReactContext reactContext;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
reactContext = new ReactContext(getApplicationContext());
new Timer().scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
WritableMap params = Arguments.createMap();
distance+= 0.7;
Log.d("LOG", "Trying to send distance: "+distance+" on lifecycle: "+reactContext.getLifecycleState());
params.putDouble("distance", distance);
sendEvent(reactContext, "updateDistance", params);
}
},0,1000);
return START_STICKY;
}
private void sendEvent(ReactContext reactContext, String eventName, #Nullable WritableMap params) {
if (reactContext.getLifecycleState() == LifecycleState.RESUMED) {
reactContext.getJSModule(DeviceEventManagerModule
.RCTDeviceEventEmitter.class)
.emit(eventName, params);
Log.d("LOG", "Sent distance: "+distance);
}
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
Module:
public class ServiceModule extends ReactContextBaseJavaModule {
ReactContext reactContext;
public ServiceModule(ReactApplicationContext reactContext) {
super(reactContext);
this.reactContext = reactContext;
this.initialize();
}
#ReactMethod
public void startTrackingService() {
Intent intent = new Intent(reactContext, TestService.class);
reactContext.startService(intent);
}
#Override
public String getName() {
return "ServiceModule";
}
}
Package:
public class ServicePackage implements ReactPackage {
#Override
public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {
List<NativeModule> modules = new ArrayList<>();
modules.add(new ServiceModule(reactContext));
return modules;
}
#Override
public List<Class<? extends JavaScriptModule>> createJSModules() {
return Collections.emptyList();
}
#Override
public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {
return Collections.emptyList();
}
}
MainApplication:
#Override
protected List<ReactPackage> getPackages() {
return Arrays.<ReactPackage>asList(
new MainReactPackage(),
new ReactNativePushNotificationPackage(),
new ServicePackage()
);
}
I solved it :)
In the service I was creating a new context from base context which is NOT the same object. The workaround was to broadcast the data from the service and then send them do javascript.
ServiceModule:
public class ServiceModule extends ReactContextBaseJavaModule {
public static String UPDATE = "updateDistance";
public static String DISTANCE = "distance";
private IntentFilter intentFilter;
private BroadcastReceiver receiver;
public ServiceModule(ReactApplicationContext reactContext) {
super(reactContext);
initializeBroadcastReceiver();
}
#ReactMethod
public void startTrackingService() {
Intent intent = new Intent(getReactApplicationContext(), TestService.class);
getReactApplicationContext().startService(intent);
}
#ReactMethod
public void stopTrackingService() {
Intent intent = new Intent(getReactApplicationContext(), TestService.class);
getReactApplicationContext().stopService(intent);
}
private void sendEvent(ReactContext reactContext, String eventName, #Nullable WritableMap params) {
if (reactContext.hasActiveCatalystInstance()) {
reactContext.getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)
.emit(eventName, params);
}
}
private void initializeBroadcastReceiver() {
intentFilter = new IntentFilter();
intentFilter.addAction(UPDATE);
receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
WritableMap params = Arguments.createMap();
params.putDouble(DISTANCE, intent.getDoubleExtra(DISTANCE, 0));
sendEvent(getReactApplicationContext(), UPDATE, params);
}
};
getReactApplicationContext().registerReceiver(receiver, intentFilter);
}
#Override
public String getName() {
return "ServiceModule";
}
}
TestService:
public class TestService extends Service {
double distance = 0.0;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Timer().scheduleAtFixedRate(new TimerTask(){
#Override
public void run(){
Intent broadcastIntent = new Intent();
broadcastIntent.setAction(ServiceModule.UPDATE);
broadcastIntent.putExtra(ServiceModule.DISTANCE, distance);
sendBroadcast(broadcastIntent);
distance+= 0.7;
}
},0,1000);
return START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}