Android app not opening from launch activity - android

I have an app which first logs in the user with firebase and then proceeds to the mainactivity. Initially I didn't have the log in feature and so the app began from mainactivity. Once I added the login activity, and tested it with my phone, it worked just fine. But after reinstalling the app, it doesn't open from login activity. It starts from the mainactivity and asks for permissions.
I have done the necessary changes to Android manifest and im sure it's right.
Yet it doesn't work.
And I'm a beginner so please explain any solutions in detail.
Thanks!
PS: im using Google location services. mypp has to request permissions for fine location, internal storage,etc.
These permissions are located in Mainactivity.
Code of MainActivity and LoginActivity is given below:
package com.sitepoint.example02;
import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import java.io.File;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.FusedLocationProviderApi;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.firebase.auth.FirebaseAuth;
import static com.sitepoint.example02.R.id.initiate;
import static com.sitepoint.example02.R.id.textView16;
public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
private FirebaseAuth auth;
private static final String TAG = "MainActivity";
private GoogleApiClient mGoogleApiClient;
private LocationRequest mLocationRequest;
private boolean permissionIsGranted = false;
private FusedLocationProviderApi LocationProvider = LocationServices.FusedLocationApi;
private static final int MY_PERMISSIONS_REQUEST_FINE_LOCATION = 101;
private static final int MY_PERMISSIONS_REQUEST_COARSE_LOCATION = 102;
private Uri file;
TextView vv;
String latt;
String longit;
Button b;
int threshld1 = 0;
int threshld = 0;
int skipped = 0;
int locationdata=0;
String close;
int i = 0;
Button myresdone;
private ImageView whitee;
private ImageView logo;
private Button register;
private Button skipbut;
private Button takePictureButton;
private ImageView imageView;
Boolean a;
TextView signout;
TextView txt16;
String useridd="";
//private FirebaseAuth user;
private ProgressBar pbb;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//user=FirebaseAuth.getInstance();
auth=FirebaseAuth.getInstance();
pbb=(ProgressBar)findViewById(R.id.progressBar2) ;
signout=(TextView)findViewById(R.id.signout);
signout.setEnabled(false);
signout.setVisibility(View.INVISIBLE);
close = getIntent().getStringExtra("c");
if (close == "c")
finish();
whitee = (ImageView) findViewById(R.id.wholepage);
logo = (ImageView) findViewById(R.id.logo);
takePictureButton = (Button) findViewById(R.id.button_image);
register = (Button) findViewById(R.id.button3);
txt16=(TextView)findViewById(textView16);
myresdone = (Button) findViewById(R.id.button6);
skipbut = (Button) findViewById(R.id.button5);
skipbut.setEnabled(false);
skipbut.setVisibility(View.INVISIBLE);
vv = (TextView) findViewById(R.id.textView);
takePictureButton.setEnabled(false);
register.setEnabled(false);
register.setVisibility(View.INVISIBLE);
takePictureButton.setVisibility(View.INVISIBLE);
vv.setEnabled(false);
myresdone.setVisibility(View.INVISIBLE);
myresdone.setEnabled(false);
//getting user account id
useridd = auth.getCurrentUser().getUid();
vv.setVisibility(View.INVISIBLE);
new CountDownTimer(1000, 1000) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
/* if (system==null) {
auth.signOut();
register.setVisibility(View.INVISIBLE);
register.setEnabled(false);
initiate.setVisibility(View.VISIBLE);
if (i == 1 && threshld1 != 1 && threshld != 1)
initiate.setEnabled(true);
} else {
useridd = auth.getCurrentUser().getUid();
txt16.setText(useridd);*/
a = fileExistance(useridd + ".txt");
if (!a) {
register.setVisibility(View.VISIBLE);
if(i == 1 && threshld1 != 1 && threshld != 1)
register.setEnabled(true);
} else {
skipbut.setVisibility(View.VISIBLE);
takePictureButton.setVisibility(View.VISIBLE);
myresdone.setVisibility(View.VISIBLE);
pbb.setVisibility(View.VISIBLE);
if (i == 1 && threshld1 != 1 && threshld != 1 && locationdata == 1) {
takePictureButton.setEnabled(true);
skipbut.setEnabled(true);
signout.setEnabled(true);
signout.setVisibility(View.VISIBLE);
myresdone.setEnabled(true);
pbb.setVisibility(View.INVISIBLE);
}
vv.setEnabled(true);
vv.setVisibility(View.VISIBLE);
whitee.setVisibility(View.INVISIBLE);
whitee.setEnabled(false);
logo.setVisibility(View.INVISIBLE);
logo.setEnabled(false);
}
}
}.start();
imageView = (ImageView) findViewById(R.id.imageview);
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(5000);
mLocationRequest.setFastestInterval(3000);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
myresdone.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(MainActivity.this, myresdone.class);
i.putExtra("useridd",useridd);
startActivity(i);
}
});
signout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
auth.signOut();
startActivity(new Intent(MainActivity.this, LoginActivity.class));
finish();
}
});
register.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent rg = new Intent(MainActivity.this, Main5Activity.class);
rg.putExtra("useridd", useridd);
startActivity(rg);
}
});
skipbut.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this, Main2Activity.class);
i.putExtra("latt", latt);
i.putExtra("longit", longit);
skipped = -2;
i.putExtra("useridd", useridd);
i.putExtra("skipped", skipped);
startActivity(i);
finish();
}
});
b = (Button) findViewById(R.id.btnClick);
b.setEnabled(false);
b.setVisibility(b.INVISIBLE);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View arg0) {
Intent i = new Intent(MainActivity.this, Main2Activity.class);
i.putExtra("latt", latt);
i.putExtra("longit", longit);
i.putExtra("useridd", useridd);
startActivity(i);
finish();
}
});
LocationManager_check locationManagerCheck = new LocationManager_check(
this);
Location location = null;
Boolean internet=isOnline();
if (locationManagerCheck.isLocationServiceAvailable()==false && internet==false ) {
//locationManagerCheck.createLocationServiceError(MainActivity.this);
Toast.makeText(MainActivity.this, "Internet and location access unavailable!", Toast.LENGTH_LONG).show();
}
else if(locationManagerCheck.isLocationServiceAvailable()==false && internet==true ) {
//locationManagerCheck.createLocationServiceError(MainActivity.this);
Toast.makeText(MainActivity.this, "location access unavailable!", Toast.LENGTH_LONG).show();
}
else if(locationManagerCheck.isLocationServiceAvailable()==true && internet==false ) {
//locationManagerCheck.createLocationServiceError(MainActivity.this);
Toast.makeText(MainActivity.this, "Internet connection unavailable!", Toast.LENGTH_LONG).show();
}
else if (locationManagerCheck.isLocationServiceAvailable() == true && isOnline()==true) {
i = 1;
}
}
//some required functions
public boolean fileExistance(String fname) {
File file = getBaseContext().getFileStreamPath(fname);
return file.exists();
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 0) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
} else {
register.setEnabled(false);
takePictureButton.setEnabled(false);
skipbut.setEnabled(false);
threshld1 = 1;
}
} else if (requestCode == MY_PERMISSIONS_REQUEST_FINE_LOCATION) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED && grantResults[2] == PackageManager.PERMISSION_GRANTED) {
permissionIsGranted = true;
} else {
permissionIsGranted = false;
Toast.makeText(getApplicationContext(), "This app requires all three permissions to be granted", Toast.LENGTH_SHORT).show();
register.setEnabled(false);
takePictureButton.setEnabled(false);
skipbut.setEnabled(false);
threshld1 = 1;
}
}
}
public void takePicture(View view) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
file = Uri.fromFile(getOutputMediaFile());
intent.putExtra(MediaStore.EXTRA_OUTPUT, file);
startActivityForResult(intent, 100);
}
private static File getOutputMediaFile() {
File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES), "CameraDemo");
if (!mediaStorageDir.exists()) {
if (!mediaStorageDir.mkdirs()) {
Log.d("CameraDemo", "failed to create directory");
return null;
}
}
return new File(mediaStorageDir.getPath() + File.separator + "hsr.jpg");
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == 100) {
if (resultCode == RESULT_OK) {
imageView.setImageURI(file);
vv.setVisibility(View.INVISIBLE);
if (i == 1) {
b.setEnabled(true);
b.setVisibility(b.VISIBLE);
takePictureButton.setEnabled(false);
takePictureButton.setVisibility(takePictureButton.INVISIBLE);
skipbut.setEnabled(false);
myresdone.setEnabled(false);
myresdone.setVisibility(View.INVISIBLE);
skipbut.setVisibility(View.INVISIBLE);
}
}
}
}
//Location code
/////////////////////////////////////////////////////////////////////////////////////////
#Override
protected void onStart() {
super.onStart();
mGoogleApiClient.connect();
}
protected void onResume() {
super.onResume();
if (permissionIsGranted) {
if (mGoogleApiClient.isConnected()) {
RequestLocationUpdates();
}
}
}
protected void onPause() {
super.onPause();
if (permissionIsGranted)
LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
}
#Override
protected void onStop() {
super.onStop();
if (permissionIsGranted)
mGoogleApiClient.disconnect();
}
#Override
public void onConnected(Bundle bundle) {
RequestLocationUpdates();
}
private void RequestLocationUpdates() {
if ((ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) || ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M ) {
requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE}, MY_PERMISSIONS_REQUEST_FINE_LOCATION);
} else {
permissionIsGranted = true;
}
return;
}
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
}
#Override
public void onConnectionSuspended(int i) {
Log.i(TAG, "Connection Suspended");
mGoogleApiClient.connect();
}
#Override
public void onLocationChanged(Location location) {
latt = String.valueOf(location.getLatitude());
longit = String.valueOf(location.getLongitude());
locationdata=1;
if (i == 1 && threshld1 != 1 && threshld != 1 &&locationdata==1) {
takePictureButton.setEnabled(true);
skipbut.setEnabled(true);
myresdone.setEnabled(true);
signout.setEnabled(true);
signout.setVisibility(View.VISIBLE);
pbb.setVisibility(View.INVISIBLE);
}
}
#Override
public void onConnectionFailed(ConnectionResult connectionResult) {
Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());
}
public boolean isOnline() {
ConnectivityManager conMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo netInfo = conMgr.getActiveNetworkInfo();
if(netInfo == null || !netInfo.isConnected() || !netInfo.isAvailable()){
return false;
}
return true;
}
}
Login Activity:
package com.sitepoint.example02;
import android.text.TextUtils;
import android.widget.Toast;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.AuthResult;
import com.google.firebase.auth.FirebaseAuth;
public class LoginActivity extends AppCompatActivity {
private EditText inputEmail, inputPassword;
private FirebaseAuth auth;
private ProgressBar progressBar;
private Button btnSignup, btnLogin, btnReset;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
if (auth.getCurrentUser() != null) {
Intent i=new Intent(LoginActivity.this, MainActivity.class);
startActivity(i);
finish();
}
// the above code checks whether the same person had previously logged in and therefore loads previous profile*********
// set the view now
setContentView(R.layout.activity_login);
// Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
// setSupportActionBar(toolbar);
inputEmail = (EditText) findViewById(R.id.email);
inputPassword = (EditText) findViewById(R.id.password);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
btnSignup = (Button) findViewById(R.id.btn_signup);
btnLogin = (Button) findViewById(R.id.btn_login);
btnReset = (Button) findViewById(R.id.btn_reset_password);
//Get Firebase auth instance
auth = FirebaseAuth.getInstance();
btnSignup.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, signupactivity.class));
}
});
btnReset.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startActivity(new Intent(LoginActivity.this, ResetPasswordActivity.class));
}
});
btnLogin.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String email = inputEmail.getText().toString();
final String password = inputPassword.getText().toString();
if (TextUtils.isEmpty(email)) {
Toast.makeText(getApplicationContext(), "Enter email address!", Toast.LENGTH_SHORT).show();
return;
}
if (TextUtils.isEmpty(password)) {
Toast.makeText(getApplicationContext(), "Enter password!", Toast.LENGTH_SHORT).show();
return;
}
progressBar.setVisibility(View.VISIBLE);
//authenticate user
auth.signInWithEmailAndPassword(email, password)
.addOnCompleteListener(LoginActivity.this, new OnCompleteListener<AuthResult>() {
#Override
public void onComplete(#NonNull Task<AuthResult> task) {
// If sign in fails, display a message to the user. If sign in succeeds
// the auth state listener will be notified and logic to handle the
// signed in user can be handled in the listener.
progressBar.setVisibility(View.GONE);
if (!task.isSuccessful()) {
// there was an error
if (password.length() < 6) {
inputPassword.setError(getString(R.string.minimum_password));
} else {
Toast.makeText(LoginActivity.this, getString(R.string.auth_failed), Toast.LENGTH_LONG).show();
}
} else {
Intent intent = new Intent(LoginActivity.this, MainActivity.class);
startActivity(intent);
finish();
}
}
});
}
});
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<uses-permission-sdk-23 android:name="android.permission.CAMERA" />
<uses-permission-sdk-23 android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.INTERNET" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="AniNet"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".LoginActivity"
android:configChanges="orientation"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main2Activity"
android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity
android:name=".Main3Activity"
android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity
android:name=".Main5Activity"
android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity
android:name=".MainActivity"
android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity
android:name=".signupactivity"
android:configChanges="orientation"
android:screenOrientation="portrait" />
<activity android:name=".myresdone" />
<activity android:name=".myresinfo" />
<activity android:name=".ResetPasswordActivity"></activity>
</application>

