0

我想这样做,当一个人插入耳机时,在手机上做任何事情时,不仅仅是在应用程序上开始,通知图标出现在通知区域(非常顶部)我已经有了通知图标代码

   //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 我只是想不出任何其他方法来解决这个问题,我已经坚持了这么久。因此,如果您能帮助我并尝试用初学者的方式说出来,那对我来说就意味着整个世界。太感谢了。

4

2 回答 2

0

终于找到了这个问题的答案

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

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);
    }
于 2013-10-14T19:36:17.507 回答
0

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

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

context.getSystemService()

您还试图创建intent一个在已经创建时调用的变量,因此您需要另一个名称。

总而言之,看看错误在说什么并做出这些改变

于 2013-10-14T19:10:16.310 回答