Android报警,服务未被调用

时间:2012-06-04 14:53:41

标签: android alarms

在我的活动中:

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。为什么? 此代码已从样本中删除,因此测试后该代码运行正常。我会忘记任何事吗?

2 个答案:

答案 0 :(得分:1)

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

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

已解释了服务中Toast的问题here

答案 1 :(得分:0)

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

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

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