2011-10-23 65 views
0

我需要在應用程序中爲顯示通知創建服務。我對服務代碼:在服務狀態欄中創建通知的問題Android

package com.bba.droid; 

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 AlertsMonitorService extends Service{ 

    @Override 
    public IBinder onBind(Intent arg0) { 
     // TODO Auto-generated method stub 
     return null; 
    } 

    @Override 
    public void onCreate() { 

     super.onCreate(); 
    } 

    @Override 
    public void onStart(Intent intent, int id) { 

     NotificationManager notifyMngr=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE); 
     Notification notification=new Notification(R.drawable.icon_back, "Downloading...", System.currentTimeMillis()); 

     PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, null, 0); 

     notification.setLatestEventInfo(this.getApplicationContext(), "YoutubeDownloader", "The video is downloading...", contentIntent); 
     notifyMngr.notify(0, notification); 
    } 
} 

而且我對主要活動代碼:

package com.bba.droid; 

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.net.Uri; 
import android.os.Bundle; 
import android.util.DisplayMetrics; 
import android.util.Log; 

public class DroidTestActivity extends Activity { 
    /** Called when the activity is first created. */ 
    @Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.main); 

     Intent service=new Intent(); 
     service.setClass(this, AlertsMonitorService.class); 
     this.startService(service); 
    } 
} 

但服務不創建狀態欄上的通知。我犯了什麼錯誤?

+0

問題已修復。我忘記了將「已啓用」屬性添加到清單文件中的服務記錄。 – user975290

回答

0

我不知道這是不是唯一的問題,但你在你的意圖的活動指定null

PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, null, 0); 

你想指定意圖將推出你的活動:

Intent intent = new Intent(this, DroidTestActivity.class); 
PendingIntent contentIntent = PendingIntent.getActivity(this.getApplicationContext(), 0, intent, 0);