因此,在此处获得一些帮助之后,appwidget已修复,但是在发送或接收任何消息之前,启动ChatRoomActivity的意图无效。
我应该如何设置它,以便在发送/接收任何消息之前意图启动该活动(显然,它没有消息,但有一个textView表示单击以打开聊天。.etc)。
我的代码:
public class ProTalkWidget extends AppWidgetProvider {
private static final String ACTION_BROADCASTWIIDGET = "ACTION_BROADCASTWIIDGET";
public static final String PROTALK_APPWIDGET_UPDATE = "PROTALK_APPWIDGET_UPDATE";
private final int REQUEST_CODE = 0;
public static final String USER_ID = "userId";
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
FirebaseAuth mAuth = FirebaseAuth.getInstance();
String msgReceiverId;
private void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
final int appWidgetId) {
//Construct the RemoteViews object
final RemoteViews views;
views = new RemoteViews(context.getPackageName(), R.layout.pro_talk_widget);
Intent intent = new Intent(context, ProTalkWidget.class);
intent.setAction(ACTION_BROADCASTWIIDGET);
context.sendBroadcast(intent);
appWidgetManager = AppWidgetManager.getInstance(context);
appWidgetManager.updateAppWidget(appWidgetId, views);
}
@Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
if(PROTALK_APPWIDGET_UPDATE.equals(intent.getAction())){
Log.i("onReceive", "getting onReceived!");
handleMsg(intent, context);
}
}
private void handleMsg(final Intent intent, final Context ctx){
msgReceiverId = intent.getStringExtra("receiverId");
if(msgReceiverId!=null) {
String my_Id = mAuth.getCurrentUser().getUid();
final RemoteViews views;
views = new RemoteViews(ctx.getPackageName(), R.layout.pro_talk_widget);
DatabaseReference rootRef = FirebaseDatabase.getInstance().getReference();
Query query = rootRef.child("Messages").child(my_Id).child(msgReceiverId).limitToLast(1);
ValueEventListener valueEventListener = new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
for(DataSnapshot ds : dataSnapshot.getChildren()) {
Messages messages = ds.getValue(Messages.class);
String message = messages.getMessage();
String from = messages.getFrom();
Log.d("TAG", message + "+" + from);
views.setTextViewText(R.id.appwidget_message, message);
Intent mainIntent = new Intent(ctx, ChatRoomActivity.class);
if(msgReceiverId != null)
mainIntent.putExtra("profile_view_userId", msgReceiverId);
mainIntent.putExtra("username", "Ben");
PendingIntent mainPendingIntent = PendingIntent.getActivity(ctx, REQUEST_CODE, mainIntent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_layout, mainPendingIntent);
AppWidgetManager.getInstance(ctx).updateAppWidget(new ComponentName(ctx, ProTalkWidget.class), views);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {}
};
query.addListenerForSingleValueEvent(valueEventListener);
}
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
// There may be multiple widgets active, so update all of them
for (int appWidgetId : appWidgetIds) {
updateAppWidget(context, appWidgetManager, appWidgetId);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
@Override
public void onEnabled(Context context) {
// Enter relevant functionality for when the first widget is created
}
@Override
public void onDisabled(Context context) {
// Enter relevant functionality for when the last widget is disabled
}
}
打开聊天室并发送消息后,请注意意图并显示消息。
ChatroomActivity
public class ChatRoomActivity extends AppCompatActivity {
private static final String TAG = ChatRoomActivity.class.getSimpleName();
private static final int IMAGE_PICK = 1;
private String msgReceiverId;
private String msgReceiverName;
private static final int TOTAL_ITEMS = 10;
private int currentPage = 1;
private TextView chatUserName;
private TextView chatLastSeen;
private CircleImageView chatProfileImg;
private DatabaseReference rootRef;
private ImageView sendMsgBtn;
private EditText textInputET;
private RecyclerView usersMsgList;
private final List<Messages> messagesList = new ArrayList<>();
private LinearLayoutManager linearLayoutManager;
//private TabsPagerAdapter.MessagesAdapter messagesAdapter;
private SwipeRefreshLayout swipeRefreshLayout;
private int ITEM_POSITION = 0;
private String lastKey;
private String prevKey;
private StorageReference imgStorage;
FirebaseAuth mAuth;
String msgSenderId;
Toolbar appBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if(AppCompatDelegate.getDefaultNightMode() == AppCompatDelegate.MODE_NIGHT_YES){
setTheme(R.style.darkTheme);
}else{
setTheme(R.style.AppTheme);
}
setContentView(R.layout.activity_chat_room);
rootRef = FirebaseDatabase.getInstance().getReference();
mAuth = FirebaseAuth.getInstance();
msgSenderId = mAuth.getCurrentUser().getUid();
msgReceiverId = getIntent().getExtras().getString("profile_view_userId");
msgReceiverName = getIntent().getExtras().getString("username");
sendMsgBtn = findViewById(R.id.input_text_btn);
textInputET = findViewById(R.id.input_text);
ProTalkApplication.getInstance().messagesAdapter = new TabsPagerAdapter.MessagesAdapter(messagesList);
usersMsgList = findViewById(R.id.users_messages_list);
linearLayoutManager = new LinearLayoutManager(this);
usersMsgList.setHasFixedSize(true);
usersMsgList.setLayoutManager(linearLayoutManager);
usersMsgList.setAdapter(ProTalkApplication.getInstance().messagesAdapter);
swipeRefreshLayout = findViewById(R.id.swipeRefreshLayout);
imgStorage = FirebaseStorage.getInstance().getReference();
fetchMsg();
Intent widgetIntent = new Intent(this,ProTalkWidget.class);
//send value
widgetIntent.putExtra("receiverID", msgReceiverName);
sendBroadcast(widgetIntent);
appBar = findViewById(R.id.chat_appbar);
setSupportActionBar(appBar);
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setDisplayShowCustomEnabled(true);
LayoutInflater inflater = (LayoutInflater) this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View actionBarView = inflater.inflate(R.layout.chat_bar, null);
actionBar.setCustomView(actionBarView);
chatUserName = findViewById(R.id.chat_profile_name);
chatLastSeen = findViewById(R.id.chat_last_seen);
chatProfileImg = findViewById(R.id.chat_profile_img);
chatUserName.setText(msgReceiverName);
sendMsgBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendMsg();
}
});
swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
@Override
public void onRefresh() {
currentPage++;
ITEM_POSITION = 0;
fetchMoreMsg();
}
});
rootRef.child("User").child(msgReceiverId).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
String online = dataSnapshot.child("online").getValue().toString().trim();
final String userImg = dataSnapshot.child("thumbnail").getValue().toString();
if (online.equals("true")) {
chatLastSeen.setText(R.string.online);
} else {
GetTimeAgo getTime = new GetTimeAgo();
long lastSeen = Long.parseLong(online);
String lastOnline = getTime.getTimeAgo(lastSeen, getApplicationContext());
//
chatLastSeen.setText(lastOnline);
}
Picasso.get().load(userImg).networkPolicy(NetworkPolicy.OFFLINE)
.placeholder(R.drawable.defaultimg).into(chatProfileImg, new Callback() {
@Override
public void onSuccess() {
}
@Override
public void onError(Exception e) {
Picasso.get().load(userImg)
.placeholder(R.drawable.defaultimg).into(chatProfileImg);
}
});
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void fetchMoreMsg() {
DatabaseReference msgRef = rootRef.child("Messages").child(msgSenderId).child(msgReceiverId);
Query msgQuery = msgRef.orderByKey().endAt(lastKey).limitToLast(10);
msgQuery.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();
if (!prevKey.equals(messageKey)) {
messagesList.add(ITEM_POSITION++, messages);
} else {
prevKey = lastKey;
}
if (ITEM_POSITION == 1) {
lastKey = messageKey;
}
ProTalkApplication.getInstance().messagesAdapter.notifyDataSetChanged();
linearLayoutManager.scrollToPositionWithOffset(10, 0);
swipeRefreshLayout.setRefreshing(false);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void fetchMsg() {
DatabaseReference msgRef = rootRef.child("Messages").child(msgSenderId).child(msgReceiverId);
Query msgQuery = msgRef.limitToLast(currentPage * TOTAL_ITEMS);
msgQuery.addChildEventListener(new ChildEventListener() {
@Override
public void onChildAdded(DataSnapshot dataSnapshot, String s) {
Messages messages = dataSnapshot.getValue(Messages.class);
String messageKey = dataSnapshot.getKey();
ITEM_POSITION++;
if (ITEM_POSITION == 1) {
lastKey = messageKey;
prevKey = messageKey;
}
messagesList.add(messages);
ProTalkApplication.getInstance().messagesAdapter.notifyDataSetChanged();
usersMsgList.scrollToPosition(messagesList.size() - 1);
swipeRefreshLayout.setRefreshing(false);
Intent intent = new Intent(ChatRoomActivity.this, ProTalkWidget.class);
intent.setAction(ProTalkWidget.PROTALK_APPWIDGET_UPDATE);
intent.putExtra("senderId", msgSenderId);
intent.putExtra("receiverId", msgReceiverId);
sendBroadcast(intent);
}
@Override
public void onChildChanged(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onChildRemoved(DataSnapshot dataSnapshot) {
}
@Override
public void onChildMoved(DataSnapshot dataSnapshot, String s) {
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
private void sendMsg() {
String msgTxt = textInputET.getText().toString();
if (TextUtils.isEmpty(msgTxt)) {
Toast.makeText(ChatRoomActivity.this, R.string.please_write_a_msg, Toast.LENGTH_SHORT).show();
} else {
String sender_message_ref = "/Messages/" + msgReceiverId + "/" + msgSenderId;
String receiver_message_ref = "/Messages/" + msgSenderId + "/" + msgReceiverId;
DatabaseReference userMsgKey = rootRef.child("Messages").child(msgReceiverId)
.child(msgSenderId).push();
String push_id = userMsgKey.getKey();
Map msgTxtBody = new HashMap();
msgTxtBody.put("message", msgTxt);
msgTxtBody.put("from", msgSenderId);
msgTxtBody.put("seen", false);
msgTxtBody.put("type", "text");
msgTxtBody.put("time", ServerValue.TIMESTAMP);
Map msgBodyDetails = new HashMap();
msgBodyDetails.put(sender_message_ref + "/" + push_id, msgTxtBody);
msgBodyDetails.put(receiver_message_ref + "/" + push_id, msgTxtBody);
rootRef.updateChildren(msgBodyDetails, new DatabaseReference.CompletionListener() {
@Override
public void onComplete(DatabaseError databaseError, DatabaseReference databaseReference) {
if (databaseError != null) {
Log.d(TAG, databaseError.getMessage().toString());
}
textInputET.setText("");
}
});
}
}
}
再次感谢!