如何从android中的活动启动服务?

时间:2014-09-08 04:58:23

标签: android android-activity android-service

在从活动中启动后台服务时非常困惑,并且提供了用于从活动启动服务的代码。

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;
}

上面的代码是检查服务是否正在运行。如果不是意味着这样做

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);
                        }

建议您的答案和解决方案以解决此问题。

2 个答案:

答案 0 :(得分:1)

如果您可以开始使用服务,请使用

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);
}

并定义

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

在清单中。

如果您想要检查服务是否运行,请在服务中使用一个静态变量,并在开始服务之前进行检查。如果是,那么启动服务。

答案 1 :(得分:0)

您可以使用Intent

Intent intent = new Intent(this, MyService.class);

startService(intent),然后将服务添加到清单文件中。

相关问题