I am building a simple camera app that opens up the the system camera app on a button click and displays it in a image view.But the app is crashing on the startActivityForResult method.
MainActivity.java:
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
Button button;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
Bundle extra = data.getExtras();
Bitmap bitmap = (Bitmap) extra.get("data");
imageView.setImageBitmap(bitmap) ;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
button = (Button) findViewById(R.id.button);
if(getPackageManager().hasSystemFeature(PackageManager.FEATURE_CAMERA_ANY))
button.setEnabled(true);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
}
});
}
}
log cat:
Process: com.eldhoittangeorge.camera11032017, PID: 587
java.lang.SecurityException: Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=org.cyanogenmod.snap/com.android.camera.PhotoCamera } from ProcessRecord{f228cdc 587:com.eldhoittangeorge.camera11032017/u0a132} (pid=587, uid=10132) with revoked permission android.permission.CAMERA
at android.os.Parcel.readException(Parcel.java:1684)
at android.os.Parcel.readException(Parcel.java:1637)
at android.app.ActivityManagerProxy.startActivity(ActivityManagerNative.java:3093)
at android.app.Instrumentation.execStartActivity(Instrumentation.java:1520)
at android.app.Activity.startActivityForResult(Activity.java:4225)
at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
at android.app.Activity.startActivityForResult(Activity.java:4183)
at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
at com.eldhoittangeorge.camera11032017.MainActivity$1.onClick(MainActivity.java:42)
at android.view.View.performClick(View.java:5639)
at android.view.View$PerformClick.run(View.java:22391)
at android.os.Handler.handleCallback(Handler.java:751)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:154)
at android.app.ActivityThread.main(ActivityThread.java:6088)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:886)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)
call active take photo on button click
private void activeTakePhoto() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED || ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED ) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, 110);
} else {
takePicture();
}
}
public void takePicture() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, 22);
}
and override
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == 110) {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED
&& grantResults[1] == PackageManager.PERMISSION_GRANTED) {
takePicture();
}
}}
and manifest should have
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
why you are supposed to follow this procedure is because from marshmallow onward its mandatory to ask for self permission from the user before using camera and accessing galley irrespective of you have permission in your manifest.
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
public class MainActivity extends AppCompatActivity {
static final int REQUEST_IMAGE_CAPTURE = 1;
ImageView imageView;
Button button;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK){
Bundle extra = data.getExtras();
Bitmap bitmap = (Bitmap) extra.get("data");
imageView.setImageBitmap(bitmap) ;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
imageView = (ImageView) findViewById(R.id.imageView);
button = (Button) findViewById(R.id.button);
if(ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(this,new String[] {Manifest.permission.CAMERA},110);
takingPhoto();
}
else {
takingPhoto();
}
}
public void takingPhoto(){
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent,REQUEST_IMAGE_CAPTURE);
}
});
}
}
Related
I am a beginner learning android development and I started learning about permissions but it is not working nor appearing in the emulator and when I go to the settings of the apps it is showing that there are no permissions asked for this app can anyone help me, please
the Actvity:
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.core.app.ActivityCompat;
import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.provider.Settings;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.Toast;
import com.google.android.material.snackbar.BaseTransientBottomBar;
import com.google.android.material.snackbar.Snackbar;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
private Button btnOPenCamera;
private ImageView imgPhotoFromCamera;
private ConstraintLayout parent;
private static final int PERMISSION_REQUEST_CODE = 909;
private static final int OPEN_CAMERA_INTENT = 808;
private static final int OPEN_SETTINGS_INTENT = 707;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnOPenCamera = findViewById(R.id.btnOPenCamera);
imgPhotoFromCamera = findViewById(R.id.imgPhotoFromCamera);
parent = findViewById(R.id.parent);
btnOPenCamera.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
handlePermession();
}
});
}
private void handlePermession(){
if (ActivityCompat.checkSelfPermission(this , Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED){
Log.d(TAG, "handlePermession: it is working");
openCamera();
}else {
if (ActivityCompat.shouldShowRequestPermissionRationale(this , Manifest.permission.CAMERA)){
showSnackBar();
}else{
Log.d(TAG, "handlePermession: it is working in the request");
ActivityCompat.requestPermissions(this , new String[] {Manifest.permission.CAMERA} , PERMISSION_REQUEST_CODE);
}
}
}
private void openCamera(){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent , OPEN_CAMERA_INTENT);
}
private void showSnackBar(){
Snackbar.make(parent , "This app need your permission to the camera" , BaseTransientBottomBar.LENGTH_INDEFINITE)
.setAction("Allow", new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
intent.setData(Uri.parse("package:" + getPackageName()));
startActivityForResult(intent , OPEN_SETTINGS_INTENT );
}
}).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch(requestCode){
case OPEN_CAMERA_INTENT:
if (resultCode == PackageManager.PERMISSION_GRANTED && data != null){
Bundle bundle = data.getExtras();
if (null != bundle){
Bitmap bitmap =(Bitmap) bundle.get("data");
imgPhotoFromCamera.setImageBitmap(bitmap);
}
}
break;
case OPEN_SETTINGS_INTENT:
handlePermession();
break;
default:
break;
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch(requestCode){
case PERMISSION_REQUEST_CODE:
if(grantResults.length>0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
openCamera();
}else{
Toast.makeText(this, "Permission Denied", Toast.LENGTH_SHORT).show();
}
}
}
}
and there are no errors in the logcat which is something confusing for me, Thanks
Your code seems to work for me. The only difference is that I have added the camera permission to the AndroidManifest.xml file
<manifest ...>
<uses-permission android:name="android.permission.CAMERA" />
...
<application ...>
...
</application>
</manifest>
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.
i have the following Custom Listener
package home.dan.signalstrengthatlocation;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.SignalStrength;
import android.util.Log;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
public class CustomPhoneStateListener extends PhoneStateListener {
Context mContext;
public static String LOG_TAG = "CPhoneStateListener";
public CustomPhoneStateListener(Context context) {
mContext = context;
}
#Override
public void onSignalStrengthsChanged(SignalStrength signalStrength) {
super.onSignalStrengthsChanged(signalStrength);
Log.i(LOG_TAG, "onSignalStrengthsChanged: " + signalStrength);
Intent i = new Intent("Signal_update");
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.putExtra("signals","signals updated");
CustomPhoneStateListener.this.mContext.startActivity(i);
//mContext.startActivity(i); also does not work
}
}
In the last command it tries to send data to the MainActivity Class to be picked up by it's onReceive method.
But this does not work. i get the following error.
android.content.ActivityNotFoundException: No Activity found to handle Intent
What is the best way to send data from above Listner class to the MainActivity class ?
EDIT -
Class below is supposed to receive information from above intent
package home.dan.signalstrengthatlocation;
import android.app.Activity;
import android.telephony.TelephonyManager;
import android.telephony.PhoneStateListener;
import android.Manifest;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Build;
import android.support.annotation.NonNull;
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.TextView;
public class MainActivity extends AppCompatActivity {
private static final int NETWORKTYPE_WIFI = 0;
private static final int NETWORKTYPE_4G = 1;
private static final int NETWORKTYPE_2G = 2;
private static final int NETWORKTYPE_NONE = 3;
public TelephonyManager mTelephonyManager;
public PhoneStateListener mListener;
private Button start_btn,stop_btn;
private TextView textview;
private BroadcastReceiver broadcastReceiver;
private String coordinates;
public String getCoordinates() {
return coordinates;
}
public void setCoordinates(String coordinates) {
this.coordinates = coordinates;
}
private String signalStrength;
public String getSignalStrength() {
return signalStrength;
}
public void setSignalStrength(String signalStrength) {
this.signalStrength = signalStrength;
}
#Override
protected void onResume() {
super.onResume();
if(broadcastReceiver == null){
broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
setCoordinates(intent.getExtras().get("coordinates").toString());
updateScrollText();
}
};
}
registerReceiver(broadcastReceiver,new IntentFilter("location_update"));
}
private void updateScrollText(){
textview.append("\n"+getCoordinates()+" "+getSignalStrength());
}
#Override
protected void onDestroy() {
super.onDestroy();
if(broadcastReceiver != null){
unregisterReceiver(broadcastReceiver);
}
}
GPS_Service gps;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTelephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
mTelephonyManager.listen(new CustomPhoneStateListener(this), PhoneStateListener.LISTEN_SIGNAL_STRENGTHS);
start_btn = (Button) findViewById(R.id.button1);
stop_btn = (Button) findViewById(R.id.button2);
textview = (TextView) findViewById(R.id.textview);
if(!runtime_permissions()){
enable_buttons();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
// TODO Extract the data returned from the child Activity.
setSignalStrength(data.getStringExtra("signals"));
updateScrollText();
}
}
private void enable_buttons(){
start_btn.setEnabled(true);
stop_btn.setEnabled(false);
start_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),GPS_Service.class);
startService(i);
if(!stop_btn.isEnabled()){
start_btn.setEnabled(false);
stop_btn.setEnabled(true);
}
}
});
stop_btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(getApplicationContext(),GPS_Service.class);
stopService(i);
if(!start_btn.isEnabled()){
start_btn.setEnabled(true);
stop_btn.setEnabled(false);
}
}
});
}
private boolean runtime_permissions(){
if(Build.VERSION.SDK_INT >= 23
&&
ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED
&&
ContextCompat.checkSelfPermission(this,
Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
requestPermissions(
new String[]{Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION,
Manifest.permission.READ_PHONE_STATE},
100);
return true;
}
return false;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if(requestCode == 100){
if (grantResults[0] == PackageManager.PERMISSION_GRANTED && grantResults[1] == PackageManager.PERMISSION_GRANTED) {
enable_buttons();
}else{
runtime_permissions();
}
}
}
}
In your onResume() of your MainActivity, add following
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction("location_update");
intentFilter.addAction("signal_update);
registerReceiver(broadcastReceiver, intentFilter);
And then use sendBroadcast in CustomPhoneStateListener instead of startActivity.
Intent i = new Intent("signal_update");
i.putExtra("signals","signals updated");
CustomPhoneStateListener.this.mContext.sendBroadcast(i);
You'll receive both signal as well as location update here:
public void onReceive(Context context, Intent intent) {
if("signal_update".equals(intent.getAction())) {
//update UI for signal update
} else if ("location_update".equals(intent.getAction())) {
// update UI for location update
}
}
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;
}
}
}
How can i open Android device contacts list at button click event.
Try this code..
yourButton.setOnClickListener(new YouButtonEvent());
class YouButtonEventimplements OnClickListener{
#Override
public void onClick(View v) {
Intent it= new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(it, PICK_CONTACT);
}
}
Declare Some variables. Create a method & handle the events.
private static final int CONTACT_PICKER_RESULT = 1001;
private static final String DEBUG_TAG = "Contact List";
private static final int RESULT_OK = -1;
// a method to open your contact list
private void openContactList() {
Intent it = new Intent(Intent.ACTION_PICK, Contacts.CONTENT_URI);
startActivityForResult(it, CONTACT_PICKER_RESULT);
}
// handle after selecting a contact from the list
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
if (resultCode == RESULT_OK) {
switch (requestCode) {
case CONTACT_PICKER_RESULT:
// handle contact results
Log.w(DEBUG_TAG, "Warning: activity result is ok!");
break;
}
} else {
// gracefully handle failure
Log.w(DEBUG_TAG, "Warning: activity result not ok");
}
}
You can use this source code as a reference:
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
public class Test1Activity extends Activity {
private static final int PICK_CONTACT_REQUEST = 1;
private static final int PICK_CONTACT = 0;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button pickContact = (Button) findViewById(R.id.button1);
pickContact.setOnClickListener(new OnClickListener()
{
public void onClick(View v) {
Intent i = new Intent(Intent.ACTION_INSERT_OR_EDIT);
i.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
startActivity(i);
}
});
}
}
if u want to pick contact from your device then use this code.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
openContect();
dialog.dismiss();
}
and openContact() is:
private void openContect() {
Intent intent = new Intent(Intent.ACTION_PICK);
intent.setType(ContactsContract.Contacts.CONTENT_TYPE);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivityForResult(intent, REQUEST_SELECT_CONTACT);
}
}
and in your onActivityResult() use this:
if (requestCode==REQUEST_SELECT_CONTACT && resultCode == RESULT_OK && null != data){
Uri contactUri = data.getData();
//do what you want...
}