2016-09-29 61 views
-1

我在清单文件中添加了一些像AACTION_POWER_CONNECTED的itent,我想在充电器连接时获得通知。这是我的代码。在广播接收器中获取通知

public class AwesomeReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Toast.makeText(context, "Inside onReceive", Toast.LENGTH_LONG).show(); 
     NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); 
     mBuilder.setSmallIcon(R.drawable.ic_launcher); 
     mBuilder.setContentTitle("This is A Notification"); 
     mBuilder.build(); 

    } 
} 

我每次连接充电器时都收到Toast,但没有收到通知。由于我在Android中是全新的,我不知道如何实现这一点。

+1

请在将它发布到社交网站之前查看您的代码。 :P –

+1

P.S.我在讲吐司的消息。 :D –

+0

您忘记了通知通知。 –

回答

0

试试这个代码:

public class AwesomeReceiver extends BroadcastReceiver { 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     Toast.makeText(context, "Inside onReceive", Toast.LENGTH_LONG).show(); 
     NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context); 
     mBuilder.setSmallIcon(R.drawable.ic_launcher); 
     mBuilder.setContentTitle("This is A Notification"); 

     NotificationManager mNotificationManager = 
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
     mNotificationManager.notify(mId, mBuilder.build()); 
    } 
} 

其实你创建的通知对象,但从来没有发射吧:) 所以,你只需用notify()打电话剩余。

+0

什么是'mId',在这里? –

+0

@Firdoeshkhan分配给每个通知的唯一ID。现在,你可以传递0 –