2013-10-12 38 views
0

我想这样做,当有人插入耳机时会出现通知图标。我已经做到了这一点,当手机打开时,这会启动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 
+0

您能否详细说明您的问题。您需要通知的地方?请在此添加更多代码。 –

+0

@androiduser当用户连接耳机时,我确实需要一个通知图标。我希望通知出现在手机的最上面(通知区域,将通知区域拉下来)我已经有了代码写和它的作品。 (用它更新了主要问题)但是我只想让用户在耳机插入时运行该代码。我不希望该应用启动或任何其他功能,只是为了显示该图标。 – Fernando

回答

0

正如我在写your last question,在您的清单中侦听ACTION_HEADSET_PLUG广播添加<receiver>。该documentation显示Intent演员,你可以用它来看看这款耳机在(state)堵塞等

+0

我明白了。使用这个接收器。 '<接收机机器人: “BootReciever” 名称=> <意图滤波器> \t \t \t <动机器人:名称= “android.intent.ACTION_HEADSET_PLUG”/> \t \t \t \t “但是,我会如何做出如果其他声明说明如何处理这件事。和哪里。这就是让我困惑的问题 – Fernando

+0

@FernandoRamirez:我不知道你在说什么。你“想要这样做,当有人插入耳机通知图标出现”。这需要在'BroadcastReceiver'的'onReceive()'方法中设置十几行代码来侦听“ACTION_HEADSET_PLUG”广播。 – CommonsWare

+0

我只需要知道如何使它在后台工作,就像无需打开应用程序就可以检测到它一样。就像这个新问题一样。我已经解决了除此之外的所有问题,这是我的最后一次。 http://stackoverflow.com/questions/19368767/how-to-call-this-even-when-the-app-hasnt-even-started – Fernando

0

我发布一个解决方案,允许您监视耳机状态(有线和蓝牙),over here。这个解决方案可以很容易地扩展以允许您显示通知。

相关问题