如何使用startForeground? [英] How to use startForeground?
问题描述
我有一个机器人服务,我使用startForeground,并没有得到我所期望得到的。 我用下面的code:
I have an android service, I am using startForeground, and do not get what I to expect to get. I use the following code:
Intent intent = new Intent(this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setContentTitle("TITLE").setContentText("CONTENT").setContentInfo("INFO")
.setWhen(System.currentTimeMillis()).setAutoCancel(false)
.setContentIntent(pendIntent);
Notification notice = builder.build();
startForeground(startForegroundId, notice);
我让旁边的图标:MyApp的运行 - 到目前为止好,但他们我得到的标准文本:触摸如需更多信息或停止...... 而且 - 当用户点击图标上的应用程序信息标准对话框
What I get next to the icon is: MyApp is running - so far so good, but them I get the standard text: "Touch for more information or to stop..." And - when the user clicks on the icon the App info standard dialog.
我要如何更改文本? 我如何运行我MainActivity当用户点击该图标?
How do I change the text? How do I run my MainActivity when the user clicks on the icon?
推荐答案
写娄code内onStartCommand()你的服务的方法:
Write bellow code inside onStartCommand() method of your service:
Notification note = new Notification(R.drawable.ic_launcher,
"Foreground Service notification?", System.currentTimeMillis());
Intent i = new Intent(this, CurrentActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pi = PendingIntent.getActivity(this, 0, i, 0);
Date dateService=new Date(System.currentTimeMillis());
String dateString=dateService.toString().split(" ")[1]+" "+dateService.toString().split(" ")[2]+" "+dateService.toString().split(" ")[3];
note.setLatestEventInfo(this, "Foreground service",
"Now foreground service running: "+dateString, pi);
note.flags |= Notification.FLAG_AUTO_CANCEL;
startForeground(2337, note);
这篇关于如何使用startForeground?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!