如何在android中自动调用我的应用程序

时间:2010-12-20 10:02:56

标签: android alarm

我想在上午12点自动调用我的应用程序,这种过程,如何在android中实现,是否可能?

2 个答案:

答案 0 :(得分:1)

请看AlarmManager

以下是一个例子:

Intent myIntent = new Intent(getApplicationContext(), YourActivity.class);              
PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 1,  myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);

答案 1 :(得分:1)

ReminderBootUp.java文件包含在特定时间安排活动的代码

     package com.app.reminder;

        import java.text.SimpleDateFormat;
        import java.util.Date;

        import android.app.AlarmManager;
        import android.app.PendingIntent;
        import android.content.BroadcastReceiver;
        import android.content.Context;
        import android.content.Intent;
        import android.database.Cursor;
        import android.database.sqlite.SQLiteDatabase;
        import android.util.Log;

        public class ReminderBootUp extends BroadcastReceiver {
            private SQLiteDatabase myDataBase = null;
            private Cursor rs = null;

            @Override
            public void onReceive(Context context, Intent arg1) {
                // TODO Auto-generated method stub
                try {
                    long alarmTime = new SimpleDateFormat("yyyy-MM-dd HH:mm").parse(
                            "2010-12-21 12:00").getTime();
                    int id = 1;
                    Date date = new Date();
                    if (date.getTime() <= alarmTime) {
                        Intent notifyIntent = new Intent(context, youractivity.class);
                        PendingIntent intent = PendingIntent.getBroadcast(context, id,
                                notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
                        AlarmManager am = (AlarmManager) context
                                .getSystemService(Context.ALARM_SERVICE);
                        am.set(AlarmManager.RTC_WAKEUP, alarmTime, intent);
                    }

                } catch (Exception e) {
                    Log.e("Exception", e.getMessage(), e);
                }
            }

        }

您应该在Manifest.xml文件中添加此行

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED">
<receiver android:name="ReminderBootUp" android:permission="android.permission.RECEIVE_BOOT_COMPLETED" android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"></action>
<category android:name="android.intent.category.DEFAULT"></category>
</intent-filter>
</receiver>

启动设备后此代码将起作用...

如果您想以正常的statup活动启动应用程序, 写为普通代码