0

从字面上看,我和我的朋友正在通过编写玩具应用程序来自学安卓。我们制作了一个使用加速度计的简单游戏。游戏只是一个带球的迷宫游戏。我们使用加速度计来检测运动并使用瓷砖检测来确定球是在路径上还是撞到墙上。

但是,我们也想用加速度计构建一个计时服务。此计时服务将使用加速度计确定用户何时处于空闲状态(例如 10 秒),发出警告,然后关闭游戏。也就是说,杀死活动。

所以我现在要做的是看看我是否可以在游戏在小部件上运行的 10 秒内抛出一条消息。我完全基于这里找到的代码:

我在下面的视图中实现了在上面那个教程中找到的代码,如下所示。我创建了一个名为 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 - 一些类似的问题,但没有找到解决我的课程没有被调用的原因。我也得了重感冒,所以请放过我的技术性问题。我正在努力。:-)

4

1 回答 1

1

我建议使用AlarmManager。每次调用 onSensorChanged(...) 时,您都会重置一个警报,该警报将在 10 秒内结束您的游戏。

于 2012-12-07T21:12:03.733 回答