我的朋友和我正在通过编程一个玩具应用程序来自学android。我们做了一个使用加速度计的简单游戏。这场比赛只是一场带球的迷宫比赛。我们使用加速度计来检测移动并使用检测区域来确定球是在路径上还是撞到墙上。编辑:在与加速度计的计时服务工作。为什么警报管理器玩具代码在这里失败?
然而,我们要建立一个与加速度计定时服务也是如此。此定时服务将确定用户何时闲置使用加速计(如10秒),发出警告,然后关闭游戏。那就是杀死这个活动。
所以我现在正在做的是看看我是否能在小部件上运行游戏的10秒内扔了一个消息。我此基础恰好关闭代码中发现here:
我实现了在该教程发现上面下面我看来,下面的代码。我创建了一个名为timingService的方法,并在我的toyappView中调用它:
public void timingService(Context context, Activity activity){
// get a Calendar object with current time
Calendar cal = Calendar.getInstance();
// add 10 seconds to the calendar object
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(context, AlarmReciever.class);
intent.putExtra("alarm_message", "This is the alarm message");
// In reality, you would want to have a static variable for the request code instead of 192837
PendingIntent sender = PendingIntent.getBroadcast(context, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
// Get the AlarmManager service
AlarmManager am = (AlarmManager) activity.getSystemService(context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
}
下面是当闹钟响起时它应该调用的类。
package com.example.toyapp;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class AlarmReciever extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
try{
Bundle bundle = intent.getExtras();
String message = bundle.getString("alarm message");
Toast.makeText(context, message, Toast.LENGTH_LONG).show();
}catch(Exception e){
Toast.makeText(context, "There was an error somewhere", Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
}
在这里我只是被卡住了。我的教程中的AlarmReciever永远不会被调用。为什么?我用我的模拟器运行调试,它永远不会进入AlarmReciever。就我而言,此游戏应持续10秒钟,然后调用AlarmReciever并在我的widgit上显示消息。对?我怀疑我的问题是在am.set?但我不明白为什么。
一如既往,感谢大家的耐心等待。当我自学如何在android中编写玩具应用程序时,我感谢您的意见和见解。这对其他人可能看起来很愚蠢,但我已经在这方面做了很多的考虑。所以,如果其他人不得不提供帮助,我将不胜感激。希望你放下我的技术。另外,我感冒了。我不相信这会在stackoverflow上重复其他问题,因为这个警报将被修改为加速度计。我会改变它从做吐司消息到杀死游戏。
亲切问候, GeekyOmega
PS - 周围的一些类似的问题,但没有发现任何解决为什么我的类不会被调用。我也有一个非常严重的感冒,所以请让我关闭这个技术。我尝试着。 :-)
所以你认为在Service中创建另一个SensorEventListener实例没有问题?我认为我已经有了。这是我的其他问题之一。除此之外,听起来像是一个很好的计划。 – GeekyOmega
不,我的意思是你应该在你使用的SensorEventListener中设置警报。 –
是的。我在我的toyapp视图中开始了一个玩具警报示例。它没有被调用。所以我认为一旦我得到这个工作,我真的很接近。因为那时我只是在每次传感器改变时重置警报。否则,当警报被调用时,我会打电话来杀死游戏。对? – GeekyOmega