为什么我的服务不适用于Android?(我只想记录5秒钟的东西)

TIM*_*MEX 18 java service android timer

我创建了一个名为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;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的其他活动称之为:

    Intent helloservice = new Intent(this, HelloService.class);
    startService(helloservice);
Run Code Online (Sandbox Code Playgroud)

出于某种原因,我在我的新HelloService中放了一个断点......但它甚至没有打.它也没有记录.

编辑:"无法启动服务Intent {cmp = com.examples.hello/.HelloService}:not found"

那是什么意思?...我在其他地方创建了HelloService.java ...


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

<service android:name=".HelloService"/>
Run Code Online (Sandbox Code Playgroud)

至:

   <service android:name="HelloService"></service>
Run Code Online (Sandbox Code Playgroud)

小智 7

也许你并没有在最明确的时候宣布这项服务.无论如何你正在使用错误的课程.您必须使用AlarmManager来编程事件.看到那个链接,对我来说非常有用.

使用alarmManager和service仅在特定时间段内执行计划通知


小智 1

你会尝试这个吗:

helloservice.setComponent(new ComponentName
                 (*hello service package name goes here*, 
                                *hello service canonical name goes here*));
startService(helloservice);
Run Code Online (Sandbox Code Playgroud)