gpt4 book ai didi

android - 如何显示android通知和应用程序图标

转载 作者:太空宇宙 更新时间:2023-11-03 11:10:10 26 4
gpt4 key购买 nike

我有一个服务正在运行,我想发送一个通知。太糟糕了,通知对象需要一个上下文,比如一个 Activity,而不是一个服务。

你知道绕过它的方法吗?我尝试为每个通知创建一个 Activity,但它看起来很难看,而且我找不到在没有任何 View 的情况下启动 Activity 的方法。

我还想将我的应用程序图标发送到通知以在屏幕顶部显示图标

最佳答案

这是一个工作代码,它从服务本身创建一个通知。希望对你有帮助,

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();
}
}

关于android - 如何显示android通知和应用程序图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26787091/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com