0

我有通知,并且在点击通知时应该使用intent来放置值。此值应在其他Activity的BroadcastReceiver中接收。任何帮助如何解决?下面有我的代码:如何把通知中的额外使用意图通知BroadCast

public void showNotification(){ 
     Intent intent = new Intent(MainActivity.ACTION_NEW_MSG); 
     intent.putExtra(MainActivity.MSG_FIELD, "TEST VALUES"); 
     intent.setAction(Intent.ACTION_MAIN); 
     intent.addCategory(Intent.CATEGORY_LAUNCHER); 
     ComponentName cn = new ComponentName(getApplicationContext(), MainActivity.class); 
     intent.setComponent(cn); 
     sendBroadcast(intent); 
     contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0); 


    notification = new NotificationCompat.Builder(getApplicationContext()) 
        .setCategory(Notification.CATEGORY_PROMO) 
        .setContentTitle("TEST VALUE") 
        .setContentText("Please click for") 
        .setSmallIcon(R.drawable.ic_launcher) 
        .setAutoCancel(false) 
        .setVisibility(1) 
        .setSubText("Time left: " + millisUntilFinished/1000) 
        .addAction(android.R.drawable.ic_menu_view, "View details", contentIntent) 
        .setContentIntent(contentIntent) 
        .setPriority(Notification.PRIORITY_HIGH) 
        .setVibrate(new long[]{0}).build(); 
      notificationManager = 
        (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
      int notification_id = 666; 
      notificationManager.notify(notification_id, notification); 
     } 

及以下MainActivity:

private void initReceiver() { 
    myReceiver = new MyReceiver(); 
    IntentFilter filter = new IntentFilter(ACTION_NEW_MSG); 
    registerReceiver(myReceiver, filter); 
} 

public class MyReceiver extends BroadcastReceiver { 
    @Override 
    public void onReceive(Context context, Intent intent) { 
     if (intent.getAction().equals(ACTION_NEW_MSG)) { 
      String message = intent.getStringExtra(MSG_FIELD); 
      Toast.makeText(getApplicationContext(),message, Toast.LENGTH_LONG).show(); 
      Log.e("TESTING", "TESTING"); 
     } 
    } 
} 
+1

你使用当前代码得到了什么问题? –

+0

我的问题是,我看不到任何吐司,或日志。在我看来,向Intent提供额外数据存在问题。 – user5523912

回答

0

你为什么不使用一个服务,而不是一个reciever的?你可以像这样创建意图:Intent i = new Intent(MainActivity.this, MyService.class); 你可以把意外和行动。 在服务类中,只是覆盖此功能:

@Override 
    public int onStartCommand(Intent intent, int flags, int startId){ 
     if (intent != null) { 
      final String action = intent.getAction(); 
     } 
    }