2013-10-14 10 views
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我只是想不出任何其他方式來解決這個問題,我一直堅持這一點。所以,如果你能幫助我,並嘗試用初學者的話來說,那對我來說意味着這個世界。非常感謝。

回答

0

你沒有在大多數地方設置正確的上下文。上下文不是MainActivity.this,你甚至沒有範圍到你的主要活動。你的onReceive中有一個上下文變量只是使用它。

從非活動/服務,您需要使用

context.getSystemService() 

你也試圖創建一個名爲intent,當一個人已經建立,所以你需要另一名變量得到了system service

在求和看看

什麼錯誤都在說,讓這些變化

0

找到這個問題的答案終於

我在的onReceive宣佈此的所有方法外

int YOURAPP_NOTIFICATION_ID = 1234567890; 
NotificationManager mNotificationManager; 

然後方法我叫:

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

Th en宣佈以下方法:

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); 
    }