在Service中弹出Notification
我的Service类:
package test.service;import test.activity.TestServiceActivity;import android.app.Notification;import android.app.NotificationManager;import android.app.PendingIntent;import android.app.Service;import android.content.Context;import android.content.Intent;import android.os.IBinder;public class MyService extends Service { @Override public IBinder onBind(Intent arg0) { // TODO Auto-generated method stub return null; } @Override public void onCreate() { // TODO Auto-generated method stub super.onCreate(); } @Override public void onDestroy() { // TODO Auto-generated method stub super.onDestroy(); } @Override public void onStart(Intent intent, int startId) { // TODO Auto-generated method stub super.onStart(intent, startId); String ns = Context.NOTIFICATION_SERVICE; NotificationManager nm = (NotificationManager) getSystemService(ns); CharSequence tickerText = "Hello"; long when = System.currentTimeMillis(); Notification notification = new Notification(1, tickerText, when); PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this, TestServiceActivity.class), 0); notification.setLatestEventInfo(this, "出勤提醒", "還有15分鐘就到上班時間", pi); nm.notify(1, notification); }}
package test.activity;import test.service.MyService;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;public class TestServiceActivity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } public void start(View view) { Intent serviceIntent = new Intent(this, MyService.class); // serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); startService(serviceIntent); } public void stop(View view) { Intent serviceIntent = new Intent(this, MyService.class); // serviceIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); stopService(serviceIntent); }}
<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:orientation="vertical" > <Button android:id="@+id/start" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="start" android:text="start service" android:textSize="20dip" /> <Button android:id="@+id/stop" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="stop" android:text="stop service" android:textSize="20dip" /></LinearLayout>