So, make sure you have added intent.action in android manifest file.
eg:
<activity android:name=".activities.LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>

You do launch from Login, then call if(auth.getCurrentUser != null){ start mainActivity} you aren't waiting for authorization. Your basically skipping login, but it is starting with login.

Related

Cannot able run Bluetooth Scanning in Foreground service more than 10 - 15 secs even though Notification is provided

I have used Service to keep my scan for android mobiles even when the app is closed. I used Broadcast receiver to restart my service when killed. It restarts the scanning and it works only for some 15 seconds and then stops
When i click button1 in {MainActivity} I started the service and have called startdiscovery() in startCommand method in {ExampleService}
Please Help me in running the app in background
MainActivity.java
import android.Manifest;
import android.app.ActivityManager;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.IntentSender;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.VibrationEffect;
import android.os.Vibrator;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.bluetooth.le.ScanResult;
import android.widget.Toast;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import com.google.android.gms.common.api.ApiException;
import com.google.android.gms.common.api.ResolvableApiException;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationSettingsRequest;
import com.google.android.gms.location.LocationSettingsResponse;
import com.google.android.gms.location.LocationSettingsStatusCodes;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.firestore.FirebaseFirestore;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends AppCompatActivity {
ListView scanListView;
ArrayList<String> stringArrayList = new ArrayList<String>();
ArrayAdapter<String> arrayAdapter;
static BluetoothAdapter myAdapter = BluetoothAdapter.getDefaultAdapter();
FirebaseFirestore db = FirebaseFirestore.getInstance();
static int count=0;
ScanResult sc;
String Uuid;
Date currentTime;
private LocationSettingsRequest.Builder builder;
private final int REQUEST_CHECK_CODE=8989;
public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
LocationManager locationm;
String provider;
Button button1;
BluetoothAdapter bluetoothAdapter;
Intent btEnablingIntent;
int requestCodeForEnable;
Button button;
Button scanButton1;
RegisterActivity registerActivity=new RegisterActivity();
String email ;
String phone ;
///
Intent discoverableIntenet = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
Intent mServiceIntent;
private ExampleService mYourService;
Context ctx;
public Context getCtx() {
return ctx;
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
currentTime = Calendar.getInstance().getTime();
setContentView(R.layout.activity_main);
checkLocationPermission();
btEnablingIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
requestCodeForEnable=1;
discoverableIntenet.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3000);
startActivity(discoverableIntenet);
button=(Button) findViewById(R.id.button4);
Intent intent = new Intent(MainActivity.this,ble.class);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,ble.class);
MainActivity.this.startActivity(intent);
}
});
button=(Button) findViewById(R.id.button6);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
open(view);
}
});
button=(Button) findViewById(R.id.button3);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
pdfs(view);
}
});
button=(Button) findViewById(R.id.button5);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
myths(view);
}
});
button1=(Button) findViewById(R.id.button2);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
analytics(view);
}
});
scanListView = (ListView) findViewById(R.id.scannedListView);
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
scanButton1=(Button) findViewById(R.id.Button1);
scanButton1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Log.d("disc","discoveeery!");
Log.i("hiiiiiii", String.valueOf(myAdapter.isDiscovering()));
Intent serviceIntent = new Intent(MainActivity.this, ExampleService.class);
serviceIntent.putExtra("inputExtra", "hi");
// startService( serviceIntent);
mYourService = new ExampleService();
mServiceIntent = new Intent(MainActivity.this, mYourService.getClass());
if (!isMyServiceRunning(mYourService.getClass())) {
startService(mServiceIntent);
}
}
});
bluetoothOnMethod();
BluetoothFunctions();
}
public void BluetoothFunctions(){
Log.d("disc", "discovery!");
IntentFilter intentFilter;
intentFilter=new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(myreceiver, intentFilter);
intentFilter = new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
registerReceiver(myreceiver, intentFilter);
arrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_list_item_1, stringArrayList);
scanListView.setAdapter(arrayAdapter);
Uuid="02.020202.020.02";
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == requestCodeForEnable) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "Bluetooth is enabled", Toast.LENGTH_LONG).show();
}
else if(resultCode==RESULT_CANCELED) {
Toast.makeText(getApplicationContext(), "Bluetooth enabling cancelled", Toast.LENGTH_LONG).show();
}
}
}
final BroadcastReceiver myreceiver = new BroadcastReceiver() {
#RequiresApi(api = Build.VERSION_CODES.O)
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
if (device.getName() == null) {
return;
}
String address = device.getName();
int N = 2;
float type = intent.getFloatExtra((BluetoothDevice.EXTRA_UUID),Float.MIN_VALUE);
int rssi = intent.getShortExtra(BluetoothDevice.EXTRA_RSSI, Short.MIN_VALUE);
String rssi_val = String.valueOf(rssi);
String data = device.getAddress() + " " + rssi_val;
Vibrator v1 = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
stringArrayList.add(data);
if (rssi >= -50) {
v1.vibrate(VibrationEffect.createOneShot(1000, VibrationEffect.DEFAULT_AMPLITUDE));
count++;
if (device.getAddress() != null) {
Firebasepush(device.getAddress(), rssi_val);
}
}
Log.i("lll", device.getAddress());
Log.i("lll", device.getName());
Log.i("+>>>>>>>>>>>>>", BluetoothDevice.EXTRA_UUID);
Log.i("lll", rssi_val);
arrayAdapter.notifyDataSetChanged();
// Toast.makeText(getApplicationContext()," TX power: " +sc.getTxPower() + "dBm", Toast.LENGTH_SHORT).show();
//startThread();
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
Log.v("ggggggggg", "Entered the Finished ");
myAdapter.startDiscovery();
}
}
};
public void Firebasepush(String uuid,String rrsi){
Map<String, Object> updateMap = new HashMap();
updateMap.put("RSSI", rrsi);
updateMap.put("time", currentTime);
Map<String, Object> countMap = new HashMap();
countMap.put("Count", count);
countMap.put("time", currentTime);
countMap.put("Name",registerActivity.NameString);
countMap.put("Email",registerActivity.EmailId);
countMap.put("Phone Number",registerActivity.PhoneNumber);
// Add a new document with a generated ID
db.collection("users").document(Uuid).collection("contacts").document(uuid)
.set(updateMap);
db.collection("users").document(Uuid).
set(countMap);
}
void bluetoothOnMethod() {
if(bluetoothAdapter==null){
Toast.makeText(getApplicationContext(), "Bluetooth does not support ",Toast.LENGTH_LONG).show();
}
else {
if(!bluetoothAdapter.isEnabled()){
startActivityForResult(btEnablingIntent,requestCodeForEnable);
}
}
}
public boolean checkLocationPermission() {
LocationRequest request = new LocationRequest()
.setFastestInterval(1500)
.setInterval(3000)
.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
builder = new LocationSettingsRequest.Builder()
.addLocationRequest(request);
Task<LocationSettingsResponse> result = LocationServices.getSettingsClient( this).checkLocationSettings(builder.build());
result.addOnCompleteListener(new OnCompleteListener<LocationSettingsResponse>() {
#Override
public void onComplete(#NonNull Task<LocationSettingsResponse> task) {
try{
task.getResult(ApiException.class);
}catch (ApiException e){
switch (e.getStatusCode())
{
case LocationSettingsStatusCodes
.RESOLUTION_REQUIRED:
try {
ResolvableApiException resolvableApiException= (ResolvableApiException) e;
resolvableApiException.startResolutionForResult(MainActivity.this,REQUEST_CHECK_CODE);
} catch (IntentSender.SendIntentException ex) {
ex.printStackTrace();
}catch (ClassCastException ex){
}break;
case LocationSettingsStatusCodes.SETTINGS_CHANGE_UNAVAILABLE:
{ break;}
}
}
}
});
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
!= PackageManager.PERMISSION_GRANTED) {
// Should we show an explanation?
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.ACCESS_FINE_LOCATION)) {
// Show an explanation to the user *asynchronously* -- don't block
// this thread waiting for the user's response! After the user
// sees the explanation, try again to request the permission.
new AlertDialog.Builder(this)
.setTitle(R.string.title_location_permission)
.setMessage(R.string.text_location_permission)
.setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
})
.create()
.show();
} else {
ActivityCompat.requestPermissions(this,
new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
MY_PERMISSIONS_REQUEST_LOCATION);
}
return false;
} else {
return true;
}
}
#Override
public void onRequestPermissionsResult(int requestCode,String permissions[], int[] grantResults) {
switch (requestCode) {
case MY_PERMISSIONS_REQUEST_LOCATION: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// location-related task you need to do.
if (ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION)
== PackageManager.PERMISSION_GRANTED) {
//Request location updates:
// locationm.requestLocationUpdates(provider, 400, 1,this);
}
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
}
return;
}
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
Log.i ("Service status", "Running");
return true;
}
}
Log.i ("Service status", "Not running");
return false;
}
#Override
protected void onDestroy() {
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
super.onDestroy();
// Don't forget to unregister the ACTION_FOUND receiver.
// unregisterReceiver(myreceiver);
}
public void openservices(){
Intent intnt=new Intent(this ,Services.class);
startActivity(intnt);
}
public void open(View view)
{
Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.hogist.com/#/"));
startActivity(browserIntent);
}
public void pdfs(View view)
{
Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.mohfw.gov.in/pdf/Illustrativeguidelineupdate.pdf"));
startActivity(browserIntent);
}
public void myths(View view)
{
Intent browserIntent=new Intent(Intent.ACTION_VIEW, Uri.parse("https://www.mohfw.gov.in/pdf/Illustrativeguidelineupdate.pdf"));
startActivity(browserIntent);
}
public void analytics(View view){
final Intent intent1 = new Intent(MainActivity.this, Analytics.class);
startActivity(intent1);
}
}
ExampleService.java
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.AsyncTask;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import android.widget.TextView;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import androidx.core.app.NotificationCompat;
import java.util.Timer;
import java.util.TimerTask;
public class ExampleService extends Service {
BluetoothAdapter myAdapter = BluetoothAdapter.getDefaultAdapter();
MainActivity mainActivity=new MainActivity();
public int counter=0;
#Override
public void onCreate() {
super.onCreate();
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.O)
startMyOwnForeground();
else
startForeground(1, new Notification());
}
#RequiresApi(Build.VERSION_CODES.O)
private void startMyOwnForeground()
{
String NOTIFICATION_CHANNEL_ID = "example.permanence";
String channelName = "Background Service";
NotificationChannel chan = new NotificationChannel(NOTIFICATION_CHANNEL_ID, channelName, NotificationManager.IMPORTANCE_NONE);
chan.setLightColor(Color.BLUE);
chan.setLockscreenVisibility(Notification.VISIBILITY_PRIVATE);
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
assert manager != null;
manager.createNotificationChannel(chan);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID);
Notification notification = notificationBuilder.setOngoing(true)
.setContentTitle("App is running in background")
.setPriority(NotificationManager.IMPORTANCE_MIN)
.setCategory(Notification.CATEGORY_SERVICE)
.build();
startForeground(2, notification);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// startTimer();
myAdapter.startDiscovery();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
// stoptimertask();
myAdapter.cancelDiscovery();
Intent broadcastIntent = new Intent();
broadcastIntent.setAction("restartservice");
broadcastIntent.setClass(this, Restarter.class);
this.sendBroadcast(broadcastIntent);
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}```
Restarter.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.util.Log;
import android.widget.Toast;
public class Restarter extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.i("Broadcast Listened", "Service tried to stop");
Toast.makeText(context, "Service restarted", Toast.LENGTH_SHORT).show();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
Log.i(Restarter.class.getSimpleName(), "Service Stops! Oooooooooooooppppssssss!!!!");
context.startForegroundService(new Intent(context, ExampleService.class));
} else {
context.startService(new Intent(context, ExampleService.class));
}
}
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.hogist_social_distancing">
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
android:name=".App"
android:fullBackupContent="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=".Analytics"
android:screenOrientation="portrait" />
<activity
android:name=".Services"
android:screenOrientation="portrait" />
<activity
android:name=".Permissions"
android:screenOrientation="portrait" />
<activity
android:name=".MainActivity"
android:screenOrientation="portrait" />
<activity android:name=".RegisterActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".OTPActivity" />
<activity android:name=".ble" />
<service
android:name=".ExampleService"
android:enabled="true" />
<receiver
android:name="Restarter"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="restartservice" />
</intent-filter>
</receiver>
</application>
</manifest>```
Android strives to save the battery, so it's expected that your service is stopped, especially if it runs battery draining operations such as Bluetooth scans.
Also, bare in mind that starting from Android 7, an app cannot start the BLE scan more than 5 times per 30 seconds, as mentioned here. Other issues related to BLE scanning are listed here.
If you do want to run Bluetooth scans in the background, I suggest you use a JobIntentService, in which you start BLE scan for a few seconds.
JobIntentService is very similar to IntentService but with few benefits like holding a wake lock which prevents the CPU to go to sleep
Also, this type of service does not require displaying a notification to your user. For more info: https://developer.android.com/reference/androidx/core/app/JobIntentService
are you sure your bluetooth code can work well on activity (without service)?
you can not restart your service by call Broadcast when you service was killed, because when your service was killed by OS system, it will kill your application process so your broadcast will not work. When you call return START_STICKY; it means system will automatic restart your service when it have available resource

