2014-12-02 56 views
0

我有一個關於android推送通知的查詢,並且我在另一個stackoverflow帖子中詢問過它,並且我沒有從中獲得太多幫助[Query regarding Android push notifications。所以我再次發佈它,它如下:在接收到Android推送通知時更新UI

我有一個Android應用程序,接收來自Google推送通知服務的推送通知。當我點擊收到的通知時,會打開一個顯示此消息的UI,它是一個列表視圖。現在,當用戶收到推送通知時,並假設此屏幕已打開,應自動刷新UI,以顯示最新的通知。有誰能讓我知道我該如何解決這個問題?

下面是我的代碼,我已經實現了:

Java代碼來接收通知:

import java.util.Timer; 
import java.util.TimerTask; 

import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.PendingIntent; 
import android.content.Context; 
import android.content.Intent; 
import android.os.PowerManager; 
import android.util.Log; 

import com.example.foodu.R; 
import com.google.android.gcm.GCMBaseIntentService; 

public class GCMIntentService extends GCMBaseIntentService { 

    private static final String TAG = "GCM ::Service"; 

    // Use your PROJECT ID from Google API into SENDER_ID 
    public static final String SENDER_ID = "53340195486"; 

    public GCMIntentService() { 
     super(SENDER_ID); 
    } 

    @Override 
    protected void onError(Context arg0, String errorId) { 
     Log.e(TAG, "onError: errorId=" + errorId); 
    } 

    @Override 
    protected void onMessage(Context context, Intent data) { 
     String message; 
     // Message from PHP server 
     message = data.getStringExtra("message"); 
     // Open a new activity called GCMMessageView 
     Intent intent = new Intent(this, com.example.foodu.Notification.class); 
     // Pass data to the new activity 
     intent.putExtra("message", message); 
     intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     // Starts the activity on notification click 
     PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 
       PendingIntent.FLAG_UPDATE_CURRENT); 
     // Create the notification with a notification builder 
     Notification notification = new Notification.Builder(this) 
       .setSmallIcon(R.drawable.ic_logo) 
       .setWhen(System.currentTimeMillis()) 
       .setContentTitle("Deals") 
       .setContentText(message).setContentIntent(pIntent) 
       .getNotification(); 
     // Remove the notification on click 
     notification.flags |= Notification.FLAG_AUTO_CANCEL; 

     NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 
     manager.notify(R.string.app_name, notification); 

     { 
      // Wake Android Device when notification received 
      PowerManager pm = (PowerManager) context 
        .getSystemService(Context.POWER_SERVICE); 
      final PowerManager.WakeLock mWakelock = pm.newWakeLock(
        PowerManager.FULL_WAKE_LOCK 
          | PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH"); 
      mWakelock.acquire(); 

      // Timer before putting Android Device to sleep mode. 
      Timer timer = new Timer(); 
      TimerTask task = new TimerTask() { 
       public void run() { 
        mWakelock.release(); 
       } 
      }; 
      timer.schedule(task, 5000); 
     } 

    } 

    @Override 
    protected void onRegistered(Context arg0, String registrationId) { 
     Log.i(TAG, "onRegistered: registrationId=" + registrationId); 

    } 

    @Override 
    protected void onUnregistered(Context arg0, String registrationId) { 
     Log.i(TAG, "onUnregistered: registrationId=" + registrationId); 
    } 

} 

爲當用戶點擊的通知,將推出相應的活動代碼:

import java.io.FileInputStream; 
import java.io.FileOutputStream; 
import java.io.ObjectInputStream; 
import java.io.ObjectOutputStream; 
import java.text.SimpleDateFormat; 
import java.util.LinkedList; 
import java.util.Locale; 
import java.util.StringTokenizer; 
import java.util.TimeZone; 

import com.example.foodu.R; 
import com.example.foodu.R.drawable; 
import com.example.foodu.R.id; 
import com.example.foodu.R.layout; 
import com.example.foodu.R.menu; 
import com.google.android.gcm.GCMRegistrar; 

import android.support.v7.app.ActionBarActivity; 
import android.app.AlertDialog; 
import android.content.ClipData; 
import android.content.ClipboardManager; 
import android.content.ContentResolver; 
import android.content.ContentValues; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.net.Uri; 
import android.os.Bundle; 
import android.provider.CalendarContract; 
import android.util.Log; 
import android.view.ActionMode; 
import android.view.ActionMode.Callback; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemLongClickListener; 
import android.widget.ListView; 
import android.widget.TextView; 
import android.widget.Toast; 

public class Notification extends ActionBarActivity { 

    LinkedList<NotificationData> notificationList = new LinkedList<NotificationData>(); 
    ListView listView = null; 
    NotificationListAdapter adaptor; 
    ActionMode mActionMode; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_notification); 

     overridePendingTransition(R.anim.trans_left_in, R.anim.trans_left_out); 

     listView = (ListView) findViewById(R.id.listView1); 

     // Retrive the data from GCMIntentService.java 
     Intent i = getIntent(); 
     String message = i.getStringExtra("message"); 
     //getDataForDisplay(); 
     if(message!=null) 
     { 
      parseData(message); 
     }else{ 
     getDataToDisplay(); 
     } 
     adaptor = new NotificationListAdapter(getApplicationContext(), notificationList); 
     listView.setAdapter(adaptor); 
     TextView emptyText = (TextView) findViewById(R.id.empty); 
     emptyText.setText("No Events Yet!"); 
     listView.setEmptyView(emptyText); 
     listView.setOnItemLongClickListener(new OnItemLongClickListener() { 
      public boolean onItemLongClick(AdapterView<?> parent, View view, 
        int position, long id) { 
       onListitemSelect(position); 
       view.setSelected(true); 
       return true; 
      } 
     }); 
    } 

    @Override 
    protected void onStart() { 
     // TODO Auto-generated method stub 
     super.onStart(); 


     adaptor.notifyDataSetChanged(); 
    } 

    @Override 
    protected void onRestart() { 
     // TODO Auto-generated method stub 
     super.onRestart(); 
    } 

    void writeToFile(){ 
     FileOutputStream fos; 
     try { 
     fos = openFileOutput("varun", Context.MODE_PRIVATE); 
     ObjectOutputStream oos = new ObjectOutputStream(fos); 
     oos.writeObject(notificationList); 
     oos.close(); 
    }catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    void readFromFile(){ 
     try{ 
     FileInputStream fis = openFileInput("varun"); 
     ObjectInputStream ois = new ObjectInputStream(fis); 
     LinkedList<NotificationData> local = (LinkedList<NotificationData>) ois.readObject(); 
     ois.close(); 

     for (int i = 0; i < local.size(); i++) { 
      notificationList.add(local.get(i)); 
     } 

     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
    } 


    private void getDataToDisplay() { 
     // TODO Auto-generated method stub 
     readFromFile(); 
    } 

    private void parseData(String message) { 
     try { 
      int len = 0; 
      String[] stringArr = new String[100]; 
      StringTokenizer st = new StringTokenizer(message, "."); 
      len = st.countTokens(); 
      for (int i = 0; i < len; i++) { 
       if (st.hasMoreTokens()) { 
        stringArr[i] = st.nextToken(); 
       } 
      } 

      NotificationData data = new NotificationData(); 
      data.title = stringArr[0]; 
      data.venue = stringArr[1]; 
      data.date = stringArr[2]; 
      data.time = stringArr[3]; 
      notificationList.add(data); 
      readFromFile(); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 
    private void getDateToDisplay() { 
     // TODO Auto-generated method stub 

    } 



    @Override 
    protected void onPause() { 
     // TODO Auto-generated method stub 
     super.onPause(); 
     writeToFile(); 
    } 

    @Override 
    public boolean onCreateOptionsMenu(Menu menu) { 
     getMenuInflater().inflate(R.menu.notificationmenu, menu); 
     return true; 
    } 

    @Override 
    public boolean onOptionsItemSelected(MenuItem item) { 
     int id = item.getItemId(); 
     if (id == R.id.action_settings) { 
      return true; 
     } 
     if(id == R.id.action_register){ 
      registerDevice(); 
      return true; 
     } 
     return super.onOptionsItemSelected(item); 
    } 

    private void registerDevice() { 
     try { 
      GCMRegistrar.checkDevice(this); 
      GCMRegistrar.checkManifest(this); 

      GCMRegistrar 
        .register(Notification.this, GCMIntentService.SENDER_ID); 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

    private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() { 

     @Override 
     public boolean onCreateActionMode(ActionMode mode, Menu menu) { 
      MenuInflater inflater = mode.getMenuInflater(); 
      inflater.inflate(R.menu.notificationcontext, menu); 
      return true; 
     } 

     @Override 
     public boolean onPrepareActionMode(ActionMode mode, Menu menu) { 
      return false; 
     } 

     @Override 
     public boolean onActionItemClicked(ActionMode mode, MenuItem item) { 

      switch (item.getItemId()) { 
      case R.id.menu_calender: 
       addToCalender(); 
       mode.finish(); 
       return true; 
      case R.id.menu_delete: 
       //deleteData(); 
       showAlertBox(); 
       return false; 
      case R.id.menu_share: 
       shareDate(); 
       mode.finish(); 
       return true; 
      case R.id.menu_copy: 
       copyToClip(); 
       mode.finish(); 
       return true; 
      default: 
       return false; 
      } 
     } 

     @Override 
     public void onDestroyActionMode(ActionMode mode) { 
      mActionMode = null; 
      adaptor.removeSelection(); 
     } 
    }; 

    void onListitemSelect(int position) { 
     adaptor.toggleSelection(position); 
     boolean hasCheckedItems = adaptor.getSelectedCount() > 0; 

     if (hasCheckedItems && mActionMode == null) { 
      mActionMode = startActionMode((Callback) mActionModeCallback); 
     } else if (!hasCheckedItems && mActionMode != null) { 
      mActionMode.finish(); 
     } 

     if (mActionMode != null) 
      mActionMode.setTitle(String.valueOf(adaptor.getSelectedCount())); 

    } 

    protected void showAlertBox() { 
     // TODO Auto-generated method stub 
     AlertDialog.Builder builder1 = new AlertDialog.Builder(Notification.this); 
     builder1.setMessage("Delete " + adaptor.getSelectedIds().size()+ " events?"); 
     builder1.setCancelable(true); 
     builder1.setIcon(R.drawable.alert); 
     builder1.setTitle("Caution"); 
     builder1.setIcon(android.R.drawable.ic_dialog_alert); 
     builder1.setPositiveButton("Yes", 
       new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) { 
       deleteData(); 
       mActionMode.finish(); 
      } 
     }); 
     builder1.setNegativeButton("No", 
       new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int id) { 
       dialog.cancel(); 
      } 
     }); 

     AlertDialog alert11 = builder1.create(); 
     alert11.show(); 
    } 

    protected void copyToClip() { 

     StringBuilder shareText = new StringBuilder(); 
     for (int i = 0; i < adaptor.getSelectedIds().size(); i++) { 
      NotificationData data = notificationList 
        .get(adaptor.getSelectedIds().keyAt(i)); 
      shareText.append(data.title + " " + data.venue + " " + data.date 
        + " " + data.time); 
      shareText.append("\n"); 
     } 

     ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE); 
     ClipData clip = ClipData.newPlainText("Notification App", shareText); 
     clipboard.setPrimaryClip(clip); 

     Toast.makeText(getApplicationContext(), "Data copied to ClipBoard", 
       Toast.LENGTH_LONG).show(); 
    } 

    protected void shareDate() { 

     StringBuilder shareText = new StringBuilder(); 
     for (int i = 0; i < adaptor.getSelectedIds().size(); i++) { 
      NotificationData data = notificationList 
        .get(adaptor.getSelectedIds().keyAt(i)); 
      shareText.append(data.title + " " + data.venue + " " + data.date 
        + " " + data.time); 
      shareText.append("\n"); 
     } 
     String share = shareText.toString(); 
     Intent sendIntent = new Intent(); 
     sendIntent.setAction(Intent.ACTION_SEND); 
     sendIntent.putExtra(Intent.EXTRA_TEXT, share); 
     sendIntent.setType("text/plain"); 
     startActivity(sendIntent); 
    } 

    protected void deleteData() { 
     int count = 0; 
     int startPoint = adaptor.getSelectedIds().keyAt(0); 
     for (int i = 0; i < adaptor.getSelectedIds().size(); i++) { 
      adaptor.remove(notificationList.get(startPoint)); 
      count++; 
     } 

     String message = " Event"; 
     if(count>1) 
     { 
      message = " Events"; 
     } 
     Toast.makeText(getApplicationContext(), 
       count + message+" deleted", Toast.LENGTH_LONG) 
       .show(); 

    } 

    private void addToCalender() { 

     try { 
      int count = 0; 
      for (int i = 0; i < adaptor.getSelectedIds().size(); i++) { 
       NotificationData data = notificationList 
         .get(adaptor.getSelectedIds().keyAt(i)); 

       ContentResolver cr = getApplicationContext() 
         .getContentResolver(); 
       ContentValues values = new ContentValues(); 

       String myDate = data.date + " " + data.time; 

       String timeArr[] = data.time.split("to"); 

       SimpleDateFormat sfd = new SimpleDateFormat(
         "' Date: 'MM/dd/yyyy 'Time: 'hh a", Locale.getDefault()); 

       long time = sfd.parse(myDate).getTime(); 
       values.put(CalendarContract.Events.DTSTART, time); 
       if (timeArr.length > 0) { 
        String endTime = timeArr[1]; 
        SimpleDateFormat timeFormat = new SimpleDateFormat(
          "' Date: 'MM/dd/yyyy hh a", Locale.getDefault()); 
        long endtime = timeFormat.parse(data.date + " " + endTime) 
          .getTime(); 
        values.put(CalendarContract.Events.DTEND, endtime); 
       } 

       values.put(CalendarContract.Events.TITLE, data.title); 
       values.put(CalendarContract.Events.DESCRIPTION, data.venue); 
       TimeZone timeZone = TimeZone.getDefault(); 
       values.put(CalendarContract.Events.EVENT_TIMEZONE, 
         timeZone.getID()); 
       values.put(CalendarContract.Events.CALENDAR_ID, 1); 
       Uri uri = cr 
         .insert(CalendarContract.Events.CONTENT_URI, values); 
       count++; 
      } 

      String message = " Event"; 
      if(count>1) 
      { 
       message = " Events"; 
      } 

      Toast.makeText(getApplicationContext(), 
        count + message + " added to Calender", Toast.LENGTH_LONG) 
        .show(); 
     } catch (Exception e) { 
      e.printStackTrace(); 
     } 
    } 

} 
+0

