如何在活动开始时停止AlarmManager

时间:2016-04-01 02:49:25

标签: android notifications

我是android的新手。今天我尝试使用AlarmManage作为我的Reminder应用程序,允许用户输入小时和分钟来显示通知,我有一些问题。  1.第一个问题是当通知出现时,虽然我已经设置声音默认通知并为我的手机设置允许声音,但它只是振动并且没有声音。  2.当我关闭应用程序时,如果我触摸通知,MainActivity将显示,AlarmManager再次工作,使我的应用程序再次显示通知。但是,如果我在应用程序打开时触摸通知,则通知不会显示。所以我希望我的应用程序只是一次通知。我怎么能这样做?  3.虽然我设定了提醒时间,但是当我关闭申请时,有时候我的电话会在我从未设置的时候显示我提醒申请的通知。我该如何解决这个问题?

MyAlarmService

private NotificationManager mManager;

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

@Override
public void onCreate()
{
    // TODO Auto-generated method stub
    super.onCreate();
}

@SuppressWarnings("static-access")
@Override
public void onStart(Intent intent, int startId)
{
    super.onStart(intent, startId);
   // Toast.makeText(this, "I'm running", Toast.LENGTH_SHORT).show();
    long[] v = {500,1000};
    NotificationCompat.Builder mBuilder =
            new NotificationCompat.Builder(this)
                    .setVibrate(v)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                    .setSmallIcon(R.drawable.ic_remind)
                    .setContentTitle("My notification")
        .setContentText("This is a test message!");
    mBuilder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);
    mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
    mBuilder.setAutoCancel(true);
    Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
    intent1.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);

    TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
    stackBuilder.addParentStack(MainActivity.class);
    stackBuilder.addNextIntent(intent1);



    PendingIntent pendingNotificationIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_UPDATE_CURRENT);
    mBuilder.setContentIntent(pendingNotificationIntent);
    mManager =(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    mManager.notify(0, mBuilder.build());

}

@Override
public void onDestroy()
{
    // TODO Auto-generated method stub
    super.onDestroy();
}

接收机

public void onReceive(Context context, Intent intent)
{
    Intent service1 = new Intent(context, MyAlarmService.class);
    context.startService(service1);
}

MainActivity

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final EditText edt_hours = (EditText)findViewById(R.id.edt_hour);
    final EditText edt_minutes = (EditText)findViewById(R.id.edt_minutes);
    FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
    fab.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(edt_hours.getText().toString()));
             calendar.set(Calendar.MINUTE, Integer.parseInt(edt_minutes.getText().toString()));
            //calendar.set(Calendar.SECOND,0);

            Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
            pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, myIntent,0);

            alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
            alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);

        }
    });



} //end onCre
p / s:我很抱歉,如果我的问题不清楚,因为我的英语不好。对于读过这个问题的人,我想感谢你。

1 个答案:

答案 0 :(得分:3)

这是我的示例代码。我想它会对你有帮助。

MainActivity

 public static int NOW_NOTIFICATION = 101; 

Intent intent = new Intent(MainActivity.this, NotificationReceiver.class);
                intent.putExtra(NotificationReceiver.NOTIFICATION_MESSAGE, "Sample Alert");
                PendingIntent pendingIntent = PendingIntent.getBroadcast(
                        MainActivity.this, NOW_NOTIFICATION, intent, PendingIntent.FLAG_ONE_SHOT);

                cancelNotification(NOW_NOTIFICATION);
                AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
                alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()
                        + (2 * 1000), pendingIntent);

取消通知:

public void cancelNotification(int requestCode) {
        try {
            Intent notificationIntent = new Intent(getApplicationContext(), NotificationReceiver.class);
            PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), requestCode, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
            AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
            alarmManager.cancel(pendingIntent);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

NotificationReceiver:

public class NotificationReceiver extends BroadcastReceiver {
    public static String NOTIFICATION_MESSAGE = "notificationMessage";


    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra(NOTIFICATION_MESSAGE);
        NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        //Define sound URI
        Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        Intent notificationIntent = new Intent(context, EmptyActivity.class);
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
        final DateTime dateTime = DateTime.now();
        int color = 0xffffaa00;
//        int color1 = context.getColor(R.color.notificatinBackgroundColor);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
        builder.setSmallIcon(R.drawable.festi_push_message_small);
        builder.setContentIntent(pendingIntent);
        builder.setContentTitle("Notification Sample");
        builder.setAutoCancel(true);
        builder.setContentText(message + ", Current Time : " + dateTime.getHourOfDay() + ":" + dateTime.getMinuteOfHour() + ":" + dateTime.getSecondOfMinute());
        builder.setSound(soundUri);
        builder.setLights(Color.RED, 1000, 1000);
        builder.setColor(color);


        Notification notification = builder.build();

        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        notificationManager.notify(102938, notification);
    }

}

的AndroidManifest.xml

  <receiver android:name=".NotificationReceiver" />