My app runs the first time then crashes every time I try to reopen

I am building an app that reads SMS's by converting them to speech.
After installing the apk it runs but when I close it and try to open it again it crashes.
It gives an error message saying the app keeps closing.
When I set it to only read after a button click it was working fine but after I changed it to read on initialization this problem came about.
Please help.
package com.example.receiver3;
import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.speech.tts.TextToSpeech;
import android.support.annotation.NonNull;
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.ArrayAdapter;
import android.widget.ListView;
import android.widget.Button;
import android.widget.Toast;
import java.util.ArrayList;
import java.util.Locale;
public class MainActivity extends AppCompatActivity {
ListView listView;
Button btConvert, btNext;
private static final int PERMISSION_REQUEST_READ_CONTACTS = 100;
ArrayList<String> smsList;
TextToSpeech textToSpeech;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.idList);
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
if (permissionCheck == PackageManager.PERMISSION_GRANTED){
initializeTextToSpeech(); //edit
showContact();
}
else{
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, PERMISSION_REQUEST_READ_CONTACTS);
}
btConvert = findViewById(R.id.bt_stop);
btNext = findViewById(R.id.bt_next);
btConvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get list value
for (String s : smsList) {
textToSpeech.stop();
}
}
});
Button button = (Button) findViewById(R.id.bt_next);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivity();
}
});
}
private void initializeTextToSpeech() { //edit
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS){
int lang = textToSpeech.setLanguage(Locale.UK);
}
}
});
}
public void openActivity(){
Intent intent = new Intent(this, Main2Activity.class);
startActivity(intent);
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (requestCode == PERMISSION_REQUEST_READ_CONTACTS){
showContact();
initializeTextToSpeech(); //edit
}
else {
Toast.makeText(this, "Permission Required", Toast.LENGTH_SHORT).show();
}
}
private void showContact() {
Uri inboxUri = Uri.parse("content://sms/inbox");
smsList = new ArrayList<>();
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(inboxUri,null, null, null, null);
while (cursor.moveToNext()){
String number = cursor.getString(cursor.getColumnIndexOrThrow("address")).toString();
String body = cursor.getString(cursor.getColumnIndexOrThrow("body")).toString();
smsList.add("Number: "+number+ "\n" + "Body: "+body);
}
for (String s : smsList) {
textToSpeech.speak(s,TextToSpeech.QUEUE_ADD, null);
}
cursor.close();
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,smsList);
listView.setAdapter(adapter);
}
public void speak() { //edit
for (String s : smsList) {
textToSpeech.speak(s,TextToSpeech.QUEUE_ADD, null);
}
}
#Override
protected void onPause() { //edit
super.onPause();
textToSpeech.stop();
}
#Override
protected void onStop() {
super.onStop();
textToSpeech.stop();
}
#Override
protected void onResume() { //edit
super.onResume();
showContact();
initializeTextToSpeech();
}
}
You are now calling showContact() which in turn calls textToSpeech.speak() before initialising the textToSpeech object with textToSpeech = new TextToSpeech().
The code works fine on the first run because the user hasn't given the requested permission yet and showContact() doesn't get called.
You need to change your onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
listView = (ListView) findViewById(R.id.idList);
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
// *** MOVE THIS UP HERE. ***
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS){
int lang = textToSpeech.setLanguage(Locale.UK);
return;
}
}
});
if (permissionCheck == PackageManager.PERMISSION_GRANTED){
showContact();
return;
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, PERMISSION_REQUEST_READ_CONTACTS);
}
btConvert = findViewById(R.id.bt_convert);
btNext = findViewById(R.id.bt_next);
btConvert.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//get list value
for (String s : smsList) {
textToSpeech.stop();
}
}
});
Button button = (Button) findViewById(R.id.bt_next);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openActivity();
}
});
}
But that alone won't be enough as TTS isn't ready immediately. It's usable only after the onInit() callback has run and you receive the TextToSpeech.SUCCESS state there.
So, if you want to speak something as soon as possible at application startup then it needs to be triggered from onInit().
Maybe you can think of something like:
int permissionCheck = ContextCompat.checkSelfPermission(this, Manifest.permission.READ_SMS);
if (permissionCheck != PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_SMS}, PERMISSION_REQUEST_READ_CONTACTS);
}
And then:
textToSpeech = new TextToSpeech(getApplicationContext(), new TextToSpeech.OnInitListener() {
#Override
public void onInit(int i) {
if (i == TextToSpeech.SUCCESS){
int lang = textToSpeech.setLanguage(Locale.UK);
if (permissionCheck == PackageManager.PERMISSION_GRANTED){
showContact();
}
}
}
});
I don't see why would you have the return; calls at all. And actually in the original code the return; exits the onCreate() before even trying to initialize the TTS if the permission is already given.

