【问题标题】:Android, Display alertDialog instead of notification when app is openAndroid,打开应用程序时显示alertDialog而不是通知
【发布时间】:2015-09-16 02:08:44
【问题描述】:

我按照this 开发者教程进行操作,并且按预期在我的应用程序中使用了地理围栏。

发生地理围栏转换时会从IntentService 中发送通知:

@Override
protected void onHandleIntent(Intent intent) {
    GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);

    ...        

    sendNotification(geofenceTransitionDetails);
}

private void sendNotification(String notificationDetails) {
    // Create an explicit content Intent that starts the main Activity.
    Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);

    // Construct a task stack.
    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);

    // Add the main Activity to the task stack as the parent.
    stackBuilder.addParentStack(MainActivity.class);

    // Push the content Intent onto the stack.
    stackBuilder.addNextIntent(notificationIntent);

    // Get a PendingIntent containing the entire back stack.
    PendingIntent notificationPendingIntent =
            stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);

    // Get a notification builder that's compatible with platform versions >= 4
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this);

    // Define the notification settings.
    builder.setSmallIcon(R.mipmap.ic_launcher)
            // In a real app, you may want to use a library like Volley
            // to decode the Bitmap.
            .setLargeIcon(BitmapFactory.decodeResource(getResources(),
                    R.mipmap.ic_launcher))
            .setColor(Color.RED)
            .setContentTitle(notificationDetails)
            .setContentText("Return to app")
            .setContentIntent(notificationPendingIntent);

    // Dismiss notification once the user touches it.
    builder.setAutoCancel(true);

    // Get an instance of the Notification manager
    NotificationManager mNotificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    // Issue the notification
    mNotificationManager.notify(0, builder.build());
}

这是教程中的千篇一律。 Intent 在 Main Activity 中设置:

private PendingIntent getGeofencePendingIntent() {
    // Reuse the PendingIntent if we already have it.
    if (mGeofencePendingIntent != null) {
        return mGeofencePendingIntent;
    }
    Intent intent = new Intent(this, GeofenceTransitionsIntentService.class);
    // We use FLAG_UPDATE_CURRENT so that we get the same pending intent back when calling
    // addGeofences() and removeGeofences().
    return PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}

如何添加在应用打开时禁止通知的功能,而是向用户显示 AlertDialog?理想情况下,我希望能够执行不同的任务,具体取决于发生地理围栏转换时用户当前所处的视图。我可以从每个视图内或以某种方式全局监视/拦截过渡吗?

提前致谢。

【问题讨论】:

    标签: android android-notifications android-alertdialog intentservice android-geofence


    【解决方案1】:

    有些答案不完整,所以这里是我正在寻找的完整解决方案。

    首先,设置MyApplication 类,实现ActivityLifecycleCallbacks:

    public class MyApplication extends Application implements Application.ActivityLifecycleCallbacks {
    
        private static boolean isActive;
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            registerActivityLifecycleCallbacks(this);
        }
    
        public static boolean isActivityVisible(){
            return isActive;
        }
    
        @Override
        public void onActivityResumed(Activity activity) {
            isActive = true;
        }
    
        @Override
        public void onActivityPaused(Activity activity) {
            isActive = false;
        }
    
        ... no other methods need to be used, but there are more that 
        ... must be included for the ActivityLifecycleCallbacks
    }
    

    请务必在清单中命名(仅添加名称行,其余为默认):

    <application
        android:name=".MyApplication"
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        android:hardwareAccelerated="true">
    

    上述操作用于跟踪应用的生命周期。您可以使用它来检查您的应用当前是否在前台。

    接下来是设置BroadcastReceiver,在您希望代码运行的任何位置(如果应用程序在触发发生时打开)。在这种情况下,它在我的MainActivity:

    protected BroadcastReceiver mNotificationReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            ... Do whatever you want here
    
            Toast.makeText(...).show();
        }
    };
    

    在同一活动的onCreate 中注册接收者:

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    
        ...
    
        LocalBroadcastManager.getInstance(this).registerReceiver(mNotificationReceiver, new IntentFilter("some_custom_id"));
    }
    

    别忘了注销它:

    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mNotificationReceiver);
        super.onDestroy();
    }
    

    接收到广播时,会执行接收器中的代码。

    现在,检查应用程序是否在前台,如果是则发送广播。里面IntentService:

    @Override
    protected void onHandleIntent(Intent intent) {
        GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
        if (geofencingEvent.hasError()) {
            String errorMessage = getErrorString(this,
                    geofencingEvent.getErrorCode());
            return;
        }
    
        int geofenceTransition = geofencingEvent.getGeofenceTransition();
    
        // Test that the reported transition was of interest.
        if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
                geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
    
            ...
    
            if(MyApplication.isActivityVisible()){
                Intent intnt = new Intent("some_custom_id");
                intnt.putExtra("message", geofenceTransitionDetails);
                LocalBroadcastManager.getInstance(this).sendBroadcast(intnt);
            }else{
                sendNotification(geofenceTransitionDetails);
            }
    
        } else {
            // Log the error.
        }
    }
    

    重要的是最后一个嵌套的 if 语句:

    if(MyApplication.isActivityVisible()){
        Intent intnt = new Intent("some_custom_id");
        intnt.putExtra("message", geofenceTransitionDetails);
        LocalBroadcastManager.getInstance(this).sendBroadcast(intnt);
    }else{
        sendNotification(geofenceTransitionDetails);
    }
    

    使用MyApplication.isActivityVisible()(如上所述)检查应用程序是否在前台,然后发送通知或发送广播。只需确保您的意图代码(即"some_custom_id")与您的发送者和接收者匹配即可。

    就是这样。如果应用程序在前台(特别是 MainActivity),我会执行一些代码。如果应用不在前台,我会发送通知。

    【讨论】:

      【解决方案2】:

      最简单的方法是使用LocalBroadcastManager 或一些event bus。

      因此,当转换发生时,您应该从IntentService 发送本地广播,并在IntentService 和您的任何Activity 之间使用一些component X 捕获它。 Component X 必须跟踪您的任何Activity 是否在前台并且

      • 如果是 - 将其他本地广播向上传递(到前台 Activity),
      • 如果没有 - 显示通知。

      请注意,在 Android 中,您无法轻松跟踪您的应用是否处于前台(如果您有 1 个以上的 Activity,我认为您无法正确执行此操作),但 you can try。

      【讨论】:

      • 现在,我能想到的最好的LocalBroadcastManager 就是在我的每个活动中都包含一个接收器。有没有办法用一个接收器覆盖所有活动?另外,当应用程序打开时,如何从IntentService 中抑制/停止通知?
      • 我发现最有效的方法是结合您的答案(让我显示警报和执行任务)和 this 答案(让我确定应用程序是否正在运行)。
      【解决方案3】:

      a) 您可以将活动的生命周期事件通知您的服务。

      b) 您可以将 UI 的当前状态保存在 Activity 中的静态字段中,并在显示通知之前从服务中检查它。

      【讨论】:

      • 我不确定我是否做对了,但听起来他们只会抑制通知。当地理围栏转换发生时,我如何使用它们来显示警报对话框?或者更新视图?请提供一些代码和你的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-10-29
      • 2022-07-27
      • 1970-01-01
      相关资源
      最近更新 更多