我需要在我的应用程序中创建服务以显示通知。我有服务代码:
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 :(得分: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);