【问题标题】:Create notifications every minute每分钟创建通知
【发布时间】:2016-01-08 12:47:16
【问题描述】:

我想每分钟创建一次通知,我从另一个关于每 48 小时通知一次的问题中输入代码,但应用程序正在运行并且没有创建通知。我究竟做错了什么? 显示通知:

public class ShowNotification extends Service {

    private final static String TAG = "ShowNotification";

    @Override
    public void onCreate() {
        super.onCreate();

        Intent mainIntent = new Intent(this, MainActivity.class);

        NotificationManager notificationManager
                = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        Notification noti = new NotificationCompat.Builder(this)
                .setAutoCancel(true)
                .setContentIntent(PendingIntent.getActivity(this, 0, mainIntent,
                        PendingIntent.FLAG_UPDATE_CURRENT))
                .setContentTitle("New SMS " + System.currentTimeMillis())
                .setContentText("Hello")
                .setDefaults(Notification.DEFAULT_ALL)
                .setSmallIcon(R.drawable.ic_email_white_24dp)
                .setTicker("ticker message")
                .setWhen(System.currentTimeMillis())
                .build();

        notificationManager.notify(0, noti);

        Log.i(TAG, "Notification created");
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
}

主活动:

context = MainActivity.this;
        Intent notificationIntent = new Intent(context, ShowNotification.class);
        PendingIntent contentIntent = PendingIntent.getService(context, 0, notificationIntent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        am.cancel(contentIntent);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                , 1000*60, contentIntent);

【问题讨论】:

    标签: android android-notifications android-alarms


    【解决方案1】:

    几个建议:

    1. 使用 IntentService 实现您的通知触发代码。如果您使用的是 android studio,则可以使用一个非常简单的向导来制作一个。只需右键单击一个包>新建>服务>服务(意图服务)。将您的通知触发代码放在句柄操作方法中。这需要在您的清单中声明。

    2. 定义一个 BroadcastReceiver,最好在另一个文件中,该文件调用静态方法以在其 onReceive() 中启动 Intent 服务。这在新>其他>BroadcastReciever 中的向导中也可用。这也需要在您的清单中声明。

    3. 创建一个静态方法来初始化警报(我把它放在 IntentService 本身中)并从您的主活动中调用它。

    4. 就像现在一样,您正在为通知提供相同的 id (0)。 这只会替换原始通知,而不是创建新通知。

    以下代码可能会有所帮助:(我使用向导构建了它,因此如果它们不准确,请忽略自动生成的 cmets)

    意图服务:

    import android.app.AlarmManager;
    import android.app.IntentService;
    import android.app.Notification;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.content.Intent;
    import android.content.Context;
    import android.support.v7.app.NotificationCompat;
    
    
    import java.util.Calendar;
    
    /**
     * An {@link IntentService} subclass for handling asynchronous task requests in
     * a service on a separate handler thread.
     * <p/>
     * helper methods.
     */
    public class NotificationIntentService extends IntentService {
        // TODO: Rename actions, choose action names that describe tasks that this
        // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
        private static final String ACTION_FIRENOTIF = "com.example.alarmnotif.action.FOO";
    
        public NotificationIntentService() {
            super("NotificationIntentService");
        }
        public static void initAlarm(Context context) {
            Calendar updateTime = Calendar.getInstance();
            Intent downloader = new Intent(context, AlarmReceiver.class);
            PendingIntent recurringSync = PendingIntent.getBroadcast(context,
                    0, downloader, PendingIntent.FLAG_CANCEL_CURRENT);
    
            AlarmManager alarms = (AlarmManager) context.getSystemService(
                    Context.ALARM_SERVICE);
            alarms.setInexactRepeating(AlarmManager.RTC_WAKEUP,
                    updateTime.getTimeInMillis(),
                    60000, recurringSync);
        }
    
        /**
         * Starts this service to perform action FireNotif with the given parameters. If
         * the service is already performing a task this action will be queued.
         *
         * @see IntentService
         */
        public static void startActionFireNotif(Context context) {
            Intent intent = new Intent(context, NotificationIntentService.class);
            intent.setAction(ACTION_FIRENOTIF);
            context.startService(intent);
        }
    
    
        @Override
        protected void onHandleIntent(Intent intent) {
            if (intent != null) {
                final String action = intent.getAction();
                if (ACTION_FIRENOTIF.equals(action)) {
                    handleActionFireNotif();
                }
            }
        }
    
        /**
         * Handle actionFireNotif in the provided background thread with the provided
         * parameters.
         */
        private void handleActionFireNotif() {
            Intent mainIntent = new Intent(this, MainActivity.class);
    
            NotificationManager notificationManager
                    = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
    
            Notification noti = new NotificationCompat.Builder(this)
                    .setAutoCancel(true)
                    .setContentIntent(PendingIntent.getActivity(this, 0, mainIntent,
                            PendingIntent.FLAG_UPDATE_CURRENT))
                    .setContentTitle("New SMS " + System.currentTimeMillis())
                    .setContentText("Hello")
                    .setDefaults(Notification.DEFAULT_ALL)
                    .setSmallIcon(R.drawable.ic_email_white_24dp)
                    .setTicker("ticker message")
                    .setWhen(System.currentTimeMillis())
                    .build();
    
            notificationManager.notify(0, noti);
    
        }
    
    
    }
    

    报警接收器:

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    
    public class AlarmReceiver extends BroadcastReceiver {
        public AlarmReceiver() {
        }
    
        @Override
        public void onReceive(Context context, Intent intent) {
            NotificationIntentService.startActionFireNotif(context);
        }
    }
    

    将以下内容添加到清单中:

        <service
            android:name=".alarmnotif.NotificationIntentService"
            android:exported="false" />
    
        <receiver
            android:name=".alarmnotif.AlarmReceiver"
            android:enabled="true"
            android:exported="false"></receiver>
    

    【讨论】:

    • 不工作,我创建了你所说的所有课程并且通知没有创建;我等待 2 或 3 分钟。
    • 您是否从主要活动中调用了 initAlarm?
    • 在哪里?就在 onCreate 中?
    • 我建议您研究一下 android studio 向导...它们工作得很好,可以为您节省很多工作...
    • 如果您在应用程序的 onCreate 中调用 init 会更好
    猜你喜欢
    • 2013-10-19
    • 1970-01-01
    • 2020-11-17
    • 2013-10-14
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    相关资源
    最近更新 更多