I have an Android app that in the main class start a service. So I have this error
06-09 09:34:00.880 26760-26760/it.eresult.decipher E/AndroidRuntime: FATAL EXCEPTION: main
java.lang.RuntimeException: Unable to start service it.eresult.decipher.service.CriticalInformationService#4111f448 with Intent { cmp=it.eresult.decipher/.service.CriticalInformationService }: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W#41117e00 -- permission denied for this window type
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2376)
at android.app.ActivityThread.access$1900(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
Caused by: android.view.WindowManager$BadTokenException: Unable to add window android.view.ViewRootImpl$W#41117e00 -- permission denied for this window type
at android.view.ViewRootImpl.setView(ViewRootImpl.java:537)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:301)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:215)
at android.view.WindowManagerImpl$CompatModeWrapper.addView(WindowManagerImpl.java:140)
at it.eresult.decipher.service.CriticalInformationService.onStartCommand(CriticalInformationService.java:37)
at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:2359)
at android.app.ActivityThread.access$1900(ActivityThread.java:123)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1210)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4424)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
at dalvik.system.NativeStart.main(Native Method)
This is my AndroidMainfest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="it.eresult.decipher">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:background="#color/colorToolBar">
<activity
android:name=".activity.MainActivity">
</activity>
<activity
android:name=".activity.LoginActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".service.CriticalInformationService"
android:label="Critical Information Service"
>
</service>
<uses-permission
android:name="android.permission.SYSTEM_ALERT_WINDOW" />
</application>
</manifest>
With this code, I try to start the service:
startService(new Intent(this, CriticalInformationService.class));
Then, this is the Service:
public class CriticalInformationService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
WindowManager mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
LayoutInflater mInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
View mView = mInflater.inflate(R.layout.settings_activity, null);
WindowManager.LayoutParams mLayoutParams = new WindowManager.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT,
ViewGroup.LayoutParams.WRAP_CONTENT, 0, 0,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
| WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON
/* | WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON */,
PixelFormat.RGBA_8888);
mWindowManager.addView(mView, mLayoutParams);
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
EDIT
This is the MainActivity that launch Service
public class LoginActivity extends AppCompatActivity {
private static final int REQUEST_RUNTIME_PERMISSION = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
checkPremission();
//startService(new Intent(this, CriticalInformationService.class));
}
void checkPremission() {
//select which permission you want
final String permission = Manifest.permission.SYSTEM_ALERT_WINDOW;
// if in fragment use getActivity()
if (ContextCompat.checkSelfPermission(LoginActivity.this, permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this, permission)) {
} else {
ActivityCompat.requestPermissions(LoginActivity.this, new String[]{permission}, REQUEST_RUNTIME_PERMISSION);
}
} else {
// you have permission go ahead launch service
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_RUNTIME_PERMISSION:
final int numOfRequest = grantResults.length;
final boolean isGranted = numOfRequest == 1
&& PackageManager.PERMISSION_GRANTED == grantResults[numOfRequest - 1];
if (isGranted) {
// you have permission go ahead launch service
}else{
// you dont have permission show toast
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
How can I fix this error?
public class LoginActivity extends AppCompatActivity {
private static final int REQUEST_RUNTIME_PERMISSION = 1;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_login);
checkPremission();
//startService(new Intent(this, CriticalInformationService.class));
}
void checkPremission() {
//select which permission you want
final String permission = Manifest.permission.SYSTEM_ALERT_WINDOW;
// if in fragment use getActivity()
if (ContextCompat.checkSelfPermission(LoginActivity.this, permission)
!= PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this, permission)) {
} else {
ActivityCompat.requestPermissions(LoginActivity.this, new String[]{permission}, REQUEST_RUNTIME_PERMISSION);
}
} else {
// you have permission go ahead launch service
startService(new Intent(this, CriticalInformationService.class));
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case REQUEST_RUNTIME_PERMISSION:
final int numOfRequest = grantResults.length;
final boolean isGranted = numOfRequest == 1
&& PackageManager.PERMISSION_GRANTED == grantResults[numOfRequest - 1];
if (isGranted) {
// you have permission go ahead launch service
startService(new Intent(this, CriticalInformationService.class));
}else{
// you dont have permission show toast
}
break;
default:
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
}
Related
That's what I trying to do in the background, but nothing happens. I'm using push notifications(Firebase Messaging Service) to run this code.
phoneAccountHandle = PhoneAccountHandle(
ComponentName(
packageName,
DoctorConnectionService::class.java.name
), phoneAccountHandleId
)
val builder = PhoneAccount.builder(phoneAccountHandle, "My account")
builder.setCapabilities(PhoneAccount.CAPABILITY_CALL_PROVIDER or PhoneAccount.CAPABILITY_CONNECTION_MANAGER)
val phoneAccount = builder.build()
val test = telecomManager
telecomManager?.registerPhoneAccount(phoneAccount)
telecomManager?.addNewIncomingCall(phoneAccountHandle, Bundle())
You can try BroadcastReceiver. Here is my BroadcastReceiver's Class & MainActivity. In here I just Toast a message (Incoming Call) when application is in background:
MainActivity:
public class MainActivity extends AppCompatActivity {
BroadcastReceiver callReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
checkPermission();
callReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
/*Do Whatever You Want When You Reciveing a Call And App is Open*/
}
};
IntentFilter callFilter = new IntentFilter("android.intent.action.PHONE_STATE");
registerReceiver(callReceiver, callFilter);
}
#Override
protected void onDestroy() {
super.onDestroy();
unregisterReceiver(callReceiver);
}
private void checkPermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_PHONE_STATE}, 100);
}
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == 100) {
}
}
}
And here is my BroadcastReceiver class:
public class IncomingCallReciver extends BroadcastReceiver{
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, ".:Incoming Call:.", Toast.LENGTH_SHORT).show();
/*Do Whatever You Want When You Reciveing a Call And App is In Background*/
}
}
Then Add READ_PHONE_STATE Permission in Manifest and add BroadcastReceiver's class in Manifest, Inside Application Tag:
<receiver android:name=".IncomingCallReciver">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
this is my AndroidManifest.xml file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.mycamera">
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
and this is the corresponding java file for the above code:
package com.example.mycamera;
import android.content.Intent;
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 {
Button btn;
ImageView imagedisplay;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.image);
imagedisplay = (ImageView)findViewById(R.id.image_capture);
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent , 0);
}
});
}
#Override
public void onActivityResult(int requestCode , int resultCode, Intent data){
super.onActivityResult(requestCode,resultCode,data);
Bitmap bitmap= (Bitmap) data.getExtras().get("data");
imagedisplay.setImageBitmap(bitmap);
}
}
this is working fine without even including:
<uses-permission android:name="android.permission.CAMERA"/>
in AndroidManifest.xml file.
But on including the camera permission it is not working and showing the error your app has stopped working.
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
private static final int MY_CAMERA_PERMISSION_CODE = 100;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.imageView = (ImageView)this.findViewById(R.id.imageView1);
Button photoButton = (Button) this.findViewById(R.id.button1);
photoButton.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
if (checkSelfPermission(Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED)
{
requestPermissions(new String[]{Manifest.permission.CAMERA}, MY_CAMERA_PERMISSION_CODE);
}
else
{
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults)
{
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
if (requestCode == MY_CAMERA_PERMISSION_CODE)
{
if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
{
Toast.makeText(this, "camera permission granted", Toast.LENGTH_LONG).show();
Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(cameraIntent, CAMERA_REQUEST);
}
else
{
Toast.makeText(this, "camera permission denied", Toast.LENGTH_LONG).show();
}
}
protected void onActivityResult(int requestCode, int resultCode, Intent data)
{
if (requestCode == CAMERA_REQUEST && resultCode == Activity.RESULT_OK)
{
Bitmap photo = (Bitmap) data.getExtras().get("data");
imageView.setImageBitmap(photo);
}
}
}
Try once this :
private boolean isVersionBelowMarshmallow = false;
public boolean checkPermissionForCamera() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.M) {
isVersionBelowMarshmallow = true;
}
if (isVersionBelowMarshmallow)
return true;
int result = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA);
return result == PackageManager.PERMISSION_GRANTED;
}
Try these Solution Once :
if (checkAndRequestPermissions(getContext())) {
}
private boolean checkAndRequestPermissions(Context context) {
int ExtstorePermission = ContextCompat.checkSelfPermission(context, Manifest.permission.READ_EXTERNAL_STORAGE);
int cameraPermission = ContextCompat.checkSelfPermission(context, Manifest.permission.CAMERA);
List<String> listPermissionsNeeded = new ArrayList<>();
if (cameraPermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.CAMERA);
}
if (ExtstorePermission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(Manifest.permission.WRITE_EXTERNAL_STORAGE);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(getActivity(), listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "FlagUp Requires Access to Your Storage.", Toast.LENGTH_SHORT).show();
// finish();
//super.onRequestPermissionsResult(requestCode, permissions, grantResults);
}
if (ContextCompat.checkSelfPermission(getContext(), Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "FlagUp Requires Access to Camara.", Toast.LENGTH_SHORT).show();
// finish();
}
}
I have created several activities via Intent's in the past, yet this error baffles me.
This is a simple tutorial given on Developer.Android's website for creating a new Activity
Problem:
The error is thrown before onPause() and after calling startActivityForResult() all in the same Activtiy
Error:
E/ActivityThread: Performing pause of activity that is not resumed: {wrap302.nmu.assignment_6_task_2_server/wrap302.nmu.assignment_6_task_2_server.MainActivity}
java.lang.RuntimeException: Performing pause of activity that is not resumed: {wrap302.nmu.assignment_6_task_2_server/wrap302.nmu.assignment_6_task_2_server.MainActivity}
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3398)
at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3386)
at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:3361)
at android.app.ActivityThread.-wrap13(ActivityThread.java)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1374)
at android.os.Handler.dispatchMessage(Handler.java:102)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5471)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
Minimal Working Example:
public class MainActivity extends Activity {
public static String isHost = "isHost";
private Context mContext;
private Button btnHostGame;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_main);
btnHostGame = (Button) findViewById(R.id.btnHostGame);
btnHostGame.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
startGameActivity(true);
}
});
}
private void startGameActivity(boolean isHosting) {
Intent intent = new Intent(mContext, GameConnector.class);
intent.putExtra(isHost, isHosting);
startActivityForResult(intent, 0); //Exception occurs after this method
}
#Override
protected void onResume() {
super.onResume();
getActionBar().hide();
}
// Exception occurs before this method is called
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Toast.makeText(mContext, "Did you win?", Toast.LENGTH_SHORT).show();
}
}
This is quite strange to me, any advice?
UPDATE
AndroidManifest request
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="wrap302.nmu.assignment_6_task_2_server">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.VIBRATE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme.NoActionBar">
<activity android:name=".MainActivity"
android:label="#string/title_game">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<activity
android:name=".GameConnector"
android:label="#string/title_gameconnector">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
<activity
android:name=".Game"
android:label="#string/title_game">
<intent-filter>
<action android:name="android.intent.action.SEND"/>
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
</activity>
</application>
</manifest>
yes, GameConnector does get created without a problem.
However, the Exception is thrown before the GameConnector.onCreate method is called.
UPDATE 2
GameConnector code request
public class GameConnector extends Activity implements FragmentFinishListener{
public static String GameType = "GameType", GameConnect = "GameConnect";
public static String PlayerName = "PlayerName";
private FragmentManager fragmentManager;
private Fragment gameTypeFragment;
private Intent gameIntent;
private boolean isHosting;
private Context mContext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_gameconnector);
mContext = this;
gameIntent = getIntent();
if (gameIntent.hasExtra(MainActivity.isHost))
isHosting = gameIntent.getBooleanExtra(MainActivity.isHost, false);
fragmentManager = getFragmentManager();
gameTypeFragment = (isHosting)
? new FragmentHostGame().setOnFragmentFinishListener(this)
: new FragmentJoinGame().setOnFragmentFinishListener(this);
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
fragmentTransaction.add(R.id.fragmentContainer, gameTypeFragment, GameType);
fragmentTransaction.commit();
}
#Override
public void finished(Bundle bundle) {
GameConnection gameConnection = null;
if (bundle != null){
if (bundle.containsKey(GameConnect))
gameConnection = (GameConnection) bundle.getSerializable(GameConnect);
}
fragmentManager.beginTransaction().remove(gameTypeFragment).commit();
startGame(isHosting, gameConnection);
}
private void startGame(boolean isHosting, GameConnection gameConnection) {
Intent intent = new Intent(mContext, Game.class);
intent.putExtra(MainActivity.isHost, isHosting);
intent.putExtra(GameConnect, gameConnection);
startActivityForResult(intent, 0);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (data != null){
switch (requestCode){
case 0:{
if (resultCode == 0){
finishActivity(resultCode);
}
else {
setResult(resultCode, data);
finishActivity(1);
}
break;
}
}
}
setResult(resultCode, null);
finishActivity(1);
}
}
While making a call from the app, it is not working. I have added the permission in android manifest, but it is still not working. Please see my code and help me soon.
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:999999999"));
if (ActivityCompat.checkSelfPermission(menu.this,
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
return;
}
startActivity(callIntent);
}
});
This code should work:
Intent intent = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" + "Your Phone_number"));
startActivity(intent);
Permission in Manifest:
<uses-permission android:name="android.permission.CALL_PHONE" />
but i highly recommend using ACTION_DIAL instead. It opens up the dialer screen with the number entered instead. This gives the user more flexibility. Also you don't need to have the CALL_PHONE permission with this one.
Here is an update:
With CALL_PHONE permission
Main Class
public class MainActivity extends AppCompatActivity {
private final int CALL_PHONE = 1;
private Button dialBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
dialBtn = (Button) findViewById(R.id.dial_button);
//In android 6 we need to ask for permissions:
if (ActivityCompat.checkSelfPermission(getApplicationContext(),
Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
requestPermissions(new String[]{Manifest.permission.CALL_PHONE}, CALL_PHONE);
} else {
Toast.makeText(getApplicationContext(), "We need permissions to dial.", Toast.LENGTH_LONG).show();
}
} else {
setupView();
}
}
private void setupView() {
dialBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent callIntent = new Intent(Intent.ACTION_CALL);
callIntent.setData(Uri.parse("tel:999999999"));
// We have to implement this part because ... yeah permissions in android.....
if (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
Toast.makeText(getApplicationContext(), "We need permissions to dial.", Toast.LENGTH_LONG).show();
return;
}
startActivity(callIntent);
}
});
}
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case CALL_PHONE:
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
setupView();
} else {
Toast.makeText(getApplicationContext(), "We need permissions to dial.", Toast.LENGTH_LONG).show();
}
break;
}
}
My manifest:
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
Without the permission check and only using ACTION_DIAL
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button dialBtn = (Button) findViewById(R.id.dial_button);
dialBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:999999999"));
startActivity(callIntent);
}
});
}
}
The last one is so much easier. Android permission checks are a pain in the ass.
I just made my own class. It's easier for the next time to also provide the error Stack trace. But for what I can see in your code is that your using menu.this I don't know for sure because u didn't provide enough information but I think this causes the error.
I hope I helped u out.
I am using ACTION_USER_PRESENT Broadcast Receiver in my application,
My Problem is that : I am getting the BroadCastReceiver only when my application is in Pause state.
Here is my manifest:
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
<receiver
android:name=".utils.receivers.ReminderBroadcastReceiver"
android:enabled="true"
android:exported="true" />
<receiver android:name=".utils.receivers.UserPresentBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
My Receiver:
public class UserPresentBroadcastReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
/*Sent when the user is present after
* device wakes up (e.g when the keyguard is gone)
* */
// MY STUFF - which works when my app is on paused state, but not when it is closed
}
}
am running on Marshmallo 6.0
Any help?
Getting runtime permision ofr Marshmallo 6.0 or greator.
public class RuntimePermission extends AppCompatActivity {
private static final int REQUEST_RUNTIME_PERMISSION = 123;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (CheckPermission(RuntimePermission.this, Manifest.permission.READ_PHONE_STATE)) {
// you have permission go ahead
} else {
// you do not have permission go request runtime permissions
RequestPermission(RuntimePermission.this, Manifest.permission.READ_PHONE_STATE, REQUEST_RUNTIME_PERMISSION);
}
}
#Override
public void onRequestPermissionsResult(int permsRequestCode, String[] permissions, int[] grantResults) {
switch (permsRequestCode) {
case REQUEST_RUNTIME_PERMISSION: {
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// you have permission go ahead
} else {
// you do not have permission show toast.
}
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;
}
}
}