I want to use a service to measure the mobile data used since that service is started but I'm only able to measure the mobile data since device boot using the methods getTotalRxBytes() and getTotalTxBytes() of the TrafficStats class. Can someone help me in measuring the data used when the button is clicked and the service is started?
MainActivity.java
public class MainActivity extends AppCompatActivity {
private long data_limit;
EditText et_data_limit;
Button btn_start_track;
private int STORAGE_PERMISSION_CODE = 23;
SharedPreferences sharedPreferences;
SharedPreferences.Editor editor;
int PRIVATE_MODE = 0;
#Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sharedPreferences = MainActivity.this.getSharedPreferences("Data measured", PRIVATE_MODE);
editor = sharedPreferences.edit();
editor.putLong("data", 0);
if(isPermissionAllowed()){
}
else{
requestPermission();
}
et_data_limit = (EditText)findViewById(R.id.et_data_limit);
btn_start_track = (Button)findViewById(R.id.btn_start_track);
btn_start_track.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
data_limit = Long.parseLong(et_data_limit.getText().toString());
data_limit = data_limit * 1024;
Log.i("enter", String.valueOf(data_limit));
//data_limit = data_limit + sharedPreferences.getLong("data", 0);
editor.putLong("data", data_limit);
editor.commit();
Intent intent = new Intent(MainActivity.this, DataTracking.class);
intent.putExtra("data limit", data_limit);
MainActivity.this.startService(intent);
}
});
}
private boolean isPermissionAllowed() {
//Getting the permission status
int result = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_WIFI_STATE);
int result1 = ContextCompat.checkSelfPermission(this, Manifest.permission.CHANGE_WIFI_STATE);
int result2 = ContextCompat.checkSelfPermission(this, Manifest.permission.MODIFY_PHONE_STATE);
//If permission is granted returning true
if (result == PackageManager.PERMISSION_GRANTED && result1 == PackageManager.PERMISSION_GRANTED &&
result2 == PackageManager.PERMISSION_GRANTED)
return true;
//If permission is not granted returning false
return false;
}
private void requestPermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.ACCESS_WIFI_STATE) &&
ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.CHANGE_WIFI_STATE) &&
ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.MODIFY_PHONE_STATE)){
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this,new String[]{
Manifest.permission.ACCESS_WIFI_STATE, Manifest.permission.CHANGE_WIFI_STATE,
Manifest.permission.MODIFY_PHONE_STATE},STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
//Checking the request code of our request
if(requestCode == STORAGE_PERMISSION_CODE){
//If permission is granted
if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
//Displaying a toast
Toast.makeText(this,"Permission granted!",Toast.LENGTH_LONG).show();
}else{
//Displaying another toast if permission is not granted
Toast.makeText(this,"Permission denied! App may not work properly",Toast.LENGTH_LONG).show();
}
}
}
}
DataTracking.java
public class DataTracking extends Service {
private long data_limit;
private long data_used;
public DataTracking(){
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
data_limit = intent.getExtras().getLong("data limit");
Log.i("data", String.valueOf(data_limit));
Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_SHORT).show();
onHandleIntent(intent);
return Service.START_STICKY;
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
protected void onHandleIntent(#Nullable Intent intent) {
TrafficStats trafficStats = new TrafficStats();
long mtx = TrafficStats.getMobileTxBytes();
long mrx = TrafficStats.getMobileRxBytes();
data_used = mtx + mrx;
Toast.makeText(getApplicationContext(), data_used + "-" + data_limit, Toast.LENGTH_SHORT).show();
if(data_used >= data_limit){
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
try{
TelephonyManager telephonyManager = (TelephonyManager) getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
Method setMobileDataStatus = telephonyManager.getClass().getDeclaredMethod("setDataEnabled", boolean.class);
if (null != setMobileDataStatus){
setMobileDataStatus.invoke(telephonyManager, false);
stopSelf();
}
}
catch (Exception e){
e.printStackTrace();
}
}
}
}
Related
The permission dialog does not show up on Android 9 and below. My code works fine on Android 11. i've tried ActivityCompat.requestPermissions() and ActivityResultLauncher but none of them work.
When it runs the line permissionResultLauncher.launch() my app crashes and it also crashes the emulator, such that i have to delete the Emulator and reinstall a new one, otherwise it won't show me anything on the screen.
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
...
</application>
public class MainActivity extends AppCompatActivity{
private ActivityMainBinding binding;
private long pressedTime;
private ActivityResultLauncher<String[]> permissionResultLauncher;
private boolean isRecordPermGranted = false;
private boolean isWritePermGranted = false;
private int totalCount;
private DBHelper dbHelper;
private ImageButton imgbtnRecord, imgbtnList;
private ImageView ivRestore;
private TextView tvLoading, tvRecord;
private boolean asyncTaskRunning;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = ActivityMainBinding.inflate(getLayoutInflater());
setContentView(binding.getRoot());
SharedPreferences prefs = getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
totalCount = prefs.getInt("counter", 0);
if(totalCount < 4){
totalCount++;
editor.putInt("counter", totalCount);
editor.commit();
}
dbHelper = new DBHelper(this);
asyncTaskRunning = false;
imgbtnRecord = (ImageButton) findViewById(R.id.imgbtnRecord);
imgbtnList = (ImageButton) findViewById(R.id.imgbtnList);
tvLoading = findViewById(R.id.tvLoading);
tvRecord = findViewById(R.id.tvRecord);
ivRestore = findViewById(R.id.ivRestore);
tvLoading.setVisibility(View.GONE);
ivRestore.setVisibility(View.GONE);
imgbtnRecord.setVisibility(View.VISIBLE);
imgbtnList.setVisibility(View.VISIBLE);
tvRecord.setVisibility(View.VISIBLE);
isRecordPermGranted = ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED;
isWritePermGranted = ContextCompat.checkSelfPermission(MainActivity.this,Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED;
permissionResultLauncher = registerForActivityResult(new ActivityResultContracts.RequestMultiplePermissions(), new ActivityResultCallback<Map<String, Boolean>>() {
#Override
public void onActivityResult(Map<String, Boolean> result) {
if(result.get(Manifest.permission.RECORD_AUDIO)!= null){
isRecordPermGranted = result.get(Manifest.permission.RECORD_AUDIO);
Log.d("3","-------------------------" + isRecordPermGranted);
}
if(result.get(Manifest.permission.WRITE_EXTERNAL_STORAGE)!= null){
isWritePermGranted = result.get(Manifest.permission.WRITE_EXTERNAL_STORAGE);
Log.d("4","-------------------------" + isWritePermGranted);
}
if(isWritePermGranted == false || isRecordPermGranted == false){
if(totalCount <3){
finishAffinity();
}else{
Intent intent = new Intent( MainActivity.this, PermissionActivity.class);
startActivity(intent);
}
}
}
});
imgbtnRecord.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(isRecordPermGranted == false){
requestPermission();
}else{
openRecordingActivity();
}
}
});
imgbtnList.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(!isRecordPermGranted || !isWritePermGranted){
requestPermission();
}else{
openRecordingsListActivity();
}
}
});
}
public void openRecordingsListActivity() {
Intent intent = new Intent(this, RecordingsListActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
startActivity(intent);
}
public void openRecordingActivity(){
Intent intent = new Intent(this, RecordingActivity.class);
startActivity(intent);
}
#Override
public void onBackPressed() {
if(pressedTime + 2000 > System.currentTimeMillis()){
super.onBackPressed();
Intent a = new Intent(Intent.ACTION_MAIN);
a.addCategory(Intent.CATEGORY_HOME);
a.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(a);
}else{
Toast.makeText(this, "Press back again to exit", Toast.LENGTH_SHORT).show();
}
pressedTime = System.currentTimeMillis();
}
public void requestPermission(){
List<String> permissionRequests = new ArrayList<>();
if(!isRecordPermGranted && !isWritePermGranted){
permissionRequests.add(Manifest.permission.RECORD_AUDIO);
permissionRequests.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}else if(!isRecordPermGranted){
permissionRequests.add(Manifest.permission.RECORD_AUDIO);
}else if(!isWritePermGranted){
permissionRequests.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
Log.d("permissionRequests list", permissionRequests.toString());
if(!permissionRequests.isEmpty()){
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.P){
boolean shouldShowRationale = false;
if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) ){
shouldShowRationale = true;
Log.d("1","-------------------------");
}
if( ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO)){
shouldShowRationale = true;
Log.d("2","-------------------------");
}
if(shouldShowRationale){
Toast.makeText(this, "Permissions Needed!", Toast.LENGTH_SHORT).show();
Log.d("5","-------------------------");
}else{
permissionResultLauncher.launch(permissionRequests.toArray(new String[0]));
Log.d("6","-------------------------");
}
}else{
Log.d("old permission ", permissionRequests.toArray(new String[permissionRequests.size()])+" " );
ActivityCompat.requestPermissions(MainActivity.this,permissionRequests.toArray(new String[permissionRequests.size()]), 5);
}
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if(requestCode == 5){
for (int i =0; i< permissions.length; i++){
if(permissions[i].equals(Manifest.permission.RECORD_AUDIO) && grantResults[i] != PackageManager.PERMISSION_GRANTED){
isRecordPermGranted = false;
}
if(permissions[i].equals(Manifest.permission.WRITE_EXTERNAL_STORAGE) && grantResults[i] != PackageManager.PERMISSION_GRANTED){
isWritePermGranted = false;
}
}
}
if(isWritePermGranted == false || isRecordPermGranted == false){
Log.d("REQUEST PERMISSIONS RESULT", "onPermissionResult");
if(totalCount <3){
finishAffinity();
}else{
Intent intent = new Intent( MainActivity.this, PermissionActivity.class);
startActivity(intent);
}
}
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
When i use the statement if(ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) || ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.RECORD_AUDIO )
then it runs the first part of the "OR" statement and shows one of the permission dialog but it never shows both, even with an "&&" or my current code in the requestPermission()
i've tried it without shouldShowRequestPermissionRationale, but it still doesn't work.
I've also added the permissions in the AndroidManifest file.
My application is all about an EMERGENCY SMS where I just click my volume button and a simulated Message is sent to a certain Phone Number.
I wanted to know how I can make my application run on background when I want and close it whenever I want?
Hoping for your kind help, my Code is this:
public class MainActivity extends Activity {
private final static int SEND_SMS_PERMISSION_REQUEST_CODE = 111;
private Button sendMessage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sendMessage = findViewById(R.id.send_message);
final EditText phone = findViewById(R.id.phone_no);
final EditText message = findViewById(R.id.message);
sendMessage.setEnabled(false);
if (checkPermission(Manifest.permission.SEND_SMS)) {
sendMessage.setEnabled(true);
} else {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.SEND_SMS}, SEND_SMS_PERMISSION_REQUEST_CODE);
}
sendMessage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
}
});
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)) {
final EditText phone = findViewById(R.id.phone_no);
final EditText message = findViewById(R.id.message);
String msg = message.getText().toString();
String phonenumber = phone.getText().toString();
if (!TextUtils.isEmpty(msg) && !TextUtils.isEmpty(phonenumber)) {
if (checkPermission(Manifest.permission.SEND_SMS)) {
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(String.valueOf(phone), null, msg, null, null);
} else {
Toast.makeText(MainActivity.this, "Permission denied", Toast.LENGTH_SHORT).show();
}
} else {
Toast.makeText(MainActivity.this, "Enter a message and a phone number", Toast.LENGTH_SHORT).show();
}
return true;
} else
return super.onKeyDown(keyCode, event);
}
private boolean checkPermission(String permission) {
int checkPermission = ContextCompat.checkSelfPermission(this, permission);
return checkPermission == PackageManager.PERMISSION_GRANTED;
}
#Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
switch (requestCode) {
case SEND_SMS_PERMISSION_REQUEST_CODE:
if (grantResults.length > 0 && (grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
sendMessage.setEnabled(true);
}
break;
}
}
}
You have to start a service in your Application class to run it always. If you do that, your service will be always running.Even though user terminates your app from task manager or force stop your app, it will start running again in Background.
You can get more info about service from this link:
https://developer.android.com/training/run-background-service/create-service
I have problem with access to camera first time. I installed
my app. Next go to scan to QR Code. I use to scan QR Code google vision. App show dialog, which show about the permissions, next click "Allow",but camera doesn't open. But I go back activity and go to activity which scan QR Code, camera open.
my AdnroidManifest.xml
my class
public class ScanQrCodeActivity extends AppCompatActivity {
protected void attachBaseContext(Context context) {
super.attachBaseContext(CalligraphyContextWrapper.wrap(context));
}
private static final String TAG = "Barcode-reader";
// intent request code to handle updating play services if needed.
private static final int RC_HANDLE_GMS = 9001;
// permission request codes need to be < 256
private static final int RC_HANDLE_CAMERA_PERM = 2;
private DatabaseHandler helper;
private TextView title_app;
private CameraSource mCameraSource;
private CameraSourcePreview mPreview;
private GraphicOverlay<BarcodeGraphic> mGraphicOverlay;
String passwordString, eightChars, barcodeString, decodedBarcodeValue, OTP;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_scan_qr_code);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.ic_arrow_back);
title_app = (TextView) findViewById(R.id.toolbar_title);
helper = new DatabaseHandler(this);
mPreview = (CameraSourcePreview) findViewById(R.id.preview);
mGraphicOverlay = (GraphicOverlay<BarcodeGraphic>) findViewById(R.id.graphicOverlay);
eightChars = getIntent().getStringExtra("eightChars");
passwordString = getIntent().getStringExtra("passwordString");
int rc = ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA);
if (rc == PackageManager.PERMISSION_GRANTED) {
createCameraSource();
} else {
requestCameraPermission();
}
Snackbar snackbar = Snackbar.make(mGraphicOverlay, R.string.zeskanuj_wygenerowany_kod, Snackbar.LENGTH_INDEFINITE);
View mView = snackbar.getView();
TextView mTextView = (TextView) mView.findViewById(android.support.design.R.id.snackbar_text);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1)
mTextView.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
else
mTextView.setGravity(Gravity.CENTER_HORIZONTAL);
snackbar.show();
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.stage2, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == android.R.id.home) {
finish();
}
return super.onOptionsItemSelected(item);
}
private void requestCameraPermission() {
Log.w(TAG, "Camera permission is not granted. Requesting permission");
final String[] permissions = new String[]{Manifest.permission.CAMERA};
if (!ActivityCompat.shouldShowRequestPermissionRationale(this,
Manifest.permission.CAMERA)) {
ActivityCompat.requestPermissions(this, permissions, RC_HANDLE_CAMERA_PERM);
return;
}
final Activity thisActivity = this;
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(thisActivity, permissions,
RC_HANDLE_CAMERA_PERM);
}
};
findViewById(R.id.topLayout).setOnClickListener(listener);
Snackbar.make(mGraphicOverlay, "Aby móc wykryć Qr Koda potrzebny jest dostęp do kamery.",
Snackbar.LENGTH_INDEFINITE)
.setAction(R.string.ok, listener)
.show();
}
#SuppressLint("InlinedApi")
private void createCameraSource() {
boolean autoFocus = false;
boolean useFlash = false;
Context context = getApplicationContext();
BarcodeDetector barcodeDetector = new BarcodeDetector.Builder(context).build();
BarcodeTrackerFactory barcodeFactory = new BarcodeTrackerFactory(mGraphicOverlay);
barcodeDetector.setProcessor(
new MultiProcessor.Builder<>(barcodeFactory).build());
barcodeFactory.setNewBarcodeListener(new BarcodeTrackerFactory.OnNewBarcodeListener() {
#Override
public void onNewItem(final Barcode item) {
Log.d("BarcodeFound", "Found new barcode! " + item.rawValue);
title_app.post(new Runnable() {
#Override
public void run() {
if (!barcodeDetector.isOperational())
{
IntentFilter lowstorageFilter = new IntentFilter(Intent.ACTION_DEVICE_STORAGE_LOW);
boolean hasLowStorage = registerReceiver(null, lowstorageFilter) != null;
if (hasLowStorage) {
Toast.makeText(this, R.string.low_storage_error, Toast.LENGTH_LONG).show();
Log.w(TAG, getString(R.string.low_storage_error));
}
}
CameraSource.Builder builder = new CameraSource.Builder(getApplicationContext(), barcodeDetector)
.setFacing(CameraSource.CAMERA_FACING_BACK)
.setRequestedPreviewSize(1600, 1024)
.setRequestedFps(15.0f);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH)
{
builder = builder.setFocusMode(
autoFocus ? Camera.Parameters.FOCUS_MODE_CONTINUOUS_PICTURE : null);
}
mCameraSource = builder
.setFlashMode(useFlash ? Camera.Parameters.FLASH_MODE_TORCH : null)
.
build();
}
#Override
protected void onResume() {
super.onResume();
startCameraSource();
}
#Override
protected void onPause() {
super.onPause();
if (mPreview != null) {
mPreview.stop();
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mPreview != null) {
mPreview.release();
}
}
private void startCameraSource() throws SecurityException {
// check that the device has play services available.
int code = GoogleApiAvailability.getInstance().isGooglePlayServicesAvailable(
getApplicationContext());
if (code != ConnectionResult.SUCCESS) {
Dialog dlg =
GoogleApiAvailability.getInstance().getErrorDialog(this, code, RC_HANDLE_GMS);
dlg.show();
}
if (mCameraSource != null) {
try {
mPreview.start(mCameraSource, mGraphicOverlay);
} catch (IOException e) {
Log.e(TAG, "Unable to start camera source.", e);
mCameraSource.release();
mCameraSource = null;
}
}
}
}
In your code immplement the following method
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case 0:
boolean isPerpermissionForAllGranted = false;
if (grantResults.length > 0 && permissions.length==grantResults.length) {
for (int i = 0; i < permissions.length; i++){
if (grantResults[i] == PackageManager.PERMISSION_GRANTED){
isPerpermissionForAllGranted=true;
}else{
isPerpermissionForAllGranted=false;
}
}
Log.e("value", "Permission Granted, Now you can use local drive .");
} else {
isPerpermissionForAllGranted=true;
Log.e("value", "Permission Denied, You cannot use local drive .");
}
if(isPerpermissionForAllGranted){
// Fire here again for camera
createCameraSource();
}
break;
}
}
So what happens is When you fire the dialog for permission, you can implement the result method to come to know whether you were granted permission or not. So here you can check if the permission is granted for your permission request, You can again fire your method to open the camera.
Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app. This approach streamlines the app install process, since the user does not need to grant permissions when they install or update the app.
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public boolean checkPermission()
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_CALENDAR) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale((Activity) context, Manifest.permission.WRITE_CALENDAR)) {
AlertDialog.Builder alertBuilder = new AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("Write calendar permission is necessary to write event!!!");
alertBuilder.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else {
ActivityCompat.requestPermissions((Activity)context, new String[]{Manifest.permission.WRITE_CALENDAR}, MY_PERMISSIONS_REQUEST_WRITE_CALENDAR);
}
return false;
} else {
return true;
}
} else {
return true;
}
}
References :
https://developer.android.com/training/permissions/requesting.html
https://www.sitepoint.com/requesting-runtime-permissions-in-android-m-and-n/
http://www.theappguruz.com/blog/runtime-permissions-in-android-marshmallow
I am calling from my app. After ends that call, I am trying to get a call duration. But my code return call duration two times. Last call duration while making call and new call duration after ends a call. But I need only one call duration after user ends the new call. How can i achieve this. Here is my code. Thanks in advance.
public class MainActivity extends AppCompatActivity {
private static final int CALL_PERMISSION= 99;
private static final int READ_LOG_PERMISSION=11;
Button btnGetCallDuration;
Context mContext;
private int mFlag = 0;
String phNumber = "";
boolean flag=false;
String callDuration = "";
public static int REQ_CODE=1;
private boolean callPermission=false;
private boolean readlogPermission=false;
public static final int MULTIPLE_PERMISSIONS = 10; // code you want.
String[] permissions = new String[] {
Manifest.permission.READ_CALL_LOG,
Manifest.permission.CALL_PHONE,
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContext = MainActivity.this;
btnGetCallDuration = (Button) findViewById(R.id.btnGetCallDuration);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
checkPermissions();
}
btnGetCallDuration.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.v("onclick", "called");
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:121"));
startActivity(intent);
//flag = true;
}
});
}
private boolean checkPermissions() {
int result;
List<String> listPermissionsNeeded = new ArrayList<>();
for (String p:permissions) {
result = ContextCompat.checkSelfPermission(mContext,p);
if (result != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(p);
}
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeeded.toArray(new
String[listPermissionsNeeded.size()]), MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Log.v("request code",requestCode+"\t"+resultCode);
if(requestCode==REQ_CODE)
{
Log.v("request code",requestCode+"");
// getCallDruation();
}
}
#Override
public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
switch (requestCode) {
case MULTIPLE_PERMISSIONS: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permissions granted.
callPermission=true;
} else {
// no permissions granted.
callPermission=false;
}
return;
}
}
}
#Override
protected void onPause() {
super.onPause();
Log.v("Pause is called","pause");
flag=true;
}
public boolean checkLocationPermission() {
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.CALL_PHONE)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.CALL_PHONE)) {
// 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.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
CALL_PERMISSION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
CALL_PERMISSION);
}
return false;
} else {
return true;
}
}
public boolean readCallLogPermission() {
if (ContextCompat.checkSelfPermission(mContext,
Manifest.permission.READ_CALL_LOG)
!= PackageManager.PERMISSION_GRANTED) {
// Asking user if explanation is needed
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this,
Manifest.permission.READ_CALL_LOG)) {
// 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.
//Prompt the user once explanation has been shown
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.READ_CALL_LOG},
READ_LOG_PERMISSION);
} else {
// No explanation needed, we can request the permission.
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CALL_PHONE},
READ_LOG_PERMISSION);
}
return false;
} else {
callPermission=true;
return callPermission;
}
}
#Override
protected void onResume() {
super.onResume();
Log.v("flag","onrsume called");
if(flag)
{
getCallDruation();
flag=false;
}
}
private void getCallDruation() {
StringBuffer sb = new StringBuffer();
Uri contacts = CallLog.Calls.CONTENT_URI;
Log.v("get duration","called");
Cursor cur = getContentResolver().query(contacts, null, null, null, android.provider.CallLog.Calls.DATE + " DESC");
int number = cur.getColumnIndex(CallLog.Calls.NUMBER);
int duration = cur.getColumnIndex(CallLog.Calls.DURATION);
sb.append("Call Details : \n");
while (cur.moveToNext()) {
phNumber = cur.getString(number);
callDuration = cur.getString(duration);
sb.append("\nPhone Number:" + phNumber+"\t"+callDuration);
break;
}
cur.close();
String str = sb.toString();
Log.v("restult",str);
Toast.makeText(mContext, phNumber + "\t\t" + callDuration, Toast.LENGTH_SHORT).show();
}
}
This above code is called from onResume() life cycle method of activity.
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
While Reading Device ID etc. I am getting an error in Android 6.
How ever its working fine in all other versions 4.0,5.1 etc..
This is my code:
public class MyDevIDS extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
PackageInfo pInfo = null;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (NameNotFoundException e) {
e.printStackTrace();
}
String version = pInfo.versionName;
TextView versionText = (TextView) findViewById(R.id.tv7);
versionText.setText("Version : " + version);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imei_id = telephonyManager.getDeviceId();
TextView imei_idT = (TextView) findViewById(R.id.tv9);
String imei_idV = "<b><font color=#008000>" + imei_id + "</b></font>";
imei_idT.setText(Html.fromHtml("IMEI ID : " + imei_idV));
String device_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
TextView device_idT = (TextView) findViewById(R.id.tv10);
String device_idV = "<b><font color=#008000>" + device_id + "</b></font>";
device_idT.setText(Html.fromHtml("Device ID : " + device_idV));
}
}
this is error I am getting
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.test.devid/com.test.devid.MyDevIDS}: java.lang.SecurityException: getDeviceId: Neither user 10102 nor current process has android.permission.READ_PHONE_STATE.
How ever I Have given permission in manifest.. but I need to give Run time permissions in Android 6...
For that I followed this
https://developer.android.com/training/permissions/requesting.html
But I tried but its notworking..
Can any one suggest me how to use Run time permissions in my code..
public class MyDevIDS extends AppCompatActivity {
private static final int REQUEST_READ_PERMISSION = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_NOSENSOR);
if (CheckPermission(this, Manifest.permission.READ_PHONE_STATE)) {
YourStuffHandling();
} else {
RequestPermission(MyDevIDS.this, Manifest.permission.READ_PHONE_STATE, REQUEST_READ_PERMISSION );
}
}
private void YourStuffHandling() {
PackageInfo pInfo = null;
try {
pInfo = getPackageManager().getPackageInfo(getPackageName(), 0);
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
String version = pInfo.versionName;
TextView versionText = (TextView) findViewById(R.id.tv7);
versionText.setText("Version : " + version);
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
String imei_id = telephonyManager.getDeviceId();
TextView imei_idT = (TextView) findViewById(R.id.tv9);
String imei_idV = "<b><font color=#008000>" + imei_id + "</b></font>";
imei_idT.setText(Html.fromHtml("IMEI ID : " + imei_idV));
String device_id = Settings.Secure.getString(getContentResolver(), Settings.Secure.ANDROID_ID);
TextView device_idT = (TextView) findViewById(R.id.tv10);
String device_idV = "<b><font color=#008000>" + device_id + "</b></font>";
device_idT.setText(Html.fromHtml("Device ID : " + device_idV));
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
switch (permsRequestCode) {
case REQUEST_READ_PERMISSION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
YourStuffHandling();
} else {
ShowToast(getString(R.string.permission_needed_sms));
}
return;
}
}
}
public void RequestPermission(Activity thisActivity, String Permission, int Code) {
if (ContextCompat.checkSelfPermission(thisActivity,
Permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(thisActivity,
Permission)) {
} else {
ActivityCompat.requestPermissions(thisActivity,
new String[]{Permission},
Code);
}
}
}
public boolean CheckPermission(Context context, String Permission) {
if (ContextCompat.checkSelfPermission(context,
Permission) == PackageManager.PERMISSION_GRANTED) {
return true;
} else {
return false;
}
}
}
Android sdk has implemented Runtime permission feature from version 6.0 onwards. No matter weather you have given permission in manifest file you need to check that permission before you access.
You can check at runtime using either hasSystemFeature(PackageManager.FEATURE_TELEPHONY) or getPhoneType().
Or you can check by following format I have done for Camera permission
public void getCameraPermission(){
if (!checkPermission()) {
requestPermission();
}
}
private boolean checkPermission(){
int result = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
if (result == PackageManager.PERMISSION_GRANTED){
return true;
} else {
return false;
}
}
private void requestPermission(){
if (ActivityCompat.shouldShowRequestPermissionRationale(MainActivity.this, Manifest.permission.CAMERA)){
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.CAMERA}, 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) {
Toast.makeText(MainActivity.this,"Permission granted",Toast.LENGTH_SHORT).show();
//store permission in shared pref
}
else {
Toast.makeText(MainActivity.this,"Permission denied",Toast.LENGTH_SHORT).show();
//store permission in shared pref
}
break;
}
}