我在一个 android 应用程序中有以下代码。它当前所做的是,在与 Calendar when 变量一起传递的指定时间,它打开 RunningActivity(它是空白的),振动并发送通知。即使我按下了主页按钮并且它在后台运行,它也会启动一个新的空白 RunningActivity 并振动并发送通知。我试图弄清楚如何在不打开空白 RunningActivity 的情况下执行 RunningActivity 中的所有内容(振动并发送通知),从而允许应用程序留在后台。
我不需要帮助来实际调用通知或振动。我只需要知道如何在不打开/显示 RunningActivity 的情况下在特定时间运行 RunningActivity onCreate 中的操作。如下所示,我使用 AlarmManager 设置了一个 PendingIntent,问题是它正在启动一个 Activity 并在我想要它做的只是振动/发送通知时显示它。
public void startAlarm(Activity activity, Calendar when){
currentTimerHour = when.get(Calendar.HOUR);
currentTimerMin = when.get(Calendar.MINUTE);
Intent intent = new Intent(activity, RunningActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(activity, 12345, intent, PendingIntent.FLAG_CANCEL_CURRENT);
AlarmManager am = (AlarmManager)activity.getSystemService(Activity.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, when.getTimeInMillis(), pendingIntent);
}
RunningActivity 类:
public class RunningActivity extends Activity {
@Override
public void onCreate(Bundle bundle){
super.onCreate(bundle);
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);
NotificationCompat.Builder mBuilder;
mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("My notification")
.setContentText("Hello World!");
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
}