在Android开发中,PhoneWindow
类通常不直接用于显示通知栏。相反,你应该使用 NotificationManagerCompat
类来显示通知。以下是一个简单的示例,展示了如何使用 NotificationManagerCompat
显示一个基本的通知:
添加必要的权限:
在你的 AndroidManifest.xml
文件中添加以下权限:
<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY"/>
创建通知渠道(适用于Android 8.0及以上版本):
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import androidx.core.app.NotificationCompat;
import androidx.core.app.NotificationManagerCompat;
public class MyApplication extends Application {
@Override
public void onCreate() {
super.onCreate();
createNotificationChannel();
}
private void createNotificationChannel() {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_description);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel("my_channel_id", name, importance);
channel.setDescription(description);
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
}
显示通知:
import android.app.NotificationCompat;
import android.content.Context;
import androidx.core.app.NotificationManagerCompat;
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, "my_channel_id")
.setSmallIcon(R.drawable.ic_notification)
.setContentTitle("My Notification")
.setContentText("Hello, this is a notification!")
.setAutoCancel(true);
NotificationManagerCompat notificationManager = NotificationManagerCompat.from(this);
notificationManager.notify(1, builder.build());
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
在 AndroidManifest.xml
中声明服务:
<service android:name=".MyService" />
启动服务: 你可以通过以下方式启动服务:
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
通过上述步骤,你可以使用 NotificationManagerCompat
类来显示一个基本的通知。如果你需要更复杂的通知功能,可以进一步自定义 NotificationCompat.Builder
对象。