【问题标题】:Why doesn't my Service work in Android? (I just want to log something ever 5 seconds)为什么我的服务在 Android 中不起作用? (我只想每 5 秒记录一次)
【发布时间】:2010-02-15 09:47:26
【问题描述】:

我创建了一个名为 HelloService 的新类。 我将此添加到 Android manifest.xml 中。

public class HelloService extends Service {
    private Timer timer = new Timer();
    private long INTERVAL = 5000;

    public void onCreate() {
        super.onCreate();
        startservice();

    }

    private void startservice() {
        timer.scheduleAtFixedRate( new TimerTask() {
            public void run() {
                Log.d("servy", "This proves that my service works.");
            }
        }, 0, INTERVAL);
    ; }

    private void stopservice() {
        if (timer != null){
            timer.cancel();
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        return null;
    }
}

我的其他活动这样称呼它:

    Intent helloservice = new Intent(this, HelloService.class);
    startService(helloservice);

出于某种原因,我在新的 HelloService 中设置了一个断点……但它甚至没有命中。它也没有记录。

编辑: “无法启动服务 Intent { cmp = com.examples.hello/.HelloService }:未找到”

这是什么意思? ...我在与其他所有内容相同的位置创建了 HelloService.java...


解决了。我修复了我的清单文件。 谢谢 Nikola Smiljanic

<service android:name=".HelloService"/>

到:

   <service android:name="HelloService"></service>

【问题讨论】:

  • 您在清单文件中添加了什么?
  • 如果您的问题已解决,请发布答案并接受。这会将其从日益增长的未回答提示中删除。
  • 正是我遇到的,奇怪的是在官方文档中:developer.android.com/guide/topics/fundamentals/…,他们使用,以点为前缀跨度>

标签: java android service timer


【解决方案1】:

也许您没有在清单中声明该服务。无论如何,您使用了错误的课程。您必须使用 AlarmManager 来编写事件。看到那个链接,它对我很有用。

Use alarmManager and service to perform schedule notification only during specific time period

【讨论】:

    【解决方案2】:

    服务与任何其他 Android 应用程序一样具有生命周期。因此,您的服务可能会被系统杀死(请参阅Service 文档)。实现这一点的正确方法是使用Alarm Manager,如Android service stops 中所述。

    【讨论】:

      【解决方案3】:

      你会试试这个:

      helloservice.setComponent(new ComponentName
                       (*hello service package name goes here*, 
                                      *hello service canonical name goes here*));
      startService(helloservice);
      

      【讨论】:

        【解决方案4】:

        在项目的 mainfest.xml 文件中声明你的服务。

        <services  android:name=".SMSReceiver" android:enabled="true">
                  <intent-filter>
                          <action android:name=/>
                 </intent-filter>
         </services>
        

        【讨论】:

          【解决方案5】:
          猜你喜欢
          • 2018-07-17
          • 1970-01-01
          • 2016-09-15
          • 1970-01-01
          • 2021-06-07
          • 1970-01-01
          • 2015-06-22
          • 1970-01-01
          • 2013-04-25
          相关资源
          最近更新 更多