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;
}
}
}
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();
}
}
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.
Hey guys I am working on an app which should connect to bluetooth devices. But at the moment I'm struggling with the problem that it doesn't find any bluetooth devices in my app but in the bluetooth settings it finds some. (my device runs android 6.x)
My code:
public class MainActivity extends AppCompatActivity {
private ProgressDialog progressDialogBluetoothDiscovery;
private ListView bluetoothDevices;
private ArrayList<String> bluetoothNearbyDevices;
private BluetoothAdapter mBluetoothAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
bluetoothDevices = (ListView) findViewById(R.id.bluetoothDevicesList);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
IntentFilter filter = new IntentFilter();
filter.addAction(BluetoothDevice.ACTION_FOUND);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_STARTED);
filter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
filter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(bluetoothBroadcast, filter);
bluetoothNearbyDevices = new ArrayList<>();
final FloatingActionButton searchDevices = (FloatingActionButton) findViewById(R.id.search_devices);
searchDevices.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
searchDevices();
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(bluetoothBroadcast);
}
private void searchDevices() {
if (mBluetoothAdapter == null) {
Toast.makeText(MainActivity.this, getResources().getString(R.string.bluetooth_not_supported), Toast.LENGTH_LONG).show();
return;
} else {
if (!mBluetoothAdapter.isEnabled()) {
Snackbar.make(findViewById(R.id.coordinatorLayout), getResources().getString(R.string.bluetooth_not_enabled), Snackbar.LENGTH_LONG).setAction(getResources().getString(R.string.activate_bluetooth), new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, MainActivity.CONTEXT_INCLUDE_CODE);
}
}).show();
} else {
scanForDevices();
}
}
}
private void scanForDevices() {
mBluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver bluetoothBroadcast = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
if (intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, -1) == BluetoothAdapter.STATE_ON) {
scanForDevices();
}
} else if (BluetoothAdapter.ACTION_DISCOVERY_STARTED.equals(action)) {
progressDialogBluetoothDiscovery = ProgressDialog.show(MainActivity.this, getResources().getString(R.string.bluetooth_discovery_title), getResources().getString(R.string.bluetooth_discovery_message), true);
} else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
progressDialogBluetoothDiscovery.dismiss();
ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(MainActivity.this, android.R.layout.simple_list_item_1, bluetoothNearbyDevices);
bluetoothDevices.setAdapter(arrayAdapter);
} else if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
String deviceName = device.getName();
String deviceHardwareAddress = device.getAddress(); // MAC address
Toast.makeText(MainActivity.this, deviceName, Toast.LENGTH_LONG).show();
bluetoothNearbyDevices.add(deviceName);
}
}
};
}
And my manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.package">
<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>
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
</manifest>
So do you have any Idea why it doesn't find any device in my app?
What version of Android are you running this on? If it is Android 6.x, I believe you need to add the ACCESS_COURSE_LOCATION permission to your manifest.
Below is how run time Permissions work Android 6.0 Marshmallow i.e:
> API level 23
For example:
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
switch (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION)) {
case PackageManager.PERMISSION_DENIED:
((TextView) new AlertDialog.Builder(this)
.setTitle("Runtime Permissions up ahead")
.setMessage("To find nearby bluetooth devices please click Allow on the runtime permissions popup." )
.setNeutralButton("Okay", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (ContextCompat.checkSelfPermission(getBaseContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(DeviceListActivity.this,
new String[]{Manifest.permission.ACCESS_COARSE_LOCATION},
REQUEST_ACCESS_COARSE_LOCATION);
}
}
})
.show()
.findViewById(android.R.id.message))
.setMovementMethod(LinkMovementMethod.getInstance());
break;
case PackageManager.PERMISSION_GRANTED:
break;
}
}
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);
}
}
}