【问题标题】:How to start a service from an activity in android?如何从android中的活动启动服务?
【发布时间】:2014-09-08 04:58:22
【问题描述】:

在从 Activity 启动后台服务时太困惑了,我提供了我用来从 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;
}

上面的代码是检查服务是否在运行。如果不是,则表示正在执行此操作

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

建议你的答案和解决方案来解决这个问题。

【问题讨论】:

  • 你的代码有什么问题?您是否遇到任何异常或错误?
  • Intent intent = new Intent(yourActivity.this,yourservice.class); yourActivity.this.startService(intent);
  • 如果你可以启动你的服务然后使用 Intent intent = new Intent(this, YOUR_SERIVICE_NAME.class);启动服务(意图);并在清单中定义
  • 没有异常发生总是代码移动到else部分。

标签: android android-activity android-service


【解决方案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>

在清单中。

如果您想检查服务是否运行,请在服务中使用一个静态变量并在启动服务之前进行检查。如果为假,则启动服务。

【讨论】:

  • 我在清单文件中添加了&lt;service android:name="com.*.*.service"&gt;&lt;/service&gt;
  • 这可能吗? Intent service = new Intent(); service.setAction("com.*.*.Service"); startService(service);
  • @SabariKarthik 你在清单文件中给出了完整的包名??如果没有,请给出完整的包名。
  • 主要针对清单文件中的所有声明,我曾经给出以com.*.*.filename开头的完整包名
  • @SabariKarthik 我编辑我的答案它工作。如果您检查服务是否正在运行,则登录 onStartCommand。
猜你喜欢
  • 1970-01-01
  • 2011-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多