Предположим, я создаю приложение для Android, похожее на приложение SMS.Требования следующие:
- Пользователь может получать несколько уведомлений, каждое из которых имеет динамический идентификатор типа int.
- Когда выбрано уведомление, оно загружает действие, которое отображаетсоответствующее сообщение (SMS).
- Одно выбранное уведомление должно быть автоматически отклонено.
Моя идея о том, как справиться с этим, заключалась в использовании putExtra для добавления целочисленного идентификаторадля намерения, которое затем будет доступно из намерения в загружаемом им действии, которое затем отклонит уведомление, которое его вызвало.
Для моего тестового примера приведены спецификации:
- Уведомления в конечном итоге будут генерироваться из службы, поскольку теперь они создаются, когда тестовый пользователь нажимает кнопку.
- Когда выбрано уведомление, вызываемая активность передает сообщение, а затем пытается отклонитьуведомление.(Для наглядности)
Вот мои проблемы:
- Когда выбрано первое уведомление, оно корректно.Уведомление отклоняется.
- Когда выбрано каждое последующее уведомление, отображается идентификатор первого уведомления, и ничего не отклоняется.
- Я новичок в Java, более привыкший к языкам сценариев (таким какPerl, PHP и т. Д.):)
Вот мой источник:
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android = "http://schemas.android.com/apk/res/android"
android:orientation = "vertical"
android:layout_width = "fill_parent"
android:layout_height = "fill_parent"
>
<Button
android:id="@+id/create_notification"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:text = "Create new notification"
/>
package org.test.notifydemo;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.Random;
public class aRunNotificationDemo extends Activity
{
private NotificationManager mNotificationManager;
@Override
public void onCreate( Bundle icicle )
{
super.onCreate( icicle );
setContentView( R.layout.run_notify_demo );
mNotificationManager = (NotificationManager) getSystemService( aRunNotificationDemo.NOTIFICATION_SERVICE );
int close_notify_id = getIntent().getIntExtra( "notification_id", 0 );
if ( close_notify_id != 0 )
{
Toast.makeText( aRunNotificationDemo.this, "Dimissing this notification: " + Integer.toString(close_notify_id), Toast.LENGTH_SHORT ).show();
mNotificationManager.cancel( close_notify_id );
}
findViewById( R.id.create_notification ).setOnClickListener( new MyButtonListener() );
}
private class MyButtonListener implements Button.OnClickListener
{
public void onClick( View my_view )
{
Random randGen = new Random();
int notify_id = randGen.nextInt();
int icon = R.drawable.icon_notification_01;
CharSequence tickerText = Integer.toString(notify_id) + " New SMS!";
long when = System.currentTimeMillis();
Notification my_notification = new Notification(icon, tickerText, when);
Context context = getApplicationContext();
CharSequence contentTitle = Integer.toString(notify_id) + " New SMS Available!";
CharSequence contentText = Integer.toString(notify_id) + " There is a new SMS available.";
Intent notificationIntent = new Intent( aRunNotificationDemo.this, aRunNotificationDemo.class );
notificationIntent.putExtra( "notification_id", notify_id );
PendingIntent contentIntent = PendingIntent.getActivity( aRunNotificationDemo.this, 0, notificationIntent, 0 );
my_notification.setLatestEventInfo( context, contentTitle, contentText, contentIntent );
mNotificationManager.notify( notify_id, my_notification );
}
}
}