2016-02-23 96 views
0

我应该为我的服务类添加一个计时器,该计时器每10秒向LogCat打印一条消息。一旦我调用startService方法,服务类中的任何内容都不会打印,我不知道为什么。任何想法?服务不能正常工作

package com.murach.reminder; 

import android.content.Intent; 
import android.os.Bundle; 
import android.app.Activity; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.widget.Button; 
import android.widget.Toast; 

public class ReminderActivity extends Activity implements OnClickListener { 

private Button startServiceButton; 
private Button stopServiceButton; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_reminder); 

    startServiceButton = (Button) findViewById(R.id.startServiceButton); 
    stopServiceButton = (Button) findViewById(R.id.stopServiceButton); 

    startServiceButton.setOnClickListener(this); 
    stopServiceButton.setOnClickListener(this); 
} 

@Override 
public void onClick(View v) { 
    Intent serviceIntent = new Intent(this, ReminderService.class); 
    switch (v.getId()) { 
     case R.id.startServiceButton: 
      // put code to start service and display toast here 
      startService(serviceIntent); 
      Toast.makeText(this, "Service started", Toast.LENGTH_SHORT).show(); 
      break; 
     case R.id.stopServiceButton: 
      // put code to stop service and display toast here 
      stopService(serviceIntent); 
      Toast.makeText(this, "Service stopped", Toast.LENGTH_SHORT).show(); 
      break; 
    } 
} 
} 

package com.murach.reminder; 

import android.app.Service; 
import android.content.Intent; 
import android.os.IBinder; 
import android.util.Log; 

import java.util.Timer; 
import java.util.TimerTask; 

public class ReminderService extends Service 
{ 
private Timer timer; 

public void onCreate() 
{ 
    Log.d("Reminder", "Service created"); 
    startTimer(); 
} 

@Override 
public IBinder onBind(Intent intent) 
{ 
    Log.d("Reminder", "No binding for this activity"); 
    return null; 
} 

public void onDestroy() 
{ 
    Log.d("Reminder", "Service destroyed"); 
    stopTimer(); 
} 

private void startTimer() { 
    TimerTask task = new TimerTask() { 

     public void run() { 
      Log.d("Reminder", "Timer task executed"); 
     } 
    }; 

    timer = new Timer(true); 
    int delay = 1000 * 10; 
    int interval = 1000 * 10; 
    timer.schedule(task, delay, interval); 
} 

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

这里是我如何注册清单中的服务(在服务元素,它不会让我完全的类型吧)

android:name="com.murach.reminder.ReminderService" 

回答

0

package名称不匹配。 Manifest声明中的单词murach中存在拼写错误。

+0

哦哎呀。我解决了这个问题,但我仍然遇到同样的问题。日志中没有任何东西出现 – Sam

相关问题