Notification

1,创建一个class继承IntentService;

 1 package com.service;
 2 
 3 import com.broadcast.BroadcastReiverActivity;
 4 
 5 import android.R;
 6 import android.R.integer;
 7 import android.app.IntentService;
 8 import android.app.Notification;
 9 import android.app.NotificationManager;
10 import android.app.PendingIntent;
11 import android.content.BroadcastReceiver;
12 import android.content.Context;
13 import android.content.Intent;
14 import android.util.Log;
15 
16 public class StatusService extends IntentService {
17     private static final int K = 0;
18     public StatusService(String name) {
19         super(name);
20         // TODO Auto-generated constructor stub
21     }
22     public StatusService () {
23         super("StatusService");
24     }
25     @Override
26     protected void onHandleIntent(Intent intent) {
27         // TODO Auto-generated method stub
28         Log.i("StatusService", "开始下载....");
29         showNotification();
30         try {
31             Thread.sleep(2000);
32         } catch (InterruptedException e) {
33             // TODO Auto-generated catch block
34             e.printStackTrace();
35         }
36         Log.i("StatusService", "开始完毕....");
37     }
38     
39     private void  showNotification() {
40         Notification notification = new Notification(R.drawable.ic_btn_speak_now, "开始下载", System.currentTimeMillis());
41         Intent intent = new Intent(this,BroadcastReiverActivity.class);
42         PendingIntent contentIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
43         notification.setLatestEventInfo(this, "下载", "你好吗,我在下载哦", contentIntent);
44         NotificationManager mNotificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
45         mNotificationManager .notify(K, notification);
46     }
47 
48 }

 在MainAtivity中设置监听按钮,启动service;

package com.broadcast;

import com.service.StatusService;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class BroadcastReiverActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button st = (Button)findViewById(R.id.st);
        st.setOnClickListener(new OnClickListener() {
            
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(BroadcastReiverActivity.this,StatusService.class);
                startService(intent);
            }
        });
        
    }
}

3,配置service

posted @ 2012-05-03 10:51  春仔  阅读(265)  评论(0编辑  收藏  举报