1

在我的活动中:

Intent myIntent = new Intent(this, MyAlarmService.class);
pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);

AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show();

要调用的类:

public class MyAlarmService extends Service {

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        Toast.makeText(this, "MyAlarmService.onCreate()", Toast.LENGTH_LONG).show();
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        // TODO Auto-generated method stub
        super.onStart(intent, startId);
        Toast.makeText(this, "MyAlarmService.onStart()", Toast.LENGTH_LONG).show();
    }
}

使用此代码,MyAlarmService 没有被调用。为什么?此代码从示例中删除,因此经过测试可以正常运行。我会忘记什么吗?

4

2 回答 2

1

我认为,您的服务已正确启动。Toast 在服务中存在问题。

尝试更改Toast.makeText()Log.d()并查看记录是否出现在您的 Logcat 中。

服务中的 Toast 问题已在此处进行了解释。

于 2012-06-04T15:13:44.607 回答
0

似乎是对的。我还在我的代码中尝试了这个示例,它运行良好。

我认为问题出在 Manifest 中。您需要在项目的清单中声明服务,如下所示:

< service android:name=".MyAlarmService" />
于 2012-06-25T18:15:46.693 回答