zxd_72 2012-10-17 08:45 采纳率: 0%
浏览 4857
已采纳

android中启动服务的问题

我想在一个活动开始时调用一个服务。
这是Service class:

public class UpdaterServiceManager extends Service {

private final int UPDATE_INTERVAL = 60 * 1000;
private Timer timer = new Timer();  
private static final int NOTIFICATION_EX = 1;
private NotificationManager notificationManager;

public UpdaterServiceManager(){}

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}


@Override   
public void onCreate() {
  //code to execute when the service is first created

}   

@Override   
public void onDestroy() {   

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

@Override
public int onStartCommand(Intent intent, int flags, int startid) {  


    notificationManager = (NotificationManager) 
    getSystemService(Context.NOTIFICATION_SERVICE);

    int icon = android.R.drawable.stat_notify_sync;
    CharSequence tickerText = "Hello";
    long when = System.currentTimeMillis();

    Notification notification = new Notification(icon, tickerText, when);

    Context context = getApplicationContext();
    CharSequence contentTitle = "My notification";
    CharSequence contentText = "Hello World!";
    Intent notificationIntent = new Intent(this, Main.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 
        0, notificationIntent, 0);

    notification.setLatestEventInfo(context, contentTitle, 
        contentText, contentIntent);

    notificationManager.notify(NOTIFICATION_EX, notification);

    Toast.makeText(this, "Started!", Toast.LENGTH_LONG);
    timer.scheduleAtFixedRate(new TimerTask() {

        @Override
        public void run() {
            // Check if there are updates here and notify if true

        }       

    }, 0, UPDATE_INTERVAL);

    return START_STICKY;
}

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

这是调用Service的方法:

Intent serviceIntent = new Intent();
        serviceIntent.setAction("cidadaos.cidade.data.UpdaterServiceManager");
        startService(serviceIntent);

可结果是没有调用成功。上面的代码块是在activity中的onCreate方法里调用的。我调试过了也没有抛出异常。
请大牛指点错误之处,谢谢。

  • 写回答

2条回答

  • 小边3310903 2012-10-18 01:40
    关注

    检查下看在Manifest中有没有注册这个Service,我有时候会忘记注册,导致花了很长时间来解决。

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?