ユーザーからの入力を受け取り、それを通知として設定する非常にシンプルなアプリがあります。ユーザーは、好きなだけ通知を作成できます。ユーザーに通知をクリックして、と呼ばれる新しいアクティビティに移動してもらいたいResultActivity
。次に、通知インテントからResultActivity
を読み込み、ユーザーに表示します。以下のコードを使用すると、通知が押されるたびに最後に作成された通知putExtras
を受け取ることを除いて、私が望むほとんどすべてのことを実行できます。putExtra
Intent notificationIntent = new Intent(ctx, MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(ctx, i,notificationIntent,PendingIntent.FLAG_CANCEL_CURRENT);
NotificationManager nm = (NotificationManager) ctx.getSystemService(Context.NOTIFICATION_SERVICE);
Resources res = ctx.getResources();
NotificationCompat.Builder builder = new NotificationCompat.Builder(ctx);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res,R.drawable.ic_launcher))
.setTicker("Remember to " + text.getText())
.setWhen(System.currentTimeMillis()).setAutoCancel(true)
.setContentTitle(text.getText());
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, ResultActivity.class);
String pass = text.getText().toString();
resultIntent.putExtra("title", pass);
resultIntent.putExtra("uid", i);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);
new Uri.Builder().scheme("data").appendQueryParameter("text", "my text").build();
builder.setContentIntent(resultPendingIntent);
Notification n = builder.build();
n.flags = Notification.FLAG_NO_CLEAR;
nm.notify(i++, n);
text.setText(null);
アプリケーションを開きます
「One」と入力します
ヒットOK
通知が送信されます
アプリケーションを開きます
「2」と入力します
ヒットOK
通知が送信されます
これで、2つの通知があります。「1つ」と言うものと「2つ」と言うもの。「Two」という通知をクリックすると、「Two」という画面が表示されます。完全!
通知「One」をクリックすると、「Two」という画面が表示されます。壊れた!
ResultActivity.java
public class ResultActivity extends Activity {
String title = null;
TextView text;
int i=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity);
text = (TextView) findViewById(R.id.textView1);
title = getIntent().getStringExtra("title");
i = getIntent().getIntExtra("uid", 0);
text.setText(title);
}