My app is crashing when i try to retrieve imie number...here is my code

Android Manifest
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
MainActivity.java
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
TextView tv;
Button bn;
String imei;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tvimei);
bn = (Button)findViewById(R.id.button);
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imei = telephonyManager.getDeviceId();
bn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tv.setText(imei);
}
});
}
}
I was trying to get imei number and display it on homepage for testing purpose but the app crashes as soon as I run it on the phone
Hi try to add permission if your device is marshmallow check the below code also
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private static final int PERMISSION_REQUEST_CODE = 1;
TextView tv;
Button bn;
String imei;
private boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.READ_PHONE_STATE);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tv = (TextView)findViewById(R.id.tvimei);
bn = (Button)findViewById(R.id.button);
if(checkPermission()){
Snackbar.make(view, "Permission already granted.", Snackbar.LENGTH_LONG).show();
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
imei = telephonyManager.getDeviceId();
}else{
Snackbar.make(view,"Please give access to read your phone state.",Snackbar.LENGTH_LONG).show();
requestPermission();
}
bn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
tv.setText(imei);
}
});
}
private void requestPermission() {
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_PHONE_STATE)){
Toast.makeText(getApplicationContext(),"Give permission to check whether internet is of or on.",Toast.LENGTH_LONG).show();
} else {
ActivityCompat.requestPermissions(this,new String[]{Manifest.permission.READ_PHONE_STATE},PERMISSION_REQUEST_CODE);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Snackbar.make(view,"Permission Granted, Now you can check network status.",Snackbar.LENGTH_LONG).show();
} else {
Snackbar.make(view,"Permission Denied, You cannot check networkstatus.",Snackbar.LENGTH_LONG).show();
}
break;
}
}
}

