如何在android中立即删除通知

时间:2013-04-26 09:32:26

标签: android json android-intent notifications

在我的申请表中,我正在显示通知。从服务我发送登录时间到json。它正在检查服务器中是否有任何新数据可用,如果是,那么通过json我得到新数据的数量,以及最新数据的时间,我在通知中显示它。如果我们点击通知,它将进入仪表板活动页面并将时间更改为lates数据的时间。 但问题是,当我点击通知时,它首先进入仪表板活动然后改变时间。因此,在第二次点击通知消失后。谁可以告诉我如何在我的情况下第一次点击后删除通知? 这是我调用新通知的条件代码:

 public class ReviewUpdateService extends IntentService{

private Notification.Builder earthquakeNotificationBuilder;
public static final int NOTIFICATION_ID = 1;

private String user_id;
JSONObject jsonData;
private static String share_pref_time_file = "time_file";
private static String share_pref_file = "json_file";
String service_notification;
int no_of_notify;

  public ReviewUpdateService() {
        super("ReviewUpdateService");
  }

  private AlarmManager alarmManager;
  private PendingIntent alarmIntent;


public void onCreate() {
    super.onCreate();
    alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    SharedPreferences prefs = getSharedPreferences(share_pref_file,
            Context.MODE_PRIVATE);
    String strJson = prefs.getString("jsondata", "");

    if (!strJson.equals("")) {
        try {
            jsonData = new JSONObject(strJson);
            user_id = jsonData.getString(LoginActivity.KEY_UID);                
        } catch (JSONException e) {

            e.printStackTrace();
        }
    }

    String ALARM_ACTION = ReviewAlarmReceiver.ACTION_REFRESH_DASHBOARD_ALARM;
    Intent intentToFire = new Intent(ALARM_ACTION);
    alarmIntent = PendingIntent.getBroadcast(this, 0, intentToFire, 0);

    earthquakeNotificationBuilder = new Notification.Builder(this);
    earthquakeNotificationBuilder
        .setAutoCancel(true)
        .setTicker("New Review detected")
        .setSmallIcon(R.drawable.icon_1);
}
 public void refreshEarthquakes() {
        // Get the XML
        //URL url;
     UserFunctions userFunctions =  new UserFunctions();
     SharedPreferences prefs = getSharedPreferences(share_pref_time_file,
                Context.MODE_PRIVATE);
    String formattedDate = prefs.getString("time", "");
        try {           
                // Log.d("user_id", user_id);
                // Log.d("time", formattedDate);
                JSONObject json_city = userFunctions
                    .getNotification(user_id, formattedDate);
            if(json_city!=null){
        {               
                try {
                    String notify_get_id = json_city.getString(LoginActivity.KEY_NO_NOTIFY);
                    no_of_notify = Integer.parseInt(notify_get_id);
                    service_notification = json_city.getString(LoginActivity.KEY_SERVICE_NOTIFY);
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        if(no_of_notify > 0){

        broadcastNotification(no_of_notify,"");
        }
                }

        }


        finally {
        }
      }


    @Override
    protected void onHandleIntent(Intent intent) {

        int updateFreq = 1; 

            int alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
            long timeToRefresh = SystemClock.elapsedRealtime() +
                                 updateFreq*60*1000;
            alarmManager.setInexactRepeating(alarmType, timeToRefresh, updateFreq*60*1000, alarmIntent);


        refreshEarthquakes();
          Intent broadcastIntent=new Intent();
            broadcastIntent.setAction( ReviewAlarmReceiver.ACTION_REFRESH_DASHBOARD_ALARM );
            sendBroadcast( broadcastIntent );


    } 

private void broadcastNotification(int no_of_review, String service_name) {

    Intent startActivityIntent = new Intent(this, DashboardActivity.class); 
    startActivityIntent.putExtra("NotificationMessage", service_notification);
    startActivityIntent.putExtra("flag", 1);
    startActivityIntent.putExtra("notificationID", NOTIFICATION_ID);
    startActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
//  startActivityIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK| Intent.FLAG_ACTIVITY_NEW_TASK );
    PendingIntent launchIntent = PendingIntent.getActivity(this, 0,
            startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);    
    UserFunctions userFunctions = new UserFunctions();
    if (userFunctions.isUserLoggedIn(getApplicationContext())) {        
        startActivityIntent.putExtra("latest_time", service_notification);
        Log.d("latest_time", service_notification);
        startActivityIntent.putExtra("flag", 1);
        earthquakeNotificationBuilder
                .setContentIntent(launchIntent)
                .setContentTitle(no_of_review + " " + "new review is there")
                .setAutoCancel(true);
        // .setContentText(service_name);

        if (no_of_review > 10) {
            Uri ringURI = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            earthquakeNotificationBuilder.setSound(ringURI);
        }

        double vibrateLength = 100 * Math.exp(0.53 * no_of_review);
        long[] vibrate = new long[] { 100, 100, (long) vibrateLength };
        earthquakeNotificationBuilder.setVibrate(vibrate);

        int color;
        if (no_of_review < 2)
            color = Color.GREEN;
        else if (no_of_review < 5)
            color = Color.YELLOW;
        else
            color = Color.RED;

        earthquakeNotificationBuilder.setLights(color, (int) vibrateLength,
                (int) vibrateLength);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(NOTIFICATION_ID,
                earthquakeNotificationBuilder.getNotification());
    } else {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
        }
}
 } 

这就是我如何在仪表板活动中更改json请求的时间:

    protected void onNewIntent(Intent intent) {

    DashboardActivity.this.finish();

    // -----Start New Dashboard to notification clicked----

    Intent i = new Intent(DashboardActivity.this, DashboardActivity.class);       
    Bundle extras = intent.getExtras();
    if(extras != null){
        startService(new Intent(this, ReviewUpdateService.class));  
        if(extras.containsKey("NotificationMessage"))
        {
            formattedDate= extras.getString("NotificationMessage");

        }
        if(extras.containsKey("flag"))
        {
            flag= extras.getInt("flag");

        }
        if(extras.containsKey("notificationID"))
        {
            NOTIFICATION_ID= extras.getInt("notificationID");

        }
    }
if(flag != 0){              
     NotificationManager nm = (NotificationManager) 
                getSystemService(NOTIFICATION_SERVICE);
            nm.cancel(NOTIFICATION_ID);
        SharedPreferences prefs1 = getSharedPreferences(
                share_pref_time_file, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs1.edit();
        editor.remove(share_pref_time_file);
        editor.clear();
        editor.commit();
        getApplicationContext()
                .getSharedPreferences(share_pref_time_file, 0).edit()
                .clear().commit();              
        SharedPreferences prefs2 = getSharedPreferences(
                share_pref_time_file, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor1 = prefs2.edit();
        Log.d("latest_intent_time", formattedDate);
        editor1.putString("time", formattedDate);
        editor1.commit();
        }
    startActivity(i);

    super.onNewIntent(intent);
}
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
     NotificationManager nm = (NotificationManager) 
                getSystemService(NOTIFICATION_SERVICE);
            nm.cancel(NOTIFICATION_ID);
            setContentView(R.layout.dashboard);         
            startService(new Intent(this, ReviewUpdateService.class));  
                    ...................
                    }
            }

1 个答案:

答案 0 :(得分:0)

也许这个答案会对其他人有所帮助: 在仪表板活动中,我已经改变了时间并通过共享首选项保存。在服务类中,我检查旧时间和最新时间​​是否相同。如果它们相同则会删除通知,否则它将通过给定条件触发通知。 这是广播通知功能的代码:

  private void broadcastNotification(int no_of_review, String service_name) {

    Intent startActivityIntent = new Intent(this, DashboardActivity.class); 
    startActivityIntent.putExtra("NotificationMessage", service_notification);
    startActivityIntent.putExtra("flag", 1);
    startActivityIntent.putExtra("notificationID", NOTIFICATION_ID);
    startActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent launchIntent = PendingIntent.getActivity(this, 0,
            startActivityIntent, PendingIntent.FLAG_UPDATE_CURRENT);    
    UserFunctions userFunctions = new UserFunctions();
    if (userFunctions.isUserLoggedIn(getApplicationContext())) {    
        /* "formattedDate" is the date saved in shared preferences*/
        if(!formattedDate.equals(service_notification)){
        startActivityIntent.putExtra("latest_time", service_notification);
        Log.d("latest_time", service_notification);
        startActivityIntent.putExtra("flag", 1);
        earthquakeNotificationBuilder
                .setContentIntent(launchIntent)
                .setContentTitle(no_of_review + " " + "new review is there")
                .setAutoCancel(true);
        // .setContentText(service_name);

        if (no_of_review > 10) {
            Uri ringURI = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

            earthquakeNotificationBuilder.setSound(ringURI);
        }

        double vibrateLength = 100 * Math.exp(0.53 * no_of_review);
        long[] vibrate = new long[] { 100, 100, (long) vibrateLength };
        earthquakeNotificationBuilder.setVibrate(vibrate);

        int color;
        if (no_of_review < 2)
            color = Color.GREEN;
        else if (no_of_review < 5)
            color = Color.YELLOW;
        else
            color = Color.RED;

        earthquakeNotificationBuilder.setLights(color, (int) vibrateLength,
                (int) vibrateLength);

        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        notificationManager.notify(NOTIFICATION_ID,
                earthquakeNotificationBuilder.getNotification());
    } else {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
        }
    }else {
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
        }
}