Search code examples
androidandroid-activityandroid-service

How to start a service from an activity in android?


am too much confused in starting a background service from an activity and am providing the code which i used to start the service from an activity.

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    Log.v("Running activities", manager.toString());
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
 if ("com.*.*.service.Service".equals(service.service.getClassName())) {
     return true;
       }
    }
     Log.v("Currently running services in andorid phone", "other services");
    return false;
}

Above code is to check whether the service is running or not.If it is not means am doing this

if(isMyServiceRunning()) {
                          System.out.println("Service is running");
                        } else {
                          System.out.println("Service is not running");
                          Intent serviceIntent = new Intent();
                          serviceIntent.setAction("com.*.*.service.Service");
                          startService(serviceIntent);
                        }

Suggest your answers and solutions to solve this problem.


Solution

  • If you can start your service then use

    public class YourService extends Service {
    
    public static boolean isRunning = false;
    
         @Override
         public IBinder onBind(Intent intent) {
             return null;
         }
    
         @Override
         public int onStartCommand(Intent intent, int flags, int startId) {
             isRunning = true;
             return START_STICKY;
         }
    }
    
    if(!YourService.isRunning){
        Intent intent = new Intent(this, YourService.class);
        startService(intent);
    
        Date date = new Date(System.currentTimeMillis());
        SimpleDateFormat sdf = new SimpleDateFormat("hh:mm aa");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date dt = new Date(System.currentTimeMillis());
        String strTime = sdf.format(dt);
        String strDate = dateFormat.format(date);
    }
    

    and also define

    <service android:name="com.mypackagename.YourService"></service>
    

    in manifest.

    If you want check service running or not then use one static variable in service and check before start your service. If that false then start service.