Android Camera Black Screen

I am trying create an app that will read a QR Code, This code worked intermittently but it would give Permission errors and would not load. I believe I have those fixed, but now I get a Black Screen. There are no errors so I do not know where to look, but I feel it has something to do with the permissions.
package com.sample.qrcodereadervision.Activity;
import com.google.android.gms.vision.CameraSource;
import com.google.android.gms.vision.Detector;
import com.google.android.gms.vision.barcode.Barcode;
import com.google.android.gms.vision.barcode.BarcodeDetector;
import com.sample.qrcodereadervision.R;
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.util.SparseArray;
import android.view.SurfaceView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import permissions.dispatcher.NeedsPermission;
import permissions.dispatcher.OnPermissionDenied;
import permissions.dispatcher.OnShowRationale;
import permissions.dispatcher.PermissionRequest;
import permissions.dispatcher.PermissionUtils;
import permissions.dispatcher.RuntimePermissions;
#RuntimePermissions
public class QRcodeReader extends AppCompatActivity {
public final String TAG = getClass().getSimpleName();
private CameraSource cameraSource;
/** UI Parts : Preview screen */
private SurfaceView cameraView;
/** UI Parts : decoding results */
private TextView barcodeInfo;
private static final int REQUEST_CAMERA = 0x00000011;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Log.d("QRcodeReader", "onCreate");
setContentView(R.layout.activity_main);
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
!= PackageManager.PERMISSION_GRANTED) {
requestCameraPermission();
}
}
#Override
protected void onStart() {
super.onStart();
Log.d(TAG, "onStart");
barcodeInfo = (TextView) findViewById(R.id.code_info);
cameraView = (SurfaceView) findViewById(R.id.camera_view);
startQRcodeReader();
// startCameraSource();
}
#Override
protected void onPause() {
super.onPause();
Log.d(TAG, "onPause");
}
//#Override
//public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
// Log.d(TAG, "onRequestPermissionsResult");
// QRcodeReaderPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
//}
private void startQRcodeReader() {
Log.d(TAG, "startQRcodeReader");
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(this)
.setBarcodeFormats(Barcode.QR_CODE)
.build();
cameraSource = new CameraSource
.Builder(this, barcodeDetector)
.setAutoFocusEnabled(true)
.build();
QRcodeReaderPermissionsDispatcher.startCameraSourceWithCheck(QRcodeReader.this);
//requestCameraPermission();
//QR Code reading
barcodeDetector.setProcessor(
new Detector.Processor<Barcode>() {
#Override
public void release() {
}
#Override
public void receiveDetections(Detector.Detections<Barcode> detections) {
final SparseArray<Barcode> barcodes = detections.getDetectedItems();
if (barcodes.size() != 0) {
barcodeInfo.post(
new Runnable() {
public void run() {
barcodeInfo.setText(
barcodes.valueAt(0).displayValue
);
}
});
}
}
});
}
#NeedsPermission(Manifest.permission.CAMERA)
void startCameraSource() {
Log.d(TAG, "startCameraSource");
Toast.makeText(this, "\n" +
"Start the camera source", Toast.LENGTH_SHORT)
.show();
try {
releaseCameraAndPreview();
if (cameraSource != null) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
cameraSource.start(cameraView.getHolder());
return;
}
}
} catch (IOException | SecurityException e) {
Log.w(TAG, e);
}
}
#SuppressWarnings("unused")
#OnPermissionDenied(Manifest.permission.CAMERA)
void deniedPermission() {
Log.d(TAG, "deniedPermission");
if (PermissionUtils.shouldShowRequestPermissionRationale(this, Manifest.permission.CAMERA)) {
Toast.makeText(this, "\n" +
"It failed to camera startup .", Toast.LENGTH_SHORT)
.show();
}
}
#SuppressWarnings("unused")
#OnShowRationale(Manifest.permission.CALL_PHONE)
void showRationalForStorage(final PermissionRequest request) {
Log.d(TAG, "showRationalForStorage");
Toast.makeText(this, "\n" +
"The camera of the use permit is required", Toast.LENGTH_SHORT)
.show();
request.proceed();
}
private void releaseCameraAndPreview() {
if (cameraSource != null) {
cameraSource.release();
cameraSource = null;
}
}
private void requestCameraPermission() {
Log.i(TAG, "CAMERA permission has NOT been granted. Requesting permission.");
if (ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
Log.i(TAG,
"Displaying camera permission rationale to provide additional context.");
Snackbar.make(findViewById(R.id.code_info), R.string.permission_camera_rationale,
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(QRcodeReader.this,
new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA);
}
})
.show();
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA},
REQUEST_CAMERA);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String permissions[],
#NonNull int[] grantResults) {
Log.d(TAG, "onRequestPermissionsResult");
switch (requestCode) {
case REQUEST_CAMERA: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
QRcodeReaderPermissionsDispatcher.onRequestPermissionsResult(this, requestCode, grantResults);
startCameraSource();
} else {
finish();
}
}
break;
}
}
}
The Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sample.qrcodereadervision">
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-feature android:name="android.hardware.camera.autofocus"/>
<application
android:theme="#style/AppTheme"
android:label="#string/app_name"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:supportsRtl="true">
<activity android:name=".Activity.QRcodeReader">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<meta-data android:name="com.google.android.gms.vision.DEPENDENCIES" android:value="barcode"/>
</application>
</manifest>
pretty late for it but it will help you.
After that you have setup your camera and added preview and everything else. Just call
recreate();
Usage example in your Camera Activity like this.
camera = prepareCamera(camera); // a method to get camera instance
preview = createCameraPreview(camera) // a method which returns object of surfaceview
showCameraPreview(preview); // adding preview to the frame
recreate(); // <---This line should be called every time we setup a camera preview
Add the same permissions in manifest as well.

