在用户指定的时间启动应用程序?

时间:2011-03-04 17:30:35

标签: java android alarmmanager

我有一个播放广播电台的应用程序,现在我想整合一个闹钟,以便在闹钟响起时播放一个广播电台。我一直在研究报警管理器,这似乎是最好的方法。

我的应用程序有一个警报按钮,可以调用一个对话框来设置警报。如果设置了闹钟,我需要让我的应用在指定时间开始。但是,我在使用这部分代码时遇到了问题:

Intent intent = new Intent("some Context", null, null, MainActivity.class);
PendingIntent pendInt = PendingIntent.getBroadcast("some Context", 0, intent, 0);
AlarmManager alarmService = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarmService.set(AlarmManager.RTC_WAKEUP, timeToSound, pendInt);

具体来说,我对context需要的内容感到困惑。我见过很多例子,但没有人真正详细解释过。如果有人能对这件事情有所了解,我将不胜感激 更多可能有帮助的代码...

@Override
    protected Dialog onCreateDialog(int id) {
        Dialog d = null;
        switch (id) {
        case LINEUP_DIALOG_ID:
            d = new LineupDialog(this);
            d.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
            WindowManager.LayoutParams lp = d.getWindow().getAttributes();
            lp.dimAmount = 0.5f;
            d.getWindow().setAttributes(lp);
            break;

这会调用我的对话框^

private View.OnClickListener lineupAction = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            //showAlarm();
            showDialog(LINEUP_DIALOG_ID);
        }
    };

这两个都在我的mainActivity中 然后我有一个保存布局的xml文件(如果需要可以提供..只允许用户选择时间和复选框,然后保存)
保存按钮有一个onclickListener ---它在我的LineupDialog类中扩展了我的NavDialog,而我的navdialog只是扩展了Dialog。

2 个答案:

答案 0 :(得分:0)

凯尔,

它应该是包上下文,但这有时取决于您在代码中创建IntentPendingIntent的位置。您刚试过thisgetApplicationContext()吗?

答案 1 :(得分:0)

事实证明我还需要创建一个新类...上下文的一部分通过创建一个变量来工作,而且如果有其他人需要它,这里是我必须创建的新服务的代码。

//imports here
public class AlarmService extends Service{

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        //System.out.println("hello im in the alarmService Binder");

        return null;
    }

    @Override
    public void onStart(Intent intent, int startid) {
        Intent mainAct = new Intent("android.intent.action.MAIN");
        //System.out.println("hello im in the alarmService onStart " + mainAct);
        mainAct.setClass(AlarmService.this, MainActivity.class);
        mainAct.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        mainAct.putExtra("alarm","true");
        startActivity(mainAct);
    }

    @Override
    public void onCreate() {
        //System.out.println("hello im in the alarmService onCreate");
        //code to execute when the service is first created
    }

}

然后不要忘记将它添加到您的清单

相关问题