How pass value from activity to service? - android

I am fairly new to android, and I'm trying to pass a value from my activity to my service.
I've seen other answers on this subject but I not find what's my problem, the value does not pass to the service.
In my activity I've a seekbar and I want that when I change the value of seekbar ("progress") and activate the service, the service receives the value. When I close the app the value back to zero, and should be another.
In my activity I save the value with sharePreferences.
Activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
...
//SEEKBAR
textViewSensibilidad.setText("Sensibilidad: " + progress*100/seekBar.getMax()+"%");
seekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progresValue, boolean fromUser) {
progress = progresValue;
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
textViewSensibilidad.setText("Sensibilidad: " + progress*100/seekBar.getMax()+"%");
//SAVE STATE SEEKBAR
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("progress", progress);
editor.commit();
}
});
//LOAD STATE SEEKBAR
sharedPreferences = getSharedPreferences("progress" , Context.MODE_PRIVATE);
progress = sharedPreferences.getInt("progress", progress);
seekBar.setProgress(progress);
}
public void onClick(View src) {
if(toggleButton.isChecked()){
Log.d(TAG, "onClick: starting srvice");
Intent intent = new Intent(ShakeActivity.this, MyService.class);
intent.putExtra("progress", progress);
startService(intent);
...
Service
public class MyService extends Service implements SensorEventListener {
private static final String TAG = "Servicio";
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand (Intent intent, int flags, int startId){
super.onStartCommand(intent, flags, startId);
Toast.makeText(this, "Shake to Open Whatsapp Activada", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onStart");
if (intent !=null && intent.getExtras()!=null){
progress = intent.getExtras().getInt("progress");
checkeado=intent.getExtras().getBoolean("checkeado");
Toast.makeText(this, "progreso: "+progress+" checkeado: "+checkeado, Toast.LENGTH_SHORT).show();
}
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Shake to Open Whatsapp Desactivada", Toast.LENGTH_SHORT).show();
Log.d(TAG, "onDestroy");
//player.stop();
mSensorManager.unregisterListener(this);
}
Any suggestions? errors? I thank you in advance

Since you already store the progress value as a shared preference, your service can just get the shared preference value. There is no need to pass it as a value to the service.

In your service register a shared preference listener. Docs here:
http://developer.android.com/reference/android/content/SharedPreferences.html#registerOnSharedPreferenceChangeListener(android.content.SharedPreferences.OnSharedPreferenceChangeListener)
This will allow you to make the service completely independent of the activity yet observe the value changes when they are made.
Example - make your service implement SharedPreferences.OnSharedPreferenceChangeListener interface. Then define the following method in your service:
#Override
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key) {
if ("progress".equals(key) {
int progress = sharedPreferences.getInt("progress", 0);
// we have a new value -> react here
}
}
Finally don't forget to register the listener in the onStartCommand method:
SharedPreferences sharedPrefs = getSharedPreferences("progress", Context.MODE_PRIVATE);
sharedPrefs.registerOnSharedPreferenceChangeListener(this);

Related

No idea how being on service class to get float from seekbar on layoutt. Android Studio

My aim is to manage volume by seekbar of background music.
I created background music by service.
I have media player in Service class:
public class ModernService extends Service {
private MediaPlayer modernsong;
private SeekBar volumeSeekBar;
AudioManager am;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
public ModernService() {
super();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
am = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
modernsong =MediaPlayer.create(this,R.raw.modern);
modernsong.setLooping(true);
modernsong.start();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
modernsong.stop();
}
}
The question is how can i get float from a seekbar that is on layout.
Thanks in advance
First initialize the volumeSeekbar and set the max value.
volumeSeekBar = findViewById(R.id.seekBarId);
volumeSeekBar.setMax(100);
Then you need to add OnSeekBarChangeListener to the veiw.
volumeSeekBar.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
//any ui changes you wanted to do on user action on seekbar
}
});
Now you can get the value from the seekbar as volumeSeekBar.getProgress();
In service class onStartCommand is having direct access to intent.
So while starting the service through intent you can pass the seekbar value.
Intent mIntent = new Intent(this, Service.class);
Bundle extras = mIntent.getExtras();
extras.putString(key, seekbarValue);

How to stop service from logout button?

Hello I am building an app where I am using service for locations. That service have to work all the time, so I set that when service goes to onDestroy, then intent is sent to BroadcastReceiver who starts service again, and on that way, my service always works. But I want to stop service when user click on button logout. How to prevent that,when service goes to onDestroy, don't send intent to broadcast(but only when user clicks on logout)?
This is my logout from MainActivity:
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_log_out) {
if (isNetworkConnected()) {
unsubscribingFromFirebase();
removeTokenAndAccountFromSharedPreferences();
stopService(mServiceIntent);
Log.i("MAIN_ACTIVITY", "Logout!");
Log.d("MAIN_ACTIVITY " , "Internet access ");
}
else {
Toast.makeText(getApplicationContext(), getResources().getString(R.string.need_internet), Toast.LENGTH_SHORT).show();
}
}
These are methods onStartCommand, onCreate and onDestroy in location service:
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("onStartCommand" , "LocationService");
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
isEnded = false;
mRequestingLocationUpdates = false;
mLastUpdateTime = "";
Bugsnag.init(this, BUGSNAG_API_KEY);
buildGoogleApiClient();
Log.d("onCreateService", "onCreateService");
}
#Override
public void onDestroy() {
super.onDestroy();
Log.i("EXIT", "onDestroy!");
timeWhenServiceDestroyed = DateFormat.getTimeInstance().format(new Date());
SharedPreferences sharedPreferences = getSharedPreferences(getResources().getString(R.string.user_location), MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putString("onDestroyService", timeWhenServiceDestroyed);
editor.apply();
stopLocationUpdates();
Log.d("onDestroyService", "onDestroy: + " + timeWhenServiceDestroyed);
Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
}
And this is my BroadCastReceiver:
#Override
public void onReceive(Context context, Intent intent) {
Log.i(LocationServiceRestartBroadcastReceiver.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
context.startService(new Intent(context, LocationService.class));
}
How to prevent that when user clicks on logout button, my service don't create again? Thanks in advance.
You could use static boolean variable shouldRestart that is false only when logout button is clicked, otherwise true.
Add to your activity :
public static boolean shouldRestart=true;
Add to your "logout button click event" this line:
shouldRestart=false;
And add this lines in onDestroy method of service :
if (MainActivity.shouldRestart){
Intent broadcastIntent = new Intent("uk.ac.shef.oak.ActivityRecognition.RestartSensor");
sendBroadcast(broadcastIntent);
}
MainActivity.shouldRestart=true;

Cannot call methods of service from MainActivity

I have a service that has various methods and all they do is give a logcat message but these methods doesn't seem to be called even though I have created a instance of that service in my activity class.
My service class code is-
public class service extends Service {
IBinder ob=new My_Ibinder();
public class My_Ibinder extends Binder{
public service get_MyService(){
return service.this;
}
}
#Override
public void onCreate() {
super.onCreate();
Log.e("SERVICE CREATED","");
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("SERVICE OnStartCommand","");
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
Log.e("SERVICE onBind","");
return ob;
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("SERVICE DESTROYED","");
}
String data(){
Log.e("SERVICE data method","");
return "DATA SUCCESSFULLY TRANSFERRED";
}
public void ok(){
Log.e("SERVICE ok method","");
}
}
Here the methods I call are data() and ok().My activity class is-
Button start,stop,data,check;
TextView tv;
service ser;
Boolean flag=false;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start=(Button)findViewById(R.id.start);
check=(Button)findViewById(R.id.check);
stop=(Button)findViewById(R.id.stop);
data=(Button)findViewById(R.id.data);
tv=(TextView)findViewById(R.id.tv);
start.setOnClickListener(new OnClickListener(){public void onClick(View v){ bindService(new Intent(MainActivity.this,service.class),sc,Context.BIND_AUTO_CREATE); }});
stop.setOnClickListener(new OnClickListener(){public void onClick(View v){ unbindService(sc); flag=false; }});
data.setOnClickListener(new OnClickListener(){public void onClick(View v){ ser.ok();tv.setText(ser.data()); }});
check.setOnClickListener(new OnClickListener(){public void onClick(View v){ Log.e(""+flag,"sfsfsdfdssfsdffsdfs"); }});
}
private ServiceConnection sc=new ServiceConnection(){
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
My_Ibinder ob=(My_Ibinder)service;
ser=ob.get_MyService();
flag=true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
flag=false;
ser=null;
}
};
On clicking the button I don't get any logcat message. Neither from the methods I need to call, nor from the onCreate(),onBind() and onDestroy() methods which should have been called if the service is successfully created.
I've checked running processes in settings and this service doesn't exist over there.Strangely, if I start the service with startService(intent) then it seems to work fine(although I'm not able to communicate with it). I guess there is some problem with Binding the service.
Kindly Help.
Finally got it... Such a silly silly mistake I've done. While giving logcat message I didn't added a text attribute to it and it just had a tag. Now that I've added a text to it, it works perfectly. Such a small yet important point to be noted. Certainly we all use logcat messages to DEBUG our program but this time the PROBLEM was LOGCAT itself. Never gonna forget this one !!!
Refer http://developer.android.com/guide/components/aidl.html to communicate service from activity.

How to stop service while running the service?

In my application i am running the service in the background by using the following code.
Service myser=new Intent(EmailRegistrationActivity.this, BackgroundService.class);
startService(myser);
And in my service class i am using AsyncTask class. In that AsyncTask class i have to get the sms and mms from the device and posting to my local server.In between the process,the user want to sign out.So in that sign out method i want to stop the service.
And this is the service class
public class BackgroundService extends Service{
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#SuppressLint("NewApi")
public int onStartCommand(Intent intent, int flags, int startId) {
if(startId>1)
{
if(CheckInternetConnection.isOnline(BackgroundService.this))
{
dob=new Doinback();
dob.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
}else{
//check2=preferences.
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("checkbackground", true);
editor.commit();
}
}
return 1;
}
public void onStart(Intent intent, int startId) {
}
public IBinder onUnBind(Intent arg0) {
return null;
}
public void onStop() {
this.stopSelf();
}
public void onPause() {
}
#Override
public void onDestroy() {
super.onDestroy();
Log.e("Destroy=======#######","method calling");
dob.cancel(false);
while(strtId>0){
this.stopSelf(strtId);
strtId--;
}
onStop();
}
#Override
public void onLowMemory() {
}
}
And this is the asynctask class
class Doinback extends AsyncTask<URL, Integer, Long>{
protected void onPreExecute()
{
}
protected Long doInBackground(URL... arg0) {
if(!isCancelled())
{
try {
strResLastmessage_time = UrltoValue.getValuefromUrl(DataUrls.lastmessage_time + "userid="+strUserId);
JSONObject jsonObj = new JSONObject(strResLastmessage_time);
strLastMessage_time = jsonObj.getString("lastdatetime");
preferences = PreferenceManager.getDefaultSharedPreferences(BackgroundService.this);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong("msgtime", Long.parseLong(strLastMessage_time));
editor.commit();
} catch (Exception e) {
// e.printStackTrace();
}
messages.clear();
readSmsFromDevice();
checkMessages();
}
return null;
}
protected void onCancelled() {
}
protected void onPostExecute(Long result) {
//check=preferences.getBoolean("checkbackup", true);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("checkbackup", true);
editor.putBoolean("checkbackground", true);
editor.commit();
}
}//async class
And in this asyntask class i am using readsmsfromdevice method and checkmessages method to get the data from device and post to to service.But my requirement is whenever user want to logout, the service have to stop.So that i am using the following code to stop service and also stopped asynctask.
BackgroundService.dob.cancel(true);
getActivity().stopService(new Intent(getActivity(), BackgroundService.class));
But it not working,still in background the proceess is continue.Please suggest me how to stop this service.Thanks In Advance...
You are calling the right method "this.stopSelf()". I once had this problem and after adding return Service.START_NOT_STICKY it worked. Could you just add this code on onStartCommand method and check if it works:
return Service.START_NOT_STICKY;
What you need is IntentService.From docs:
IntentService is a base class for Services that handle asynchronous
requests (expressed as Intents) on demand. Clients send requests
through startService(Intent) calls; the service is started as needed,
handles each Intent in turn using a worker thread, and stops itself
when it runs out of work.
Refer this link on how to use IntentService:
http://code.tutsplus.com/tutorials/android-fundamentals-intentservice-basics--mobile-6183

How to stop back ground service completely..?

Hi friends i have a one problem to solve...I want to destroy the service completely, once i call onDestroy() method from Activity. But my problem is that i am unable to destroy it completely.. in background its keep on running, i am sharing the sample code what i tried..
//Activity Class
public class ServiceToAct extends Activity {
private static final String TAG = "BroadcastEvent";
private Intent intent;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
intent = new Intent(this, BroadcastService.class);
startService(intent);
registerReceiver(broadcastReceiver, new IntentFilter(myService.BROADCAST_ACTION));
}
/*#Override
protected void onResume() {
super.onResume();
}*/
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(broadcastReceiver);
}
#Override
protected void onDestroy() {
stopService(intent);
Toast.makeText(this, "Destroy Completely", Toast.LENGTH_LONG).show();
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
}
};
}
// service class
public class myService extends Service {
private static final String TAG = "BroadcastEvent";
public static final String BROADCAST_ACTION = "com.service.activity.myService";
private final Handler handler = new Handler();
Intent intent;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "created", Toast.LENGTH_LONG).show();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "start", Toast.LENGTH_LONG).show();
handler.removeCallbacks(sendToUI);
handler.postDelayed(sendToUI, 1000);
}
#Override
public void onDestroy() {
super.onDestroy();
stopSelf();
//stopService(intent);
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
private Runnable sendToUI = new Runnable() {
#Override
public void run() {
myData();
handler.postDelayed(this, 10000);
}
};
private void myData() {
Log.d(TAG, "keep on entering");
Toast.makeText(this, "Keep on despling in UI", Toast.LENGTH_LONG).show();
sendBroadcast(intent);
}
}
Here Actually i want to update my UI from service, Mine everything is working, but if i destroy the service its keep on calling myData() method, and i am getting the Toast msg if i close the application also.
My issue is i don't want that toast msg once the service is desroyed
I used stopService(intent) method, which destroy the service, but background method myData() is keep on calling
for stop service completely use this ..
myActivity.java
#Override
public void onDestroy() {
stopService(intent);
super.onDestroy();
Toast.makeText(this, "Destroy", Toast.LENGTH_LONG).show();
}
service.java
#Override
public void onDestroy()
{
stopSelf();
super.onDestroy();
}
You'd better never call onXxx() derectly.
Use stopService(Intent i) in your activity and stopSelf() in you service to stop instead.
use stopService() method after updating UI
or
Instead of using startService use bindService in the activity. When activity destroys, service also destroys

Categories

Resources