Ниже приведено действие, а Checkforrecivingcall () - это метод вызова вызывающего действия на другой телефон пользователя. Каков наилучший способ активировать вызов, когда приложение работает в фоновом режиме или не работает? Может кто-то помочь мне с этим? Будем благодарны за ваши предложения. Спасибо
package com.example.game.videochat;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import com.firebase.ui.database.FirebaseRecyclerAdapter;
import com.firebase.ui.database.FirebaseRecyclerOptions;
import com.google.android.material.bottomnavigation.BottomNavigationView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.Picasso;
import androidx.appcompat.app.AppCompatActivity;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
public class ContactsActivity extends AppCompatActivity {
private FirebaseAuth mauth;
private String currentUserID;
private DatabaseReference contactsRef ,usersRef,rootRef;
private String username="",profileimage="" ;
private String calledBy="";
private FirebaseUser currentuser;
BottomNavigationView navView;
RecyclerView myContactList;
ImageView findPeopleBtn ;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_contacts);
navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(navigationItemSelectedListener);
rootRef=FirebaseDatabase.getInstance().getReference();
mauth =FirebaseAuth.getInstance();
currentUserID=mauth.getCurrentUser().getUid();
System.out.println("111111111111111111"+currentUserID);
currentuser=mauth.getCurrentUser();
contactsRef= FirebaseDatabase.getInstance().getReference().child("contacts");
usersRef= FirebaseDatabase.getInstance().getReference().child("users");
findPeopleBtn=findViewById(R.id.find_people_btn);
myContactList=findViewById(R.id.contactList);
myContactList.setLayoutManager(new LinearLayoutManager(getApplicationContext()));
findPeopleBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Intent findPeopleIntent =new Intent(ContactsActivity.this, FindPeopleActivity.class);
startActivity(findPeopleIntent);
}
});
}
private BottomNavigationView.OnNavigationItemSelectedListener navigationItemSelectedListener =
new BottomNavigationView.OnNavigationItemSelectedListener()
{
@Override
public boolean onNavigationItemSelected(@NonNull MenuItem menuItem)
{
switch(menuItem.getItemId())
{
case R.id.navigation_home:
// Intent mainIntent =new Intent(ContactsActivity.this, ContactsActivity.class);
//startActivity(mainIntent);
break;
case R.id.navigation_settings:
Intent mainSettingsIntent=new Intent(ContactsActivity.this, SettingsActivity.class);
startActivity(mainSettingsIntent);
break;
case R.id.navigation_notifications:
Intent mainNotificationsIntent=new Intent(ContactsActivity.this,NotificationsActivity.class);
startActivity(mainNotificationsIntent);
break;
case R.id.navigation_logout:
FirebaseAuth.getInstance().signOut();
Intent mainLogoutIntent=new Intent(ContactsActivity.this,RegistrationActivity.class);
startActivity(mainLogoutIntent);
finish();
break;
case R.id.navigation_about:
Intent AboutIntent=new Intent(ContactsActivity.this,AboutActivity.class);
startActivity(AboutIntent);
break;
}
return true;
}
};
@Override
protected void onStart()
{
super.onStart();
checkForRecievingCall();
validateUser();
if(currentuser!=null)
{
System.out.println("startttttt contact");
updateUserStatus("online");
}
FirebaseRecyclerOptions<Contacts> options
= new FirebaseRecyclerOptions.Builder<Contacts>()
.setQuery(contactsRef.child(currentUserID), Contacts.class)
.build();
FirebaseRecyclerAdapter<Contacts,ContactsViewHolder> firebaseRecyclerAdapter
=new FirebaseRecyclerAdapter<Contacts, ContactsViewHolder>(options)
{
@Override
protected void onBindViewHolder(@NonNull final ContactsViewHolder holder, int i, @NonNull final Contacts contacts)
{
final String listUserID =getRef(i).getKey();
usersRef.child(listUserID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.exists())
{
username=dataSnapshot.child("name").getValue().toString();
profileimage=dataSnapshot.child("image").getValue().toString();
holder.usernameTxt.setText(username);
Picasso.get().load(profileimage).into(holder.profileImageView);
holder.profileImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
Intent settingsintent =new Intent(ContactsActivity.this,PopUp.class);
startActivity(settingsintent);
}
});
}
if(dataSnapshot.child("userstate").hasChild("status"))
{
String user_status =dataSnapshot.child("userstate").child("status").getValue().toString();
String user_date_status=dataSnapshot.child("userstate").child("date").getValue().toString();
String user_time_status =dataSnapshot.child("userstate").child("time").getValue().toString();
if(user_status.equals("online"))
{
holder.online_green_dot.setVisibility(View.VISIBLE);
holder.callbtn.setEnabled(true);
holder.last_seen.setVisibility(View.GONE);
}
else if(user_status.equals("offline"))
{
holder.online_green_dot.setVisibility(View.INVISIBLE);
holder.last_seen.setVisibility(View.VISIBLE);
holder.last_seen.setText("Last Seen "+user_time_status );
holder.callbtn.setEnabled(false);
}
}
holder.callbtn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
Intent callingintent =new Intent(ContactsActivity.this ,CallingActivity.class);
callingintent.putExtra("visit_user_id",listUserID);
startActivity(callingintent);
}
});
}
@Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
@NonNull
@Override
public ContactsViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
{
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.contact_design,parent,false);
ContactsViewHolder viewHolder =new ContactsViewHolder(view);
return viewHolder;
}
};
myContactList.setAdapter(firebaseRecyclerAdapter);
firebaseRecyclerAdapter.startListening();
}
@Override
protected void onStop()
{
super.onStop();
if(currentuser!=null)
{
System.out.println("Contact stopppppppp");
updateUserStatus("offline");
}
}
@Override
protected void onDestroy()
{
super.onDestroy();
if(currentuser!=null)
{
System.out.println("Contact destryyyyyyy");
updateUserStatus("offline");
}
}
@Override
protected void onResume() {
super.onResume();
if(currentuser!=null)
{
System.out.println("Resummme contact");
updateUserStatus("online");
}
}
@Override
protected void onRestart()
{
super.onRestart();
if(currentuser!=null)
{
System.out.println("Contact reeeeeeeeeeeestart");
updateUserStatus("online");
}
}
public static class ContactsViewHolder extends RecyclerView.ViewHolder
{
TextView usernameTxt;
Button callbtn ;
ImageView profileImageView,online_green_dot;
TextView last_seen ;
public ContactsViewHolder(@NonNull View itemView)
{
super(itemView);
usernameTxt=itemView.findViewById(R.id.name_contact);
callbtn=itemView.findViewById(R.id.call_btn);
profileImageView=itemView.findViewById(R.id.image_contact);
online_green_dot=itemView.findViewById(R.id.onl9_green_dot);
last_seen=itemView.findViewById(R.id.contact_lastSEEn);
}
}
private void validateUser()
{
DatabaseReference reference = FirebaseDatabase.getInstance().getReference();
reference.child("users").child(currentUserID).addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(!dataSnapshot.exists())
{
Intent settingsintent =new Intent(ContactsActivity.this,SettingsActivity.class);
startActivity(settingsintent);
finish();
}
}
@Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
private void checkForRecievingCall()
{
usersRef.child(currentUserID)
.child("Ringing")
.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.hasChild("ringing"))
{
calledBy=dataSnapshot.child("ringing").getValue().toString();
Intent callingintent =new Intent(ContactsActivity.this ,CallingActivity.class);
callingintent.putExtra("visit_user_id",calledBy);
startActivity(callingintent);
}
}
@Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
public void updateUserStatus(String state)
{
String savecurrentTime,saveCurrentDate;
Calendar calendar = Calendar.getInstance();
SimpleDateFormat currentdate=new SimpleDateFormat("MMM dd,yyyy");
saveCurrentDate =currentdate.format(calendar.getTime());
SimpleDateFormat currenttime=new SimpleDateFormat("hh:mm a");
savecurrentTime =currenttime.format(calendar.getTime());
HashMap<String,Object> onlinestate =new HashMap<>();
onlinestate.put("time",savecurrentTime);
onlinestate.put("date",saveCurrentDate);
onlinestate.put("status",state);
rootRef.child("users").child(currentUserID)
.child("userstate")
.updateChildren(onlinestate);
}
}
И это видео Вызов действия должен вызываться при изменении в дочернем узле базы данных Firedabse другого пользователя.
package com.example.game.videochat;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import android.Manifest;
import android.content.Intent;
import android.graphics.Camera;
import android.opengl.GLSurfaceView;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import com.opentok.android.OpentokError;
import com.opentok.android.Publisher;
import com.opentok.android.PublisherKit;
import com.opentok.android.Session;
import com.opentok.android.Stream;
import com.opentok.android.Subscriber;
import com.opentok.android.SubscriberKit;
import pub.devrel.easypermissions.AfterPermissionGranted;
import pub.devrel.easypermissions.EasyPermissions;
public class VideoChatActivity extends AppCompatActivity implements
Session.SessionListener, PublisherKit.PublisherListener
{
private static String API_Key="46653752";
private static String SESSION_ID="2_MX40NjY1Mzc1Mn5-MTU4NzI3NzIwNjI5NX5naERpakw1Y3V3T21BQXhWRU5ySk5DQXd-fg";
private static String TOKEN="T1==cGFydG5lcl9pZD00NjY1Mzc1MiZzaWc9MGVmOWNjYzZlMTk3YjI5ZjgyOGVlZTE5MTg1ZjkzZTNmYmUwNzUxZDpzZXNzaW9uX2lkPTJfTVg0ME5qWTFNemMxTW41LU1UVTROekkzTnpJd05qSTVOWDVuYUVScGFrdzFZM1YzVDIxQlFYaFdSVTV5U2s1RFFYZC1mZyZjcmVhdGVfdGltZT0xNTg3Mjc3MjE5Jm5vbmNlPTAuMTUyNDc2NjA3ODM4MTM3NDMmcm9sZT1wdWJsaXNoZXImZXhwaXJlX3RpbWU9MTU4OTg2OTIxOCZpbml0aWFsX2xheW91dF9jbGFzc19saXN0PQ==";
private static final String LOG_TAG=VideoChatActivity.class.getSimpleName();
private static final int RC_VIDEO_APP_PERM=124;
private FrameLayout mPublisherViewController;
private FrameLayout mSubscriberViewController;
private Session mSession;
private Publisher mPublisher ;
private Subscriber mSubscriber;
private ImageView close_Video_Chat_Btn;
DatabaseReference userRef;
private String userID="";
ImageView swap_camera,mute_button ,unmute_button;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_chat);
swap_camera =findViewById(R.id.swap_btn);
mute_button =findViewById(R.id.mute_btn);
unmute_button =findViewById(R.id.unmute_btn);
swap_camera.setVisibility(View.VISIBLE);
mute_button.setVisibility(View.VISIBLE);
unmute_button.setVisibility(View.VISIBLE);
close_Video_Chat_Btn=findViewById(R.id.close_video_chat_btn);
userRef= FirebaseDatabase.getInstance().getReference().child("users");
userID= FirebaseAuth.getInstance().getCurrentUser().getUid();
close_Video_Chat_Btn.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
userRef.addValueEventListener(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot)
{
if(dataSnapshot.child(userID).hasChild("Ringing"))
{
userRef.child(userID).child("Ringing").removeValue();
if(mPublisher!=null)
{
mPublisher.destroy();
}
if(mSubscriber!=null)
{
mSubscriber.destroy();
}
Intent ContactIntent=new Intent(VideoChatActivity.this,ContactsActivity.class);
startActivity(ContactIntent);
finish();
}
if(dataSnapshot.child(userID).hasChild("Calling"))
{
userRef.child(userID).child("Calling").removeValue();
if(mPublisher!=null)
{
mPublisher.destroy();
}
if(mSubscriber!=null)
{
mSubscriber.destroy();
}
Intent ContactIntent=new Intent(VideoChatActivity.this,ContactsActivity.class);
startActivity(ContactIntent);
finish();
}
else
{
if(mPublisher!=null)
{
mPublisher.destroy();
}
if(mSubscriber!=null)
{
mSubscriber.destroy();
}
//Intent ContactIntent=new Intent(VideoChatActivity.this,ContactsActivity.class);
//startActivity(ContactIntent);
//finish();
}
}
@Override
public void onCancelled(DatabaseError databaseError)
{
}
});
}
});
swap_camera.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
mPublisher.cycleCamera();
}
});
mute_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
mPublisher.setPublishAudio(false);
}
});
unmute_button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v)
{
mPublisher.setPublishAudio(true);
}
});
requestPermission();
}
//****Activity Cycle
@Override
protected void onPause() {
Log.d(LOG_TAG, "onPause");
super.onPause();
if (mSession != null) {
mSession.onPause();
}
}
@Override
protected void onResume() {
Log.d(LOG_TAG, "onResume");
super.onResume();
if (mSession != null) {
mSession.onResume();
}
}
//****Activity Cycle**********
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
EasyPermissions.onRequestPermissionsResult(requestCode,permissions,grantResults,VideoChatActivity.this);
}
@AfterPermissionGranted(RC_VIDEO_APP_PERM)
private void requestPermission()
{
String[] perms = {Manifest.permission.INTERNET,Manifest.permission.CAMERA,Manifest.permission.RECORD_AUDIO};
if(EasyPermissions.hasPermissions(this,perms))
{
mPublisherViewController =findViewById(R.id.publisherContainer);
mSubscriberViewController =findViewById(R.id.subscriber_container);
//1.initialialize and connect to the session
mSession =new Session.Builder(this,API_Key, SESSION_ID).build();
mSession.setSessionListener(VideoChatActivity.this);
mSession.connect(TOKEN);
}
else
{
EasyPermissions.requestPermissions(this,"Hey this App Needs Mic and Camera Permission",RC_VIDEO_APP_PERM,perms);
}
}
@Override
public void onStreamCreated(PublisherKit publisherKit, Stream stream)
{
}
@Override
public void onStreamDestroyed(PublisherKit publisherKit, Stream stream)
{
}
@Override
public void onError(PublisherKit publisherKit, OpentokError opentokError)
{
}
//2. Publishing a stream to the session
@Override
public void onConnected(Session session)
{
Log.i(LOG_TAG,"Session Connected");
mPublisher =new Publisher.Builder(this).build();
mPublisher.setPublisherListener(VideoChatActivity.this);
mPublisherViewController.addView(mPublisher.getView());
if(mPublisher.getView() instanceof GLSurfaceView)
{
((GLSurfaceView)mPublisher.getView()).setZOrderOnTop(true);
}
mSession.publish(mPublisher);
}
@Override
public void onDisconnected(Session session)
{
Log.i(LOG_TAG,"Stream Disconnected ");
}
//2. Recieving the published stream to the session
@Override
public void onStreamReceived(Session session, Stream stream)
{
Log.i(LOG_TAG,"Stream Recieved ");
if(mSubscriber==null)
{
mSubscriber=new Subscriber.Builder(this,stream).build();
mSession.subscribe(mSubscriber);
mSubscriberViewController.addView(mSubscriber.getView());
}
}
@Override
public void onStreamDropped(Session session, Stream stream)
{
Log.i(LOG_TAG,"Stream Dropped ");
if(mSubscriber!=null)
{
mSubscriber=null;
mSubscriberViewController.removeAllViews();
}
}
@Override
public void onError(Session session, OpentokError opentokError)
{
Log.i(LOG_TAG,"Stream Error ");
}
@Override
public void onPointerCaptureChanged(boolean hasCapture)
{
}
}