我希望在检索到任何推送通知时自动刷新列表视图,该列表视图包含所有推送通知消息。我可以点击一下按钮但不能自动刷新 我正在通过firebase获得推送通知。
这是我的主要活动代码
package com.example.romil.mypushexample;
import android.content.Context;
import android.content.Intent;
import android.support.v7.app.ActionBar;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import com.google.firebase.iid.FirebaseInstanceId;
import com.google.firebase.messaging.FirebaseMessaging;
import java.util.ArrayList;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import static java.security.AccessController.getContext;
public class MainActivity extends AppCompatActivity implements NotificationAddedListener {
ListView listView;
UserSessionManager sessionManager;
API realtrackerApi;
ArrayList<GetNotificationListOutput> data;
MyFirebaseMessagingService myFirebaseMessagingService;
int listItemCount;
Notification_Adapter adapter;
boolean notificationStatus=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView=(ListView)findViewById(R.id.notification_listView);
sessionManager=new UserSessionManager(getApplicationContext());
realtrackerApi=GlobalMethods.getRealtrackerAPI(this);
// message=myFirebaseMessagingService.getMessage();
// image=myFirebaseMessagingService.getImage();
findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),Push_Notification.class);
startActivity(i);
}
});
findViewById(R.id.showNotification).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RetroCallForGettingNotificationList();
listView.setVisibility(View.VISIBLE);
}
});
findViewById(R.id.refreshNotification).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
RetroCallForGettingNotificationList2();
}
});
if (getIntent().getExtras() != null) {
for (String key : getIntent().getExtras().keySet()) {
String value = getIntent().getExtras().getString(key);
if (key.equals("AnotherActivity") && value.equals("True")) {
Intent intent = new Intent(this, AnotherActivity.class);
intent.putExtra("value", value);
startActivity(intent);
finish();
}
}
}
subscribeToPushService();
}
private void subscribeToPushService() {
FirebaseMessaging.getInstance().subscribeToTopic("news");
Log.d("AndroidBash", "Subscribed");
Toast.makeText(MainActivity.this, "Subscribed", Toast.LENGTH_SHORT).show();
String token = FirebaseInstanceId.getInstance().getToken();
// Log and toast
Log.d("AndroidBash", token);
Toast.makeText(MainActivity.this, token, Toast.LENGTH_SHORT).show();
}
public void bindUI(ArrayList<GetNotificationListOutput> data){
this.data=data;
try{
if(data!=null) {
int listSize = data.size();
adapter = new Notification_Adapter(this, R.layout.notification_list_item, data);
listView.setAdapter(adapter);
//listItemCount=listView.getCount();
}
//setListViewHeightBasedOnChildren(listView);
}
catch (Exception e){
Toast.makeText(getApplicationContext(),""+e,Toast.LENGTH_SHORT).show();
}
}
public void refreshList(ArrayList<GetNotificationListOutput> listData){
listItemCount=listView.getCount();
int listSize=listData.size();
if(listItemCount < listSize){
GetNotificationListOutput obj=listData.get(listSize-1);
data.add(obj);
adapter.notifyDataSetChanged();
}
}
public static void setListViewHeightBasedOnChildren(ListView listView) {
try{
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null)
return;
int desiredWidth = View.MeasureSpec.makeMeasureSpec(listView.getWidth(), View.MeasureSpec.UNSPECIFIED);
int totalHeight = 0;
View view = null;
for (int i = 0; i < listAdapter.getCount(); i++) {
view = listAdapter.getView(i, view, listView);
if (i == 0)
view.setLayoutParams(new ViewGroup.LayoutParams(desiredWidth, ActionBar.LayoutParams.WRAP_CONTENT));
view.measure(desiredWidth, View.MeasureSpec.UNSPECIFIED);
totalHeight += view.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
listView.setLayoutParams(params);
}
catch (Exception e){
}
}
public void RetroCallForGettingNotificationList(){
try{
if(GlobalMethods.isConnectedToInternet(getApplicationContext(),false)) {
String token=sessionManager.getToken();
Call<ArrayList<GetNotificationListOutput>> add_notification_outputCall= realtrackerApi.GetNotificationList(token);
add_notification_outputCall.enqueue(new Callback<ArrayList<GetNotificationListOutput>>() {
@Override
public void onResponse(Call<ArrayList<GetNotificationListOutput>> call, Response<ArrayList<GetNotificationListOutput>> response) {
if(response.isSuccessful() && response.body() != null){
bindUI(response.body());
}
}
@Override
public void onFailure(Call<ArrayList<GetNotificationListOutput>> call, Throwable t) {
Log.e("Retro Error:","on failure");
}
});
}
}
catch (Exception e){
Log.e("Retro Error:",""+e);
}
}
public void RetroCallForGettingNotificationList2(){
try{
if(GlobalMethods.isConnectedToInternet(getApplicationContext(),false)) {
String token=sessionManager.getToken();
Call<ArrayList<GetNotificationListOutput>> add_notification_outputCall= realtrackerApi.GetNotificationList(token);
add_notification_outputCall.enqueue(new Callback<ArrayList<GetNotificationListOutput>>() {
@Override
public void onResponse(Call<ArrayList<GetNotificationListOutput>> call, Response<ArrayList<GetNotificationListOutput>> response) {
if(response.isSuccessful() && response.body() != null){
refreshList(response.body());
}
}
@Override
public void onFailure(Call<ArrayList<GetNotificationListOutput>> call, Throwable t) {
Log.e("Retro Error:","on failure");
}
});
}
}
catch (Exception e){
Log.e("Retro Error:",""+e);
}
}
@Override
public void notificationAdded(boolean val) {
RetroCallForGettingNotificationList2();
}
}
这是我的Firebase支持类,
package com.example.romil.mypushexample;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
import com.google.firebase.messaging.FirebaseMessagingService;
import com.google.firebase.messaging.RemoteMessage;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
/**
* Created by romil on 22/4/17.
*/
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "FCM Service";
String message;
String imageUri;
Bitmap bitmap;
String TrueOrFlase;
API realtrackerApi;
UserSessionManager sessionManager;
MainActivity mActivity;
NotificationAddedListener addedListener;
public void getActivityObjetM(){
addedListener.notificationAdded(true);
}
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
// TODO: Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated.
Log.d(TAG, "From: " + remoteMessage.getFrom());
//Log.d(TAG, "Notification Message Body: " + remoteMessage.getNotification().getBody());
// Log.i(TAG,remoteMessage.getNotification().getBody());
realtrackerApi=GlobalMethods.getRealtrackerAPI(this);
sessionManager=new UserSessionManager(this);
remoteMessage.getData();
Log.i(TAG, "Message data payload: " + remoteMessage.getData());
if (remoteMessage.getData().size() > 0) {
Log.i(TAG, "Message data payload: " + remoteMessage.getData());
message = remoteMessage.getData().get("message");
imageUri = remoteMessage.getData().get("image");
bitmap = getBitmapfromUrl(imageUri);
TrueOrFlase = remoteMessage.getData().get("AnotherActivity");
sendNotification(message, bitmap, TrueOrFlase);
getActivityObjetM();
}
if (remoteMessage.getNotification() != null) {
Log.i(TAG, "Message Notification Body: " + remoteMessage.getNotification().getBody());
}
}
private void sendNotification(String messageBody, Bitmap image, String TrueOrFalse) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.putExtra("AnotherActivity", TrueOrFalse);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
.setLargeIcon(image)/*Notification icon image*/
.setSmallIcon(R.drawable.testimage1)
.setContentTitle(messageBody)
.setStyle(new NotificationCompat.BigPictureStyle()
.bigPicture(image))/*Notification with Image*/
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
public Bitmap getBitmapfromUrl(String imageUrl) {
try {
URL url = new URL(imageUrl);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap bitmap = BitmapFactory.decodeStream(input);
return bitmap;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
}
}