I've almost built one chat app with the login functionality using Firebase. But when I clear/delete all users from Firebase, uninstall app from my device and run the app from fresh and when it install and open app, it directly login it means it redirect to MainActivty instead of StartActivity where user can login or signup. I also faced this problem before and somehow I solved it, but again I improve the project, made some other classes and now again I'm facing the same problem.
Note:
When this things happens (automatically login), in my firebase database, it creates one ID automatically in under "Users" section. Actually it should happen only when user Singup.
I implemented the Facebook login button just before an hour, but this is not the issue, I'm sure about that, so please ignore Facebook login related stuff, this issue is getting before I implemented Facebook login button.
I tell you my app structure flow: When user first time install the app, it must redirect to StartActivity. If user already installed the app and login already, but not logout and simply closes the app and again open, it can login directly, it means it will redirect to MainActivity, no need to enter thr crendetials again.
Basically, my launcher activity is MainActivity, so if new user installed the app, it redirects from MainActivity to StartActivity (which is for login/singup).
LapitChat is a application class.
I'm attaching MainActivity.java, StartActivity.java, LapitChat.java, and AndroidManifest.xml
MainActivity.java
package com.jimmytrivedi.lapitchat;
import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.facebook.login.LoginManager;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ServerValue;
public class MainActivity extends AppCompatActivity {
private FirebaseAuth mAuth;
private FirebaseUser currentUser;
private Toolbar toolbar;
private ViewPager viewPager;
private SectionsPagerAdapter sectionsPagerAdapter;
private TabLayout tabLayout;
private DatabaseReference UserDatabaseReference;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAuth = FirebaseAuth.getInstance();
currentUser = mAuth.getCurrentUser();
if (currentUser == null) {
sendTostart();
} else {
UserDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
UserDatabaseReference.child("Online").setValue("true");
}
viewPager = findViewById(R.id.viewPager);
sectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
viewPager.setAdapter(sectionsPagerAdapter);
toolbar = findViewById(R.id.mainToolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("Home");
tabLayout = findViewById(R.id.tabLayout);
tabLayout.setupWithViewPager(viewPager);
}
#Override
protected void onPause() {
super.onPause();
if (currentUser != null) {
UserDatabaseReference.child("Online").setValue(ServerValue.TIMESTAMP);
}
}
private void sendTostart() {
startActivity(new Intent(MainActivity.this, StartActivity.class));
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if (item.getItemId() == R.id.logout) {
FirebaseAuth.getInstance().signOut();
LoginManager.getInstance().logOut();
sendTostart();
}
if (item.getItemId() == R.id.settings) {
startActivity(new Intent(MainActivity.this, SettingsActivity.class));
}
if (item.getItemId() == R.id.allUsers) {
startActivity(new Intent(MainActivity.this, UsersActivity.class));
}
return true;
}
}
StartActivity.java
package com.jimmytrivedi.lapitchat;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.facebook.AccessToken;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthCredential;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FacebookAuthProvider;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class StartActivity extends AppCompatActivity {
private Button signup, exist;
private CallbackManager mCallbackManager;
private FirebaseAuth mAuth;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);
mAuth = FirebaseAuth.getInstance();
signup = findViewById(R.id.signup);
exist = findViewById(R.id.exist);
signup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(StartActivity.this, RegisterActivity.class));
}
});
exist.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(StartActivity.this, LoginActivity.class));
}
});
// Initialize Facebook Login button
mCallbackManager = CallbackManager.Factory.create();
LoginButton loginButton = findViewById(R.id.login_button);
loginButton.setReadPermissions("email", "public_profile");
loginButton.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
#Override
public void onSuccess(LoginResult loginResult) {
Log.d("wihddiewd", "facebook:onSuccess:" + loginResult);
handleFacebookAccessToken(loginResult.getAccessToken());
}
#Override
public void onCancel() {
Log.d("wihddiewd", "facebook:onCancel");
}
#Override
public void onError(FacebookException error) {
Log.d("wihddiewd", "facebook:onError", error);
}
});
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAuth.getCurrentUser();
if (currentUser != null) {
updateUI();
}
}
private void updateUI() {
startActivity(new Intent(StartActivity.this, MainActivity.class));
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Pass the activity result back to the Facebook SDK
mCallbackManager.onActivityResult(requestCode, resultCode, data);
}
private void handleFacebookAccessToken(AccessToken token) {
Log.d("wihddiewd", "handleFacebookAccessToken:" + token);
AuthCredential credential = FacebookAuthProvider.getCredential(token.getToken());
mAuth.signInWithCredential(credential)
.addOnCompleteListener(this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
if (task.isSuccessful()) {
Log.d("wihddiewd", "signInWithCredential:success");
FirebaseUser user = mAuth.getCurrentUser();
updateUI();
} else {
Log.w("wihddiewd", "signInWithCredential:failure", task.getException());
Toast.makeText(StartActivity.this, "Authentication failed.",
Toast.LENGTH_SHORT).show();
}
}
});
}
}
LapitChat.java
package com.jimmytrivedi.lapitchat;
import android.app.Application;
import android.support.annotation.NonNull;
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.ServerValue;
import com.google.firebase.database.ValueEventListener;
import com.squareup.picasso.OkHttp3Downloader;
import com.squareup.picasso.Picasso;
public class LapitChat extends Application {
private DatabaseReference UserDatabaseReference;
private FirebaseAuth mAuth;
#Override
public void onCreate() {
super.onCreate();
FirebaseDatabase.getInstance().setPersistenceEnabled(true);
Picasso.Builder builder = new Picasso.Builder(this);
builder.downloader(new OkHttp3Downloader(this, Integer.MAX_VALUE));
Picasso built = builder.build();
built.setIndicatorsEnabled(true);
built.setLoggingEnabled(true);
Picasso.setSingletonInstance(built);
mAuth = FirebaseAuth.getInstance();
if (mAuth.getCurrentUser() != null) {
UserDatabaseReference = FirebaseDatabase.getInstance().getReference().child("Users").child(mAuth.getCurrentUser().getUid());
UserDatabaseReference.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
if (dataSnapshot != null) {
UserDatabaseReference.child("Online").onDisconnect().setValue(ServerValue.TIMESTAMP);
}
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jimmytrivedi.lapitchat">
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:name=".LapitChat"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<service android:name=".FirebaseMessagingService">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".StartActivity" />
<activity
android:name=".RegisterActivity"
android:parentActivityName=".StartActivity" />
<activity
android:name=".LoginActivity"
android:parentActivityName=".StartActivity" />
<activity
android:name=".SettingsActivity"
android:parentActivityName=".MainActivity" />
<activity
android:name=".StatusActivity"
android:parentActivityName=".SettingsActivity" />
<activity
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:theme="#style/Base.Theme.AppCompat" /> <!-- optional (needed if default theme has no action bar) -->
<activity
android:name=".UsersActivity"
android:parentActivityName=".MainActivity" />
<activity android:name=".ProfileActivity">
<intent-filter>
<action android:name="com.jimmytrivedi.lapitchat_TARGET_NOTIFICATION" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<activity
android:name=".ChatActivity"
android:parentActivityName=".MainActivity" />
<meta-data android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id"/>
<activity android:name="com.facebook.FacebookActivity"
android:configChanges=
"keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
</application>
</manifest>
Thanks for reading and waiting for your help. Thank you so much!
This is happening because from Android 6.0 (API level 23) the automatic backup is set by default to true. So to solve this, you need to add the following lines of code, in your AndroidManifest.xml file:
android:allowBackup="false"
android:fullBackupContent="false"
See here more informations.
Related
I want to create an app that set/reset a timer to reproduce a song if the mobile spend 8 hours with the screen off.
I want to create a service that receive ACTION_SCREEN_OFF, but the problem is that when the app is killed from recent apps, the service is killed. I try with START_STICKY but the service is not restarted (onCreate is called sometimes but not onStart Command). I try to set in Manifest but the receiver must be register.
By now I only want that receiver detect ACTION_SCREEN_OFF.
I Have this code:
MainScreen.java (MainActivity)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainScreen extends Activity implements View.OnClickListener{
public static final String MSG_TAG = "NoSleepMore";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
findViewById(R.id.start_service_button).setOnClickListener(this);
findViewById(R.id.stop_service_button).setOnClickListener(this);
}
#Override
public void onClick(View v){
Intent intent = new Intent(getApplicationContext(), LockService.class);
switch (v.getId()) {
case R.id.start_service_button:
Log.e(MSG_TAG,"Service started");
//starts service for the given Intent
startService(intent);
break;
case R.id.stop_service_button:
Log.e(MSG_TAG,"Service stopped");
//stops service for the given Intent
stopService(intent);
break;
}
}
}
LockService.java
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
public class LockService extends Service {
#Override
public IBinder onBind(Intent arg0) {
Log.i(MainScreen.MSG_TAG, "onBind()" );
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(MainScreen.MSG_TAG, "Service Created");
/* Filtrar Acciones Capturadas */
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
// Listener
final BroadcastReceiver mReceiver = new ScreenReceiver();
// Registar Listener
registerReceiver(mReceiver, filter);
return Service.START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
Log.i(MainScreen.MSG_TAG, "onCreate()");
}
#Override
public void onDestroy() {
Log.i(MainScreen.MSG_TAG, "onDestroy()");
}
}
ScreenRecive.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
Log.i(MainScreen.MSG_TAG,"OnReceive->");
// Log Handel
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
Log.i(MainScreen.MSG_TAG,"Screen action OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
Log.i(MainScreen.MSG_TAG,"Screen action ON");
}else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
Log.e(MainScreen.MSG_TAG,"Action UserPresent");
}
}
}
AndroidManifext.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="es.mangel.nosleepmore">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_SCREEN_ON"/>
<action android:name="android.intent.action.ACTION_SCREEN_OFF"/>
<action android:name="android.intent.action.ACTION_USER_PRESENT"/>
</intent-filter>
</receiver>
<service android:name=".LockService" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</service>
</application>
</manifest>
The Main activity is just two buttons.
BTW I just need that run over Android 8.0.
I'm creating an application to scan for Bluetooth low energy devices and have implemented the scan functionality, however, am getting the error:
fail to start le scan - SecurityException thrown: java.lang.SecurityException: Need ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission to get scan results
I have the required permissions in my manifest, however, am still getting this error. I have done some research and read that SDK versions > 23 require some kind of manual checking for permissions, is this the correct solution to this problem or is there a simpler alternative?
package com.example.jake.bluetooth;
import android.Manifest;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothManager;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Handler;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
private static final int REQUEST_ENABLE_BT = 1;
private String ble_not_supported = "BLE not supported";
private BluetoothManager bluetoothManager;
private BluetoothAdapter mBluetoothAdapter;
private Button startScanBtn;
private boolean mScanning;
private Handler mHandler;
private BluetoothAdapter.LeScanCallback mLeScanCallBack;
private static final long SCAN_PERIOD = 10000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bluetoothManager = (BluetoothManager) getSystemService(Context.BLUETOOTH_SERVICE);
mBluetoothAdapter = bluetoothManager.getAdapter();
startScanBtn = findViewById(R.id.start_scan);
mHandler = new Handler();
mScanning = true;
mLeScanCallBack = new BluetoothAdapter.LeScanCallback() {
#Override
public void onLeScan(final BluetoothDevice bluetoothDevice, int rssi, byte[] bytes) {
}
};
if (mBluetoothAdapter == null || !mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
}
if(!getPackageManager().hasSystemFeature(PackageManager.FEATURE_BLUETOOTH_LE)){
Toast.makeText(this, ble_not_supported, Toast.LENGTH_SHORT).show();
finish();
}
startScanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
scanLeDevice(mScanning);
}
});
}
private void scanLeDevice(final boolean enable){
if(enable){
mHandler.postDelayed(new Runnable() {
#Override
public void run() {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallBack);
}
},SCAN_PERIOD);
mScanning = true;
mBluetoothAdapter.startLeScan(mLeScanCallBack);
} else {
mScanning = false;
mBluetoothAdapter.stopLeScan(mLeScanCallBack);
}
}
}
No it's not enough to just have it in your manifest. You must also explicitly ask the user at runtime. See https://developer.android.com/training/permissions/requesting for more info.
It's 2020, but I respond to this question anyway so maybe it will be helpfull for someone. I encauntered this problem and I resolved it with adding this line of code in onCreate call: requestPermissions(new String[]{android.Manifest.permission.ACCESS_COARSE_LOCATION}, PERMISSION_REQUEST_COARSE_LOCATION);. You're just asking to the user to allow access location. Obvisully PERMISSION_REQUEST_COARSE_LOCATION is defined like: private static final int PERMISSION_REQUEST_COARSE_LOCATION = 1;.
I've a app to use BLE and this is my AndroidManifest.xml file, all works fine.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.bluetoothlowenergy_gatt_sendreceive">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".ServiceActivity"></activity>
</application>
</manifest>
You should uninstall previous build:
Run > Edit Configurations > Application > Before launch section(on the right)
Create a gradle-aware Make add :app:uninstallAll
Aim
To login to my Admin.xml via AdminLogin.xml
Flow of Classes
AdminLoginActivity ---> AdminActivity
AdminLoginActivityClass
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AdminLoginActivity extends AppCompatActivity {
private Toolbar jAdminToolbar;
private EditText jAdminID;
private EditText jAdminPassword;
private Button jAdminLoginBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_login);
jAdminToolbar = (Toolbar) findViewById(R.id.adminLoginToolbar);
setSupportActionBar(jAdminToolbar);
getSupportActionBar().setTitle("Admin Login");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
jAdminID = (EditText) findViewById(R.id.adminLoginName);
jAdminPassword = (EditText) findViewById(R.id.adminLoginPassword);
jAdminLoginBtn = (Button) findViewById(R.id.adminLoginBtn);
jAdminLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String adminLoginID = jAdminID.getText().toString();
String adminLoginPassword = jAdminPassword.getText().toString();
if(adminLoginID.equals("admin")&& adminLoginPassword.equals("admin")){
Intent intentAdmin = new Intent(AdminLoginActivity.this, AdminActivity.class);
intentAdmin.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intentAdmin);
finish();
}else{
Toast.makeText(AdminLoginActivity.this, "Failed Login", Toast.LENGTH_SHORT).show();
return;
}
}
});
}
}
AdminActivityClass
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class AdminActivity extends AppCompatActivity {
private FirebaseAuth mAdminAuth;
private Toolbar jAdminToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
mAdminAuth = FirebaseAuth.getInstance();
jAdminToolbar = (Toolbar) findViewById(R.id.adminToolbar);
setSupportActionBar(jAdminToolbar);
getSupportActionBar().setTitle("Administrator");
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAdminAuth.getCurrentUser();
if(currentUser == null){
sendUserToStartPage();
}
}
private void sendUserToStartPage(){
Intent intentStart = new Intent(AdminActivity.this, StartActivity.class);
startActivity(intentStart);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_admin_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.mainSignOutBtn){
FirebaseAuth.getInstance().signOut();
sendUserToStartPage();
}
if(item.getItemId() == R.id.mainViewContactsBtn){
Intent intentViewContacts = new Intent(AdminActivity.this, AllUsersActivity.class);
startActivity(intentViewContacts);
}
return true;
}
}
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:name=".SecurityApp"
android:allowBackup="true"
android:icon="#mipmap/appiconone"
android:label="#string/app_name"
android:roundIcon="#mipmap/appiconone"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".StartActivity" />
<activity
android:name=".ResidentRegistrationActivity"
android:parentActivityName=".StartActivity" />
<activity
android:name=".AdminLoginActivity"
android:parentActivityName=".LoginActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.lenovo.securityapp.LoginActivity" />
</activity>
<activity
android:name=".LoginActivity"
android:parentActivityName=".StartActivity" />
<activity
android:name=".SettingsActivity"
android:parentActivityName=".MainActivity" />
<activity
android:name=".DetailsActivity"
android:parentActivityName=".SettingsActivity" />
<activity
android:name=".AllUsersActivity"
android:parentActivityName=".MainActivity" />
<activity android:name=".UserProfileActivity" />
<activity
android:name=".HelpInformationActivity"
android:parentActivityName=".StartActivity" />
<activity android:name=".AdminActivity" />
</application>
Problem
ToolBar on AdminLogin does not allow me to return to LoginActivity when I select the back Button
Admin Login does not work despite entering the hardcoded input for the Admin Name and Password. After clicking on the Login button, the app prompts out a White layout for a few seconds I am brought back to the StartActivity and the Toast message does not show "Failed Login".
SOLUTION
The problem was because the "AdminActivityClass" had
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAdminAuth.getCurrentUser();
if(currentUser == null){
sendUserToStartPage();
}
}
private void sendUserToStartPage(){
Intent intentStart = new Intent(AdminActivity.this, StartActivity.class);
startActivity(intentStart);
finish();
}
Since the Admin login was hardcoded, the currentUser within the FirebaseUser currentUser = mAdminAuth.getCurrentUser(); was set to null. This caused the activity to be sent back to the start page (sendUserToStartPage();)
After posting your full set of code, you should be doing the following.
comment out the sendUserToStartPage(); inside of the currentuser == null and then try.
why? Because the user IS null. why? because you hard coded it into the code. The user admin with password admin does not exist in your Firebase (and if it does, you never checked it prior) so when you sign in, you do not create a session for admin, therefore the current user is null.
try doing this
if ("admin".equals(adminLoginID)) {
if ("admin".equals(adminLoginPassword)) {
//goto activity
}
} else {
//not admin
}
this might be better actually
if (("admin".equals(adminLoginID)) && ("admin".equals(adminLoginPassword))) {
//goto activity
} else {
//not admin
}
or even this....
if (("admin".equals(jAdminID.getText().toString().trim())) && ("admin".equals(jAdminPassword.getText().toString().trim()))) {
//goto activity
} else {
//not admin
}
Try this example in the manifest.
Youre manifest for the activities are missing a theme.
Also, its missed the meta-data.
<activity
android:name=".Leagues.CreateLeague"
android:label="Create League"
android:parentActivityName=".MainActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme2">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.aaa.bbb.MainActivity" />
</activity>
Try like this smartly
take a String variable globally and declare and intialise them
in next step you need to add validations
String str_admin="admin";
if ((str_admin.equals(adminLoginID)) && (str_admin.equals(adminLoginPassword))) {
//pass reference of activity which you want to open it
} else {
//not admin
}
Happy to help yoh
I want to learn how to use services in my application, but Service doesn't work! Here is my code.
This is the sample code i have written for the services. Suggest me if i am missing anything.Thanks in Advance
package com.example.utente.test;
import android.content.Intent
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener {
final String[] numeri =
{"1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"
,"1","2","1","2",
"1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2",
"1","2","1","2"};
long inizio;
long fine;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inizio = System.currentTimeMillis();
Intent i= new Intent(getApplicationContext(), MyService.class);
startService(i);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.riga, numeri);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onResume()
{
super.onResume();
inizio = System.currentTimeMillis();
// new MyService(inizio);
}
#Override
public void onItemClick(AdapterView<?> adattatore, final View componente,
int posizione, long id )
{
Toast.makeText(getApplicationContext(), numeri[posizione],
Toast.LENGTH_LONG).show();
}
}
package com.example.utente.test;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service
{
long inizio;
long fine;
long tempo;
boolean ciclo=true;
int prova=0;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// This is where you would place your code that you want in the
background
// Putting your while loop here will make sure it runs when the app is closed
Toast.makeText(getApplicationContext() ,"COMMAND",
Toast.LENGTH_LONG).show();
while(ciclo)
{
fine = System.currentTimeMillis();
tempo = (fine-inizio)/1000;
if(tempo>10 && prova==0)
{
prova++;
Toast.makeText(getApplicationContext(), "10s",
Toast.LENGTH_LONG).show();
}
}
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
<?xml version="1.0" encoding="utf-8"?>
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.utente.test">
<service
android:name="MyService" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Add your Service to your Manifest as followed:
<service android:name=".MyService" />
I want start a service when my dialer (default or stock dialer) open. My service just toasts a message. How to start the service for dialer. The startService command is working in MainActivity, but it is not working while a dialer is open.
My code is shown below:
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.chatheads">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.DIAL_ACTION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" />
<activity android:name=".SecondActivity"></activity>
</application>
</manifest>
MainActivity.java
package com.example.chatheads;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.DialerKeyListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button startService,stopService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService=(Button)findViewById(R.id.startService);
stopService=(Button)findViewById(R.id.stopService);
if(getIntent().getAction().equals(Intent.ACTION_DIAL)) {
Intent intent = new Intent(getBaseContext(), MyService.class);
startService(intent);
}
startService.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getApplication(), MyService.class));
}
});
stopService.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getApplication(), MyService.class));
}
});
}
}
Myservice.java
package com..service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
intent.getStringExtra("MY_MESSAGE");
//stopSelf();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
This code is not working. The service starting when the startService calling in MainActivity. But when a dialer open it not working.
I think maybe you can try changing getApplication () to MainActivity.this.
And I think you need to jump from the dialer to MainActivity to get the service started