看看這個http://developer.android.com/reference/android/app/Notification.Builder.html#setContentIntent(android.app.PendingIntent) – MeetTitan 2014-12-02 02:26:22

+0

當您收到推送通知時發送廣播接收器,並且那將是你的回調。 – neferpitou 2015-03-15 11:10:06

回答

2

使用LocalBroadcastManager

檢查下面的代碼/步驟

1)添加在您的活動(UI刷新活動)

private BroadcastReceiver mMyBroadcastReceiver; 

然後,

2)的onResume

@Override 
protected void onResume() { 
    // TODO Auto-generated method stub 
    super.onResume(); 

    mMyBroadcastReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) 
    { 
       // Here you can refresh your listview or other UI 
      Toast.makeText(getApplicationContext(), "Receiver", 2000).show(); 
     } 
    }; 
try { 

LocalBroadcastManager.getInstance(this).registerReceiver(mMyBroadcastReceiver,new IntentFilter("your_action")); 

} catch (Exception e) 
{ 
     // TODO: handle exception 
     e.printStackTrace(); 
}} 

//和您的其他代碼

3)然後取消註冊onPause

@Override 
protected void onPause() { 
    // TODO Auto-generated method stub 
    super.onPause(); 
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mMyBroadcastReceiver); 
} 

4)最後加入你的GCM reciver類。 首先檢查你的活動是可見的或不使用靜態變量

if visible add 
     Intent gcm_rec = new Intent("your_action"); LocalBroadcastManager.getInstance(arg0).sendBroadcast(gcm_rec); 
else 
    use Notification Manager for notification. 

我覺得這是很簡單的刷新你的ListView UI /調用取出方法,最好的方法。

+0

你可以給一些工作示例源代碼ji ..我也試過,但是,它不適合我.. – harikrishnan 2016-10-03 10:33:18

+0

@harikrishnan:是的,但明天。使用示例代碼網址更新我的答案。 – 2016-10-03 11:29:15

+0

謝謝govind ..如果一點工作示例項目意味着它最有用。 – harikrishnan 2016-10-05 05:58:53