如何显示android通知和应用程序图标
我正在运行服务,希望发送通知。糟糕的是,通知对象需要一个上下文,比如一个活动,而不是一个服务 你知道有什么办法绕过那个吗?我试图为每个通知创建一个活动,但它看起来很难看,而且我找不到在没有任何视图的情况下启动活动的方法如何显示android通知和应用程序图标,android,Android,我正在运行服务,希望发送通知。糟糕的是,通知对象需要一个上下文,比如一个活动,而不是一个服务 你知道有什么办法绕过那个吗?我试图为每个通知创建一个活动,但它看起来很难看,而且我找不到在没有任何视图的情况下启动活动的方法 我还想将我的应用程序图标发送到通知,以在屏幕顶部显示图标这是一个工作代码,它从服务本身创建通知。 希望它能帮助你 import android.app.Notification; import android.app.NotificationManager; import and
我还想将我的应用程序图标发送到通知,以在屏幕顶部显示图标这是一个工作代码,它从服务本身创建通知。 希望它能帮助你
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;
import android.widget.Toast;
public class MyService extends Service {
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//We get a reference to the NotificationManager
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
String MyText = "Reminder";
Notification mNotification = new Notification(R.drawable.ic_launcher, MyText, System.currentTimeMillis() );
//The three parameters are: 1. an icon, 2. a title, 3. time when the notification appears
String MyNotificationTitle = "Medicine!";
String MyNotificationText = "Don't forget to take your medicine!";
Intent MyIntent = new Intent(Intent.ACTION_VIEW);
PendingIntent StartIntent = PendingIntent.getActivity(getApplicationContext(),0,MyIntent, PendingIntent.FLAG_CANCEL_CURRENT);
//A PendingIntent will be fired when the notification is clicked. The FLAG_CANCEL_CURRENT flag cancels the pendingintent
mNotification.setLatestEventInfo(getApplicationContext(), MyNotificationTitle, MyNotificationText, StartIntent);
int NOTIFICATION_ID = 1;
notificationManager.notify(NOTIFICATION_ID , mNotification);
//We are passing the notification to the NotificationManager with a unique id.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}
使用
getApplicationContext()
。甚至服务也有上下文。如果你不想使用getApplicationContext()
你可以使用this
好的,现在我如何发送通知和应用程序图标?看看[这个答案][1],希望能有所帮助。[1] :@soheila这件事你做完了吗