用Runnable创建一个任务,用Handler来处理这个任务。任务处理中用到Notification
package com.example.activity_and_service;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.os.Handler;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.app.PendingIntent;
import android.widget.Toast;
public class MainActivity extends Activity implements View.OnClickListener {
private static final int NOTE_ID = 100;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_main);
Button button = new Button(this);
button.setText("Post New Notification");
button.setOnClickListener(this);
setContentView(button);
}
public void onClick(View v)
{
handler.postDelayed(task, 10000);
Toast.makeText(this, "Notification will post in 10 seconds", Toast.LENGTH_SHORT).show();
}
private Handler handler = new Handler();
private Runnable task = new Runnable()
{
public void run()
{
NotificationManager nm = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
Intent launchIntent = new Intent(getApplicationContext(), MainActivity.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, launchIntent, 0);
Notification note = new Notification(R.drawable.ic_launcher, "Something Happened", System.currentTimeMillis());
note.setLatestEventInfo(getApplicationContext(), "Finished", "Click Here!", contentIntent);
note.defaults |= Notification.DEFAULT_SOUND;
note.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(NOTE_ID, note);
}
};
}