我在Android应用程序中有以下代码。它目前所做的是,在Calendar变量传递的指定时间,它打开RunningActivity(它是空白的),振动并发送通知。即使我按下主页按钮并且它在后台运行,它也会启动一个新的空白RunningActivity并振动并发送通知。我试图找出如何在RunningActivity(振动并发送通知)中完成所有工作,而无需打开空白的RunningActivity,允许应用程序保持在后台。
实际调用通知或振动时,我不需要帮助。我只需要知道如何在特定时间运行RunningActivity onCreate中的操作,而无需打开/显示RunningActivity。如下所示,我设置了一个带有AlarmManagager的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());
}
}
答案 0 :(得分:0)
从背景发送通知:
public void createNotification(Context context) {
// Prepare intent which is triggered if the
// notification is selected
Intent intent = new Intent(context,Myexample.class);
PendingIntent pIntent = PendingIntent.getActivity(context, 0, intent, 0);
Notification noti = new Notification.Builder(context)
.setContentTitle("My Title")
.setContentText("My message.")
.setSmallIcon(R.drawable.app_icon)
.setContentIntent(pIntent).build();
@SuppressWarnings("static-access")
NotificationManager notificationManager =
(NotificationManager)context.getSystemService(context.NOTIFICATION_SERVICE);
// Hide the notification after its selected
noti.flags |= Notification.FLAG_AUTO_CANCEL;
noti.flags |= Notification.FLAG_SHOW_LIGHTS;
notificationManager.notify(0, noti);
}
答案 1 :(得分:0)
您可以使用服务。在服务上添加振动器类,并在需要时调用它。您还可以在班级上创建一个方法,并在需要时调用它。
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(500);