使通知图标显示在头戴式耳机插件上



我想让它成为当一个人插入耳机时,当在那里的手机上做任何事情时,而不仅仅是从应用程序开始,通知区域会出现一个通知图标(最顶部)我已经有了通知图标代码

   //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

现在我只需要它,所以当你插入耳机时,就会显示出来。所以我用这个创建了一个新类,它检测它是否插入,然后记录它。这一切都有效

public class MusicIntentReceiver extends BroadcastReceiver {
@Override public void onReceive(Context context, Intent intent) {
    if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
        int state = intent.getIntExtra("state", -1);
        switch (state) {
        case 0:
            Log.d("unplugged", "Headset was unplugged");
            break;
        case 1:
            Log.d("plugged", "Headset is plugged");
            break;
        default:
            Log.d("uh", "I have no idea what the headset state is");
        }
    }
}

所以我所做的是尝试将该通知图标代码放入案例 1 中,以便当它检测到它已插入时,它会运行它。但它没有,相反,我得到了很多错误。这是一个截图 http://prntscr.com/1xblhb 我想不出任何其他方法来解决这个问题,我已经坚持了很长时间。因此,如果你能帮助我并尝试用初学者的术语说出来,那对我来说意味着整个世界。非常感谢。

您在

大多数地方都没有设置上下文。上下文不是MainActivity.this你甚至没有主要活动的范围。您的onReceive中有一个上下文变量,只需使用它即可。

要从您需要使用的非活动/服务中获取system service

context.getSystemService()

您还尝试创建一个名为 intent 的变量,而该变量已经创建,因此您需要另一个名称。

在总结中,查看错误所说的内容并进行这些更改

终于找到了答案

我在所有方法之外声明了这一点

int YOURAPP_NOTIFICATION_ID = 1234567890;
NotificationManager mNotificationManager;

然后在 onReceive 方法中,我调用了以下内容:

mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
showNotification(context, R.drawable.icon, "short", false);

然后声明以下方法:

private void showNotification(Context context, int statusBarIconID, String string, boolean showIconOnly) {
        // This is who should be launched if the user selects our notification.
        Intent contentIntent = new Intent();
        // choose the ticker text
        String tickerText = "ticket text";
        Notification n = new Notification(R.drawable.icon, "ticker text", System.currentTimeMillis());
        PendingIntent appIntent = PendingIntent.getActivity(context, 0, contentIntent, 0);
        n.setLatestEventInfo(context, "1", "2", appIntent);
        mNotificationManager.notify(YOURAPP_NOTIFICATION_ID, n);
    }

最新更新