2013-10-12 23 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。這個解決方案可以很容易地擴展以允許您顯示通知。

相關問題