i have a service which shows a toast message. i defined it in manifest like this-
<service android:name=".ShowNotification" />
and this is my service-
public class ShowNotification extends Service {
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(getBaseContext(), "service worked once",
Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
but i cannot figure out how to stop this service and also how to start it again?
Try :
stopService(new Intent(this, ShowNotification.class));
startService(new Intent(this, ShowNotification.class));
And restart the Service, gona recall onCreate()
Use IntentService rather than using only Service. IntentService will be destroyed automatically after completion of the task.You don't need to worry about stopping it.
Related
I am just trying Services in Android with this simple code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService(new Intent(this, PlayerService.class));
}
PlayerService.java:
public class PlayerService extends IntentService
{
public PlayerService()
{
super("PlayerService");
}
#Override
protected void onHandleIntent(Intent i)
{
int n=0;
while(true)
{
Log.i("SERVICE", "Event n." + n++);
try {
Thread.sleep(1000);
}
catch (InterruptedException e)
{ }
}
}
#Override
public void onDestroy()
{
Log.i("SERVICE", "Distr Service");
}
}
I have declared the Service in the manifest:
<service android:name="PlayerService"/>
When I start this app and then open many other apps, then this app stop working ( as I can see in the LogCat that stop showing me "Event n..." ). Why ?
In Manifest, Declare Like this
<service
android:name="Yourpackagename.PlayerService"
android:enabled="true" />
Thanks
Use Service, not IntentService. According documentation, IntentService is stoped when operation is done. Take a look here for more things about IntentService. Service is used for long term running. Take a look here.
The problem was that I must use the foreground service.
I am implementing in my Android app a splash screen which:
dowloads a sqlite database from a server
loads urls to get JSONs
creates a sqlite database in the device and execute several queries
I am using AsyncTask to do everything, my problem will occur if the user close the app in the middle of the process or turn off the device because the app:
could be creating a database or executing crucial queries in the device
could be downloading the sqlite db from a server
could be running several important process
etc
Definitely, the entire process (3-5 seconds) is important.
So... How could I avoid this? should I use handlers, loaders, on-(pause, stop, destroy) methods in order to get my objective? Can you give me an example?
As mentioned in the comment above, you should use a service as their lifecycle is separate to that of the activity.
Create the service like so:
public class MyService extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// Do everything you need to here, then call stop:
Log.d("DEBUG", "Started...");
stopSelf();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
Intent intent = new Intent("com.example.androidexample.SERVICE_STOPPING");
sendBroadcast(intent);
super.onDestroy();
}
}
Then in the activity:
public class MainActivity extends Activity {
private ServiceCompleteReceiver receiver;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
IntentFilter filter;
receiver = new ServiceCompleteReceiver();
filter = new IntentFilter("com.example.androidexample.SERVICE_STOPPING");
startService(new Intent(this, MyService.class));
registerReceiver(receiver, filter);
}
public class ServiceCompleteReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// Do whatever needs to be done here
unregisterReceiver(receiver);
}
}
}
EDIT :
Don't forget to add it to your manifest as well
<service
android:name="com.example.androidexample.MyService"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
</service>
I have the below code which freezes after the application has navigated from one activity to another. I checked my logcat for any errors but there is none. Could you please help me out with the solution? Thanks.
My service class
public class MyAlarmService extends Service
{
private Timer timer1 = new Timer();
private Timer timer2 = new Timer();
private static final long UPDATE_INTERVAL = 25000;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
_startService();
}
private void _startService() {
timer1.scheduleAtFixedRate(new TimerTask() {
public void run() {
System.out.println("Timer started1");
Leavenotification(MyAlarmService.this);
Timesheetnotification(MyAlarmService.this);
}
}, 0, UPDATE_INTERVAL);
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
}
this is how I am starting the service and activity
Intent intent = new Intent(this, Dashboard.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
intent.putExtra("userID", userID);
intent.putExtra("name", name);
startActivity(intent);
startService(new Intent(this,MyAlarmService.class);
I am not sure what is wrong here.
A service doesn't automatically run in another thread and your service doesn't make any effort to start a workerthread.
Also onStart(...) is deprecated and your service is a "bound" and "started" service which is generally fine, but if not really needed, i'd decide to use only one. The easiest way is probably using an IntentService which handles threading for you, but has some limitations.
I'd advise to have a look at the official service tutorial and get familiar with the difference between a "bound" and "started" service.
Bottom line, check out IntentService first and see if it fits your need, if not you will have to handle threading in your service yourself.
Once you start the another activity your current activity goes to background. And your current activity will not not be running on the main thread..But the service needs to running on the main thread.. A service runs in the main thread of its hosting process. try doing this
startService(new Intent(this,MyAlarmService.class);
startActivity(intent);
Declare your Service in your manifest.
<service class=".MyService" name=".MyService">
<intent-filter>
<action
android:value="sample.service.MY_SERVICE"
android:name=".MyService"
android:process="another_thread"/>
</intent-filter>
</service>
And use this propierty.
android:process="another_thread"
Use this like reference.
http://developer.android.com/guide/topics/manifest/service-element.html#exported
I want that this service run even if the application is closed (kiiled) or even if the user dont start the app.
i want the service start after the application is installed and from this point, the service should run always.
public class notifications extends Service {
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
}
#Override
public void onStart(Intent intent, int startId) {
final Handler handler = new Handler();
final Runnable runb = new Runnable()
{
public void run()
{
Toast.makeText(getApplicationContext(), " Service Started", Toast.LENGTH_LONG).show();
handler.postDelayed(this, 10000);
}
};
handler.postDelayed(runb, 0);
}
#Override
public void onDestroy() {
}
}*/
public class notifications extends IntentService
{
private Timer mBackGroundTimer;
public notifications()
{
super("myservice");
this.mBackGroundTimer=new Timer();
}
#Override
protected void onHandleIntent(Intent intent)
{
// TODO Auto-generated method stub
mBackGroundTimer.schedule(new TimerTask()
{
public void run()
{
try
{
Notification("This is message from Dipak Keshariya (Android Application Developer)", "This is Android Notification Message");
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
},1000, 2000);
} // END onHandleIntent()
private void mStopTimer()
{
//Call this whenever you need to stop the service
mBackGroundTimer.cancel();
}
private void Notification(String notificationTitle, String notificationMessage) {
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
android.app.Notification notification = new android.app.Notification(R.drawable.ic_launcher, "A New Message from Dipak Keshariya (Android Developer)!",
System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(getApplicationContext(), notificationTitle, notificationMessage, pendingIntent);
notificationManager.notify(10001, notification);
}
}
how i can do that?
Looking at your code, it appears you want your service to periodically give notifications.
As far as having it run continuously goes, keep in mind that by design, the Android system may terminate your service process at any time. You can influence this a bit, but you cannot prevent the system from killing your service.
So for your periodical actions, it would be best to use AlarmManager with a recurring alarm. Your service would then basically be one-shot, i.e. perform the action once and then exit.
For some code, look here for example:
Android: Alarm Manager
You need to implement the OnStartCommand method of the Service class and in it, return Service.START_STICKY. That will do the trick. If you kill the application, the service will continue to run in the background. However, if you restart your phone, I think you need to implement something else in your app, as well, a boot service or something like that.
As you requirement is to run the service in the background. you are on the right track to use the service because this is meant for background running purpose only.
from the activitiy you can start the service by
startService(new Intent(activityName.this, serviceName.class));
or if your application is not having any activity then you can make the service as default and main launcher of the application by putting
<service android:name="name of the service" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</service>
I think answer to this question is this : https://developer.android.com/training/sync-adapters/creating-sync-adapter.html
Sync Adapters introduced in Google I/O 2013.
I was going through the services documentation in android when I noticed two contradicting points:
In the services document it is specified in Managing the Lifecycle of a Service
These two paths are not entirely separate. That is, you can bind to a
service that was already started with startService(). For example, a
background music service could be started by calling startService()
with an Intent that identifies the music to play. Later, possibly when
the user wants to exercise some control over the player or get
information about the current song, an activity can bind to the
service by calling bindService(). In cases like this, stopService() or
stopSelf() does not actually stop the service until all clients
unbind.
But in the document about bound services in Managing the Lifecycle of a Bound Service
However, if you choose to implement the onStartCommand() callback
method, then you must explicitly stop the service, because the service
is now considered to be started. In this case, the service runs until
the service stops itself with stopSelf() or another component calls
stopService(), regardless of whether it is bound to any clients.
It may be me but I think the statements are contradictory.Could anyone please clarify...
Agree that the documentation could be clearer. What they are trying to say is:
If you call startService(), then the service will keep running unless and until you call stopSerivce() (or stopSelf() from within the service)
If you call bindService(), then the service will keep running unless and until you call unbindService()
Therefore, if you call both startService() and bindService(), then the service will keep running until you call both stopService and unbindService(). Neither on its own will stop the service.
Created a very simple Activity and Service and ran the following sequences of start/stop/bind/unbind. I observed that the calls gave the following results.
bind-unbind
bindService() caused:
onCreate()
onBind()
unbindService() caused:
onUnbind()
onDestroy()
start-bind-unbind-stop
startService() caused:
onCreate()
onStartCommand()
bindService() caused:
onBind()
unbindService() caused:
onUnbind()
stopService() caused:
onDestroy()
start-bind-stop-unbind
startService() caused:
onCreate()
onStartCommand()
bindService() caused:
onBind()
stopService() caused:
-- nothing
unbindService() caused:
onUnbind()
onDestroy()
bind-start-stop-unbind
bindService() caused:
onCreate()
onBind()
startService() caused:
onStartCommand()
stopService() caused:
-- nothing -- still running
unbindService() caused:
onUnbind()
onDestroy()
bind-start-unbind-stop
bindService() caused:
onCreate()
onBind()
startService() caused:
onStartCommand()
unbindService() caused:
onUnbind()
stopService() caused:
onDestroy()
As you can see, in each case where both bind and start were called, the service kept running until both unbind and stop were called. The sequence of unbind/stop is not important.
Here is the example code that was called from separate buttons in my simple test app:
public void onBindBtnClick(View view) {
Intent intent = new Intent(MainActivity.this, ExampleService.class);
bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}
public void onUnbindBtnClick(View view) {
if (serviceIsBound) {
unbindService(serviceConnection);
serviceIsBound = false;
}
}
public void onStartBtnClick(View view) {
Intent intent = new Intent(MainActivity.this, ExampleService.class);
startService(intent);
}
public void onStopBtnClick(View view) {
Intent intent = new Intent(MainActivity.this, ExampleService.class);
exampleService.stopService(intent);
}
Actually, both paragraphs complement each other (although their wording might be misguiding), and both paragraphs are consistent with the image from the documentation. Let's have a look:
These two paths are not entirely separate. That is, you can bind to a service that was already started with startService(). For example, a background music service could be started by calling startService() with an Intent that identifies the music to play. Later, possibly when the user wants to exercise some control over the player or get information about the current song, an activity can bind to the service by calling bindService(). In cases like this, stopService() or stopSelf() does not actually stop the service until all clients unbind.
The quintessence is: If you start a service, then bind a client to it, then try to stop it, the service is not stopped (destroyed) before all clients unbind. The second paragraph does not contradict, it refines this statement.
However, if you choose to implement the onStartCommand() callback method, then you must explicitly stop the service, because the service is now considered to be started. In this case, the service runs until the service stops itself with stopSelf() or another component calls stopService(), regardless of whether it is bound to any clients.
This means: A started and bound service runs even if no clients are bound to it until it is explicitely stopped. Granted, the wording might probably be a bit clearer on this. The lifecycle diagram given in the documentation however shows this (and I am pretty sure I already observed this in "real-life", although I am currently have no direct example on top of my head):
Yep, it works.
I want to complete with a sample code :
I had to make an app with a service started by an activity, the activity have to call some methods in the service, the service have to run in background even if the activity were killed, and when the activity restarts, it haven't to restart the service if it is running. I hope it will help you, you can see how does it work with the Log.
So that is the code :
public class MyActivity extends Activity{
private MyService myService;
private boolean mIsBound = false;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder binder) {
MyService.MyBinder b = (MyService.MyBinder) binder;
myService = b.getService();
mIsBound = true
//Do something
// Here you can call : myService.aFonctionInMyService();
}
public void onServiceDisconnected(ComponentName className) {
// Do something
mIsBound = false;
}
}
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
//Checked if my service is running
if (!isMyServiceRunning()) {
//if not, I start it.
startService(new Intent(this,MyService.class));
}
}
private boolean isMyServiceRunning() {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (RunningServiceInfo service : manager
.getRunningServices(Integer.MAX_VALUE)) {
if (MyService.class.getName().equals(
service.service.getClassName())) {
return true;
}
}
return false;
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
doBindService();
}
//Connection to the Service
private void doBindService() {
bindService(new Intent(this,MyService.class), mConnection,
Context.BIND_AUTO_CREATE);
}
// Disconnection from the service
private void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnection);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
doUnbindService();
super.onPause();
}
}
public class MyService extends Service{
public static String Tag = "MyService";
private final IBinder mBinder = new MyBinder();
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Log.d(Tag, "onCreate()");
}
public class MyBinder extends Binder {
public LocationService getService() {
return LocationService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
Log.d(Tag, "onBind()");
return mBinder;
}
#Override
public boolean onUnbind(Intent intent) {
// TODO Auto-generated method stub
Log.d(Tag, "onUnBind()");
return super.onUnbind(intent);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Log.d(Tag,"onStartCommand()");
return START_STICKY;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
Log.d(Tag, "onDestroy");
super.onDestroy();
}
public void aFonctionInMyService(){
//Do Something
}
}