only GPS location tracking

I'm working on a location based tracking app. Does anyone know how to use only gps location and not network provider location. Since i'm using acess_fine_location in my manifest it uses both.
This is my tracking code:
package com.persasrl.paul.quickfit;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.provider.Settings;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GoogleApiAvailability;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.common.SupportErrorDialogFragment;
import java.text.DateFormat;
import java.util.Date;
public class StepCounter extends FragmentActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {
// Request code to use when launching the resolution activity
private static final int REQUEST_RESOLVE_ERROR = 1001;
// Unique tag for the error dialog fragment
private static final String DIALOG_ERROR = "dialog_error";
// Bool to track whether the app is already resolving an error
private boolean mResolvingError = false;
//keys
GoogleApiClient mGoogleApiClient;
TextView mDistanceText;
TextView mTimeText;
Location mLastLocation;
Location mCurrentLocation;
UserLocalStore userLocalStore;
float[] d = new float[1];
float totald=0;
int type;
private MCountDownTimer countDownTimer;
private long timeElapsed;
private final long startTime = 9223372036854775807L;
private final long interval = 1;
LocationRequest mLocationRequest;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_step_counter);
userLocalStore = new UserLocalStore(this);
mDistanceText = (TextView) findViewById(R.id.dist);
mTimeText = (TextView) findViewById(R.id.time);
mResolvingError = savedInstanceState != null
&& savedInstanceState.getBoolean(STATE_RESOLVING_ERROR, false);
Intent startIntent = getIntent();
Bundle bundle = startIntent.getExtras();
if(bundle!=null)
type= bundle.getInt("sport");
isGpsConnected();
createLocationRequest();
buildGoogleApiClient();
}
public void isGpsConnected()
{
// Get Location Manager and check for GPS & Network location services
LocationManager lm = (LocationManager) getSystemService(LOCATION_SERVICE);
if(!lm.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
!lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)) {
// Build the alert dialog
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Location Services Not Active");
builder.setMessage("Please enable Location Services and GPS");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialogInterface, int i) {
// Show location settings when the user acknowledges the alert dialog
Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
startActivity(intent);
}
});
Dialog alertDialog = builder.create();
alertDialog.setCanceledOnTouchOutside(false);
alertDialog.show();
}
}
protected synchronized void buildGoogleApiClient() {
mGoogleApiClient = new GoogleApiClient.Builder(this)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.addApi(LocationServices.API)
.build();
}
#Override
protected void onStart() {
super.onStart();
if(!mResolvingError)
mGoogleApiClient.connect();
}
#Override
protected void onStop() {
mGoogleApiClient.disconnect();
super.onStop();
}
public void stopApp(View view)
{
User user = userLocalStore.getLoggedInUser();
Workout workout = new Workout (totald,type,user.username,timeElapsed);
registerWorkout(workout);
}
private void registerWorkout(Workout workout) {
ServerRequests serverRequest = new ServerRequests(this);
serverRequest.storeWorkoutDataInBackground(workout, new GetWorkoutCallback() {
#Override
public void done(Workout returnedWorkout) {
Intent Intent = new Intent(StepCounter.this, MainActivity.class);
startActivity(Intent);
}
});
}
public void onConnected(Bundle connectionHint) {
countDownTimer = new MCountDownTimer(startTime, interval);
countDownTimer.start();
startLocationUpdates();
}
//pana aici merge de aici vine partea cu update
protected void startLocationUpdates() {
LocationServices.FusedLocationApi.requestLocationUpdates(
mGoogleApiClient, mLocationRequest, this);
}
protected void createLocationRequest() {
mLocationRequest = new LocationRequest();
mLocationRequest.setInterval(500);
mLocationRequest.setFastestInterval(500);
mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
}
#Override
public void onLocationChanged(Location location) {
if(mCurrentLocation!=null)
mLastLocation = mCurrentLocation;
mCurrentLocation = location;
if(mLastLocation!=null && mCurrentLocation!=null)
updateDistance();
}
public void updateDistance()
{
Location.distanceBetween(mLastLocation.getLatitude(), mLastLocation.getLongitude(), mCurrentLocation.getLatitude(), mCurrentLocation.getLongitude(), d);
if(!(d[0]<0.001))
totald+=d[0];
mDistanceText.setText(String.valueOf(String.format("%.3f", totald)));
}
protected void onPause() {
super.onPause();
stopLocationUpdates();
}
protected void stopLocationUpdates() {
LocationServices.FusedLocationApi.removeLocationUpdates(
mGoogleApiClient, this);
}
#Override
public void onResume() {
super.onResume();
if (mGoogleApiClient.isConnected()) {
startLocationUpdates();
}
}
// De aici partea cu rezolvatu problemei
#Override
public void onConnectionSuspended(int i) {
//todo nust...
}
#Override
public void onConnectionFailed(ConnectionResult result) {
if (mResolvingError) {
// Already attempting to resolve an error.
return;
} else if (result.hasResolution()) {
try {
mResolvingError = true;
result.startResolutionForResult(this, REQUEST_RESOLVE_ERROR);
} catch (IntentSender.SendIntentException e) {
// There was an error with the resolution intent. Try again.
mGoogleApiClient.connect();
}
} else {
// Show dialog using GoogleApiAvailability.getErrorDialog()
showErrorDialog(result.getErrorCode());
mResolvingError = true;
}
}
// The rest of this code is all about building the error dialog
/* Creates a dialog for an error message */
private void showErrorDialog(int errorCode) {
// Create a fragment for the error dialog
ErrorDialogFragment dialogFragment = new ErrorDialogFragment();
// Pass the error that should be displayed
Bundle args = new Bundle();
args.putInt(DIALOG_ERROR, errorCode);
dialogFragment.setArguments(args);
dialogFragment.show(getFragmentManager(), "errordialog");
}
/* Called from ErrorDialogFragment when the dialog is dismissed. */
public void onDialogDismissed() {
mResolvingError = false;
}
/* A fragment to display an error dialog */
public static class ErrorDialogFragment extends DialogFragment {
public ErrorDialogFragment() { }
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Get the error code and retrieve the appropriate dialog
int errorCode = this.getArguments().getInt(DIALOG_ERROR);
return GoogleApiAvailability.getInstance().getErrorDialog(
this.getActivity(), errorCode, REQUEST_RESOLVE_ERROR);
}
#Override
public void onDismiss(DialogInterface dialog) {
((StepCounter) getActivity()).onDialogDismissed();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == REQUEST_RESOLVE_ERROR) {
mResolvingError = false;
if (resultCode == RESULT_OK) {
// Make sure the app is not already connected or attempting to connect
if (!mGoogleApiClient.isConnecting() &&
!mGoogleApiClient.isConnected()) {
mGoogleApiClient.connect();
}
}
}
}
private static final String STATE_RESOLVING_ERROR = "resolving_error";
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putBoolean(STATE_RESOLVING_ERROR, mResolvingError);
}
//timer
public class MCountDownTimer extends CountDownTimer
{
public MCountDownTimer(long startTime, long interval)
{
super(startTime, interval);
}
#Override
public void onFinish()
{
mTimeText.setText("Time Elapsed: " + String.valueOf(startTime));
}
#Override
public void onTick(long millisUntilFinished)
{
long hours=0;
long minutes=0;
long seconds=0;
timeElapsed = (startTime - millisUntilFinished)/1000;
seconds= timeElapsed%60;
minutes= timeElapsed/60%60;
hours = timeElapsed/3600;
mTimeText.setText(String.valueOf(hours) + ":" + String.valueOf(minutes)+ ":" + String.valueOf(seconds));
}
}
}
And my manifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
//android:theme="#android:style/Theme.Holo"
<activity
android:name=".LoginScreen"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".MainActivity"
android:label="#string/title_activity_main" >
</activity>
<activity
android:name=".StepCounter"
android:label="#string/title_activity_step_counter" >
</activity>
</application>

Categories

Resources