【问题标题】:Making a notification icon appear on boot/headset plugin在启动/耳机插件上显示通知图标
【发布时间】:2023-03-23 19:38:01
【问题描述】:

我想这样做,当有人插入耳机时,会出现一个通知图标。我已经做到了,所以当手机打开时,它会启动 MainActivity 类,该类在 OnCreate 方法中包含通知图标的代码,因此它会自动启动。问题在于它启动了我不想要的整个活动和应用程序。我只是想让图标出现。我该怎么办?谢谢!

public void onReceive(Context context, Intent intent) {
    // TODO Auto-generated method stub
    Intent myIntent = new Intent(context, MainActivity.class);
    myIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(myIntent);
}

以上代码在启动时启动 MainActivity。

通知图标代码

    //Notification Icon Starts
    NotificationManager nm=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification=new Notification(R.drawable.icon_notification, "Icon Notification", System.currentTimeMillis());
    Context context=MainActivity.this;
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), Notification.FLAG_ONGOING_EVENT);        
    notification.flags = Notification.FLAG_ONGOING_EVENT;
    notification.setLatestEventInfo(this, "Notification Icon", "Touch for more options", contentIntent);
    Intent intent=new Intent(context,MainActivity.class);
    PendingIntent  pending=PendingIntent.getActivity(context, 0, intent, 0);
    nm.notify(0, notification);
    //Notification Icon Ends

【问题讨论】:

  • 您能否详细说明您的问题。您需要在哪里通知?请添加更多代码。
  • @androiduser 我真的需要在用户连接耳机时出现通知图标。我希望通知出现在手机的最顶部(通知区域,将其拉下以用于通知抽屉)我已经编写了该代码,并且可以正常工作。 (用它更新了主要问题)但我只想在用户插入耳机时运行该代码。我不希望应用程序启动或其他任何事情,只是为了显示该图标。

标签: android notifications boot headset


【解决方案1】:

正如我在your last question 中所写,在您的清单中添加一个<receiver> 来监听ACTION_HEADSET_PLUG 广播。 documentation 显示 Intent 附加信息,您可以使用这些附加信息来确定耳机是否已插入 (state) 等。

【讨论】:

  • 我明白了。使用这个接收器。 <receiver android:name=".BootReciever" > <intent-filter> <action android:name="android.intent.ACTION_HEADSET_PLUG" /> </intent-filter> </receiver> 但是我将如何做出一个 if else 声明来说明如何处理它。和在哪里。这就是让我困惑的地方
  • @FernandoRamirez:我不知道你在说什么。你“想要做到这一点,当一个人插入耳机时,会出现一个通知图标”。这需要在BroadcastReceiver 集合的onReceive() 方法中使用十几行代码来侦听ACTION_HEADSET_PLUG 广播。
  • 我只需要知道如何让它在后台工作,比如让它在不打开应用程序的情况下检测它。就像在这个新问题中一样。我已经解决了我所有的问题,除了这个,这是我的最后一个。 stackoverflow.com/questions/19368767/…
【解决方案2】:

我发布了一个解决方案,可让您监控耳机状态(有线和蓝牙)over here。此解决方案可以轻松扩展以允许您显示通知。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-25
    • 1970-01-01
    • 1970-01-01
    • 2011-12-24
    • 1970-01-01
    • 2022-11-13
    相关资源
    最近更新 更多