如何去除立即通知在android系统 [英] how to remove notification instantly in android

查看:118
本文介绍了如何去除立即通知在android系统的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用我显示的通知。从服务我发送登录到JSON的时间。它在服务器上检查是否有任何新的数据可用与否如果是然后通过JSON我收到没有新的数据,而最新数据的时间,我在显示它的通知。如果我们点击通知其进入仪表板的活动页面,改变的时机拉泰什数据的时间。
但问题是,当我点击的通知,这是第一次进入仪表板的活动,然后更改时间。对于第2次点击通知后的原因是要离开。谁能告诉我如何在我的情况下,第一次点击后删除通知?
这里是我的条件code调用一个新的通知:

 公共类ReviewUpdateService扩展IntentService {私人Notification.Builder earthquakeNotificationBuilder;
公共静态最终诠释NOTIFICATION_ID = 1;私人字符串USER_ID;
的JSONObject jsonData;
私人静态字符串share_ pref_time_file =time_file;
私人静态字符串share_ pref_file =json_file;
串service_notification;
INT no_of_notify;  公共ReviewUpdateService(){
        超级(ReviewUpdateService);
  }  私人AlarmManager alarmManager;
  私人的PendingIntent alarmIntent;
公共无效的onCreate(){
    super.onCreate();
    alarmManager =(AlarmManager)getSystemService(Context.ALARM_SERVICE);
    共享preferences preFS = getShared preferences(share_ pref_file,
            Context.MODE_PRIVATE);
    串strJson = prefs.getString(jsondata,);    如果(!strJson.equals()){
        尝试{
            jsonData =新的JSONObject(strJson);
            USER_ID = jsonData.getString(LoginActivity.KEY_UID);
        }赶上(JSONException E){            e.printStackTrace();
        }
    }    字符串ALARM_ACTION = ReviewAlarmReceiver.ACTION_REFRESH_DASHBOARD_ALARM;
    意图int​​entToFire =新意图(ALARM_ACTION);
    alarmIntent = PendingIntent.getBroadcast(在此,0,intentToFire,0);    earthquakeNotificationBuilder =新Notification.Builder(本);
    earthquakeNotificationBuilder
        .setAutoCancel(真)
        .setTicker(新评论检测)
        .setSmallIcon(R.drawable.icon_1);
}
 公共无效refreshEarthquakes(){
        //获取XML
        // URL网址;
     UserFunctions userFunctions =新UserFunctions();
     共享preferences preFS = getShared preferences(share_ pref_time_file,
                Context.MODE_PRIVATE);
    字符串formattedDate = prefs.getString(时间,);
        尝试{
                // Log.d(user_ID的USER_ID);
                // Log.d(时间,formattedDate);
                JSONObject的json_city = userFunctions
                    .getNotification(USER_ID,formattedDate);
            如果(json_city!= NULL){
        {
                尝试{
                    字符串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);
                }赶上(JSONException E){                    e.printStackTrace();
                }
            }
        如果(no_of_notify大于0){        broadcastNotification(no_of_notify,);
        }
                }        }
        最后{
        }
      }
    @覆盖
    保护无效onHandleIntent(意向意图){        INT updateFreq = 1;            INT alarmType = AlarmManager.ELAPSED_REALTIME_WAKEUP;
            长timeToRefresh = SystemClock.elapsedRealtime()+
                                 updateFreq * 60 * 1000;
            alarmManager.setInexactRepeating(alarmType,timeToRefresh,updateFreq * 60 * 1000,alarmIntent);
        refreshEarthquakes();
          意图broadcastIntent =新的Intent();
            broadcastIntent.setAction(ReviewAlarmReceiver.ACTION_REFRESH_DASHBOARD_ALARM);
            sendBroadcast(broadcastIntent);
    }私人无效broadcastNotification(INT no_of_review,弦乐服务名){    意图startActivityIntent =新意图(这一点,Da​​shboardActivity.class);
    startActivityIntent.putExtra(NotificationMessage,service_notification);
    startActivityIntent.putExtra(标记,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(这一点,0,
            startActivityIntent,PendingIntent.FLAG_UPDATE_CURRENT);
    UserFunctions userFunctions =新UserFunctions();
    如果(userFunctions.isUserLoggedIn(getApplicationContext())){
        startActivityIntent.putExtra(latest_time,service_notification);
        Log.d(latest_time,service_notification);
        startActivityIntent.putExtra(标记,1);
        earthquakeNotificationBuilder
                .setContentIntent(launchIntent)
                .setContentTitle(no_of_review ++新评论是那里)
                .setAutoCancel(真);
        // .setContentText(服务名);        如果(no_of_review→10){
            乌里ringURI = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);            earthquakeNotificationBuilder.setSound(ringURI);
        }        双vibrateLength = 100 * Math.exp(0.53 * no_of_review);
        长[] =颤动新长[] {100,100(长)vibrateLength};
        earthquakeNotificationBuilder.setVibrate(振动);        INT色;
        如果(no_of_review 2)
            颜色= Color.GREEN;
        否则如果(no_of_review小于5)
            颜色= Color.YELLOW;
        其他
            颜色= Color.RED;        earthquakeNotificationBuilder.setLights(颜色,(INT)vibrateLength,
                (INT)vibrateLength);        NotificationManager notificationManager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);        notificationManager.notify(NOTIFICATION_ID,
                earthquakeNotificationBuilder.getNotification());
    }其他{
        NotificationManager notificationManager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
        }
}
 }

这就是我如何改变请求的时间JSON在仪表盘活动:

 保护无效onNewIntent(意向意图){    DashboardActivity.this.finish();    // -----开始新的仪表板,以通知----点击    意图I =新意图(DashboardActivity.this,DashboardActivity.class);
    捆绑额外= intent.getExtras();
    如果(临时演员!= NULL){
        startService(新意图(这一点,ReviewUpdateService.class));
        如果(extras.containsKey(NotificationMessage))
        {
            formattedDate = extras.getString(NotificationMessage);        }
        如果(extras.containsKey(标记))
        {
            标志= extras.getInt(标记);        }
        如果(extras.containsKey(notificationID))
        {
            NOTIFICATION_ID = extras.getInt(notificationID);        }
    }
如果(旗!= 0){
     NotificationManager纳米=(NotificationManager)
                getSystemService(NOTIFICATION_SERVICE);
            nm.cancel(NOTIFICATION_ID);
        共享preferences preFS1 = getShared preferences(
                share_ pref_time_file,Context.MODE_PRIVATE);
        共享preferences.Editor编辑器= prefs1.edit();
        editor.remove(share_ pref_time_file);
        editor.clear();
        editor.commit();
        getApplicationContext()
                .getShared preferences(share_ pref_time_file,0).edit()
                .clear()提交()。
        共享preferences preFS2 = getShared preferences(
                share_ pref_time_file,Context.MODE_PRIVATE);
        共享preferences.Editor editor1 = prefs2.edit();
        Log.d(latest_intent_time,formattedDate);
        editor1.putString(时间,formattedDate);
        editor1.commit();
        }
    startActivity(ⅰ);    super.onNewIntent(意向);
}
公共无效的onCreate(捆绑savedInstanceState){
    super.onCreate(savedInstanceState);
     NotificationManager纳米=(NotificationManager)
                getSystemService(NOTIFICATION_SERVICE);
            nm.cancel(NOTIFICATION_ID);
            的setContentView(R.layout.dashboard);
            startService(新意图(这一点,ReviewUpdateService.class));
                    ...................
                    }
            }


解决方案

也许这个答案会帮助别人:
在仪表盘的活动我已经改变了我的时间,并保存它通过共享preferences。而在服务类中,我有检查旧时代和最新的时间相同或没有。如果它们是相同的它会删除通知,否则将通过给定的条件下火的通知。
这里是广播通知功能的code:

 私人无效broadcastNotification(INT no_of_review,弦乐服务名){    意图startActivityIntent =新意图(这一点,Da​​shboardActivity.class);
    startActivityIntent.putExtra(NotificationMessage,service_notification);
    startActivityIntent.putExtra(标记,1);
    startActivityIntent.putExtra(notificationID,NOTIFICATION_ID);
    startActivityIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    的PendingIntent launchIntent = PendingIntent.getActivity(这一点,0,
            startActivityIntent,PendingIntent.FLAG_UPDATE_CURRENT);
    UserFunctions userFunctions =新UserFunctions();
    如果(userFunctions.isUserLoggedIn(getApplicationContext())){
        / *formattedDate是保存在共享preferences日期* /
        如果(!formattedDate.equals(service_notification)){
        startActivityIntent.putExtra(latest_time,service_notification);
        Log.d(latest_time,service_notification);
        startActivityIntent.putExtra(标记,1);
        earthquakeNotificationBuilder
                .setContentIntent(launchIntent)
                .setContentTitle(no_of_review ++新评论是那里)
                .setAutoCancel(真);
        // .setContentText(服务名);        如果(no_of_review→10){
            乌里ringURI = RingtoneManager
                    .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);            earthquakeNotificationBuilder.setSound(ringURI);
        }        双vibrateLength = 100 * Math.exp(0.53 * no_of_review);
        长[] =颤动新长[] {100,100(长)vibrateLength};
        earthquakeNotificationBuilder.setVibrate(振动);        INT色;
        如果(no_of_review 2)
            颜色= Color.GREEN;
        否则如果(no_of_review小于5)
            颜色= Color.YELLOW;
        其他
            颜色= Color.RED;        earthquakeNotificationBuilder.setLights(颜色,(INT)vibrateLength,
                (INT)vibrateLength);        NotificationManager notificationManager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);        notificationManager.notify(NOTIFICATION_ID,
                earthquakeNotificationBuilder.getNotification());
    }其他{
        NotificationManager notificationManager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
        }
    }其他{
        NotificationManager notificationManager =(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.cancelAll();
        }
}

In my application i am showing a notification. From service i am sending the time of login to json. It is checking in server that is there any new data available or not if yes then through json i am getting the no of new data, and timing of latest data and i am showing it in notification. And if we click on notification it is coming into dashboard activity page and change the timing to the time of lates data. But the problem is that when i am clicking on notification, it is first coming into dashboard activity then changing the time. for that reason after 2nd time clicking notification is going away. can anyone tell me how to remove notification after 1st click in my case? Here is my code of condition to call a new notification:

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

And that is how i am changing the time of request for json In dashboard activity:

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

解决方案

Maybe this answer will help others: In dashboard activity i have changed my time and save it through shared preferences. And in service class i have check that old time and the latest time are same or not. If they are same it will remove notification otherwise it will fire notification through the given condition. here is the code of broadcast notification function:

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

这篇关于如何去除立即通知在android系统的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