意图服务,选择要启动的活动

时间:2015-04-02 10:18:04

标签: android android-intent android-notifications

我有一个实现IntentService的类,它从Web服务中检索一些数据,如果验证了条件,则在通知栏的设备上显示通知。 这是代码:

public BackgroundService() {
    super("SERVICENAME");
}

@Override
protected void onHandleIntent(Intent intent) {
    if (verifyConditions()) {
        showNotification();
    }
}

private void showNotification() {
    NotificationCompat.Builder builder = new NotificationCompat.Builder(
            this).setContentTitle("title")
            .setContentText("content")
            .setSmallIcon(R.drawable.notification_icon);
    // .setContentIntent(pendingIntent);

    Intent notificationIntent = new Intent(this.getApplicationContext(),
            SplashScreen.class);
    PendingIntent contentIntent = PendingIntent.getActivity(
            this.getApplicationContext(), 0, notificationIntent, 0);
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
            | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    // set sound
    Uri alarmSound = RingtoneManager
            .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    builder.setSound(alarmSound);

    builder.setContentIntent(contentIntent);
    Notification notification = builder.build();

    // Hide the notification after it's selected
    notification.flags |= Notification.FLAG_AUTO_CANCEL;

    NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(0, notification);
}

现在,如果用户点击通知,则会启动SplashScreen活动(这是我应用的第一个活动)。如果用户已关闭应用程序,则可以,但如果应用程序位于前台,则点击通知会导致应用程序重新启动。 有一种快速检查应用是否在前台的方法,如果是,则启动与SplashScreen不同的活动?

1 个答案:

答案 0 :(得分:1)

希望这会有所帮助。您检查您的应用是否正在运行前景,并根据PendingIntent访问StackOverFlow : check android application is in foreground or not?的更改意图