Android save data with Service when activity dead - android

public class ReadList{
private static SparseArray<Read> LIST = new SparseArray<>();
public static void add(int ID){
LIST.put(ID, new Read(ID, DateFormat.getDateTimeInstance().format(new Date())));
}
public static void remove(int ID){
if(LIST.indexOfKey(ID) >= 0 )
LIST.remove(ID);
}
}
I have some similar readlist class.. Saving data with SharedPreference correctly and normally.
But i want when onDestroy(), onStop() or onPause() method called my DataSaveService starting and saving data SharedPreference file..
public class DataSaveService extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
MyCustomSharedSaveData.saveAllReadListtoXML();
MyCustomSharedSaveData.saveAllFavoriteListtoXML();
}
}
Is it possible? Thank you and sory for my bad english..

onDestroy() call is up to the Android OS, as it calls it when the memory is getting low, so placing your service call there might not be a good idea. onStop() will be called when an activity is hidden completely from the view that is either user minimizes the app or a new activity is opened from the from the previous one, so i suppose you can call the sevice in onStop method

Related

Does a paused activity, still receive callbacks from service?

So here is what I am trying to understand.
I have a service like this
public MyService extends Service {
public List<MyListener> listenersList = new ArrayList<>();
public void addListeners(MyListeners mylistener) {
listenersList.add(myListener);
}
public void eventAOccured(){
for ( MyListner mylistener : listeners ) {
mylistener.eventAOccured();
}
}
public void eventBOccured(){
for ( MyListner mylistener : listeners ) {
mylistener.eventBOccured();
}
}
}
And here is my MyListener Interface which activities
public Interface MyListener {
public eventAOccured();
public eventBOccured();
}
Now we have three activites
public Activity1 extends AppCompatActivity implements MyListener{
public static int myVariable = 1;
//starts service. For sake of brevity I am skipping this part.
MyService.add(this);
//on click of a button
startActivity( new Intent (Activity1.this, Activity2.class);
//Now I know this will put Activity1 in paused state
#Override
public void eventAOccured() {
//Call activity 3
}
#Override
public void eventBOccured() {
myVariable = 3;
}
}
This is the second activity which is called by clicking a button in activity 1. After Activity2 is launched, lets say eventB occurs. Now If I access myVariable from Activity1, will it be 1 or 3.
After some time let us say, eventA has occured. Now will Activity3 will be launched?
I know an activity being paused means it is no longer visible to the user, but will the communication with service continue?
yes, paused activity still will receive the event as it is in the back stack of system and is not destroyed.
Override the onStartCommand(Intent intent, int flags, int startId) and returen STRAT_STICKY. this will restart the service.
You can check following Example.
public class Test extends Service {
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("Test Service ", "onStartCommand");
return START_STICKY; //It will restart Service in onPause/onDestroy
}
#Override
public void onCreate() {
super.onCreate();
//Do your operation
}
}

How to keep read and receive notifications of BLE in background?

I have an application which allows to read and write (notify) in BLE. Following the sample example, I created my own read and write functions in the class BluetoothLeService as follows:
public void readCharacteristic()
{
//My function
}
public void writeCustomCharacteristic(int value)
{
//My function
}
I want to keep read and write data when the application is in background. Hence, I must to make a service to do it. A simple structure of a service will be
public class backgroundservice extends Service
{
private static final String TAG = "MyService";
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onDestroy() {
Log.d(TAG, "onDestroy");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_NOT_STICKY;
}
}
My question is how can I read/write data when my application is in background? If I use above service, which function do I need to use to call readCharacteristic() and writeCustomCharacteristic(int value)? For example, the writeCustomCharacteristic(int value) is called every 10 seconds. Thank all

Android background service checking url from sharedpreferences

I´m pretty new to Android. So far I made an App that has a webview in an activity. The webview gets the url string via sharedpreferences.
In my MainMenu I have a button that starts a service.
This service should constantly check if the sharedpreferences url is available or not. If the desired state is reached, the app should do something else. How do I do that(checking the url)? Where do I open the sharedpref url, onStartCommand or run()?
public class NotifiyService extends Service {
String savedsa;
String response = null;
int statuscode;
String statuscodeS;
final class TheThread implements Runnable{
int serviceID;
TheThread(int serviceID){
this.serviceID = serviceID;
}
#Override
public void run() {
}
}
public NotifiyService() {
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStarted),Toast.LENGTH_LONG).show();
Thread Th1 = new Thread(new TheThread(startId));
Th1.start();
return START_STICKY;
}
#Override
public void onDestroy() {
//super.onDestroy();
Toast.makeText(NotifiyService.this,getResources().getString(R.string.MonStopped), Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
return null;
}
}
As the purpose of ur service is to check the url from preferences,
you should do it in the
run()
method which you will implement for the thread inside the service.
The business logic which you need to carry out in service must not be in main thread.
I think it will be better to check url in onStartCommand before new thread creation. After that you can pass it into constructor like 'startId'
new TheThread(startId, url)
You should use Bounded Service since you have to notify the activity from service when the URL is available. Unbounded Service can not communicate with the host activity. Take a look at http://www.101apps.co.za/index.php/articles/binding-to-a-service-a-tutorial.html to understand Bounded Service. You should check the URL in the run() method.

Service is being recreated each time the activity resumes

I am in quite a tough predicament here as I have an activity that starts a service which runs a countdown timer. Each time the activity is resumed, the service starts another countdown timer. I looked up services and it has method which is called on once throughout the service and is called onCreate. The only issue with that is I am receiving time values from the activity through intents which is retrieved during onStartCommand. onCreate is called before onStartCommand meaning I cannot retrieve those values and plug them into onCreate. Is there a way I can put values from onStartCommand to onCreate. The following code shows my problem.
TextView timeTextView;
int data;
public String hms;
public CountDownAct countDownAct;
public CountDownTime countDownTimer;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
//I need the CountDownTimer to start here in order to prevent a new countdown timer from being created each time the activity is resumed.`
countDownTimer = new CountDownTime(data,1000 );
countDownTimer.start();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//the time data is being retrieved here
data = intent.getIntExtra("the", 0);
return START_STICKY;
}
#Override
public boolean stopService(Intent name) {
Log.i("CountDownService", "Stop Service");
return super.stopService(name);
}
#Override
public void onDestroy() {
countDownTimer.cancel();
}
Starting the Service
useService = new Intent(CountDownAct.this, CountDownService.class);
useService.putExtra("the", actualTimeFiniliazedInMilliSeconds);
startService(useService);
You can use SharedPreference to store actualTimeFiniliazedInMilliSeconds. This can be retrived from service class :
useService = new Intent(CountDownAct.this, CountDownService.class);
SharedPreference mShared = getApplicationContext().getSharedPreference("myShared",Context.MODE_PRIVATE);
SharedPreferences.Editor mEditor = mShared.edit();
mEditor.putInt("data",actualTimeFiniliazedInMilliSeconds).commit();
startService(useService);
Retriving :
SharedPreference mShared = getApplicationContext().getSharedPreference("myShared",Context.MODE_PRIVATE);
countDownTimer = new CountDownTime(mShared.getInt("data",0),1000);
countDownTimer.start();

Service put and get some data

I have two applications. One run service and second is only small app. I want to put some data to service in first app, but I want to get this data in second app. How can I do that? I need that because when I use home button on second app and return I need check if id was changed. I think about run service with id in first app and second app when onResume check that id.
This is code service class:
public class ServiceId extends Service{
private int id;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
}
#Override
public void onDestroy() {
}
#Override
public void onStart(Intent intent, int startid) {
id = MainActivity.getApplicationId();
Log.v("Start", "Webservice started");
}
}
I start service in mainactivity:
startService(new Intent(MainActivity.this, ServiceId.class));
how get that id in other application?

Categories

Resources