I have a problem when dragging an image from the camera and making it wallpaper to ImageView.
I used the following code and it works on versions less than 5 .
But versions 5 or higher code does not work permanently and the camera does not work at all
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.camera_capimage" android:grantUriPermissions="true" android:installLocation="auto">
<uses-sdk android:minSdkVersion="17" android:targetSdkVersion="28" />
<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"></application>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-feature android:name="android.hardware.camera" />
</manifest>
MainActivity
public class MainActivity : AppCompatActivity
{
public static Bitmap bitmap;
public static string fileName;
public ImageView _imageView;
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.activity_main);
Button button = FindViewById<Button>(Resource.Id.button1);
_imageView = FindViewById<ImageView>(Resource.Id.imageView1);
button.Click += BtnCamera_Click;
}
protected override void OnActivityResult(int requestCode, [GeneratedEnum] Result resultCode, Intent data)
{
base.OnActivityResult(requestCode, resultCode, data);
Bitmap bitmap = (Bitmap)data.Extras.Get("data");
_imageView.SetImageBitmap(bitmap);
}
private void BtnCamera_Click(object sender, System.EventArgs e)
{
Intent intent = new Intent(MediaStore.ActionImageCapture);
StartActivityForResult(intent, 0);
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
}
error message
Java.Lang.SecurityException: 'Permission Denial: starting Intent { act=android.media.action.IMAGE_CAPTURE cmp=com.android.camera/.Camera } from ProcessRecord{273b163 23970:com.companyname.camera_capimage/u0a98} (pid=23970, uid=10098) with revoked permission android.permission.CAMERA'
Related
In my xamarin android app, AltBeacon DidEnterRegion not triggered when MainLauncher attribute set to false for MainActivity. As I have SplashActivity for showing splash screen, I have to make the SplashActivity as my MainLauncher. I am using foreground service to detect iBeacon.
Code of my Application class:
namespace AltBeaconLibrarySample.Droid
{
#if DEBUG
[Application(Debuggable = true)]
#else
[Application(Debuggable = false)]
#endif
public class MainApplication : Application, IBootstrapNotifier
{
private RegionBootstrap regionBootstrap;
private BackgroundPowerSaver backgroundPowerSaver;
Region _generalRegion;
public bool IsStartedRanging { get; set; }
string foregroundServiceChannelId = "foregroundService";
string channelName = "ForegroundService";
int pendingIntentId = 1;
public MainApplication(IntPtr handle, JniHandleOwnership transer)
: base(handle, transer)
{
}
public void DidDetermineStateForRegion(int p0, Region p1)
{
}
public void DidEnterRegion(Region p0)
{
var beaconService = Xamarin.Forms.DependencyService.Get<IAltBeaconService>();
if (!IsStartedRanging)
{
beaconService.StartRanging();
IsStartedRanging = true;
}
}
public void DidExitRegion(Region p0)
{
var beaconService = Xamarin.Forms.DependencyService.Get<IAltBeaconService>();
if (IsStartedRanging)
{
beaconService.StopRanging();
IsStartedRanging = false;
}
beaconService.DidExitRegion();
}
public override void OnCreate()
{
base.OnCreate();
CrossCurrentActivity.Current.Init(this);
BeaconManager bm = BeaconManager.GetInstanceForApplication(this);
CreateNotificationChannel();
bm.EnableForegroundServiceScanning(GetForegroundServiceNotification(), 456);
bm.SetEnableScheduledScanJobs(false);
_generalRegion = new Org.Altbeacon.Beacon.Region/* AltBeaconOrg.BoundBeacon.Region*/("myEmptyBeaconId", Identifier.Parse("23A01AF0-232A-4518-9C0E-323FB773F5EF"), null, null);
regionBootstrap = new RegionBootstrap(this, _generalRegion);
backgroundPowerSaver = new BackgroundPowerSaver(this);
}
void CreateNotificationChannel()
{
if (Build.VERSION.SdkInt < BuildVersionCodes.O)
{
// Notification channels are new in API 26 (and not a part of the
// support library). There is no need to create a notification
// channel on older versions of Android.
return;
}
var channelDescription = "Foreground Sertrvice";
var channel = new NotificationChannel(foregroundServiceChannelId, channelName, NotificationImportance.High)
{
Description = channelDescription
};
var notificationManager = (NotificationManager)GetSystemService(NotificationService);
notificationManager.CreateNotificationChannel(channel);
}
public Notification GetForegroundServiceNotification()
{
NotificationCompat.Builder builder = new NotificationCompat.Builder(this, foregroundServiceChannelId);
builder.SetSmallIcon(Resource.Drawable.xamagonBlue);
builder.SetContentTitle("Scanning for Beacons");
Intent intent = new Intent(this, typeof(MainActivity));
PendingIntent pendingIntent = PendingIntent.GetActivity(this, pendingIntentId, intent, PendingIntentFlags.UpdateCurrent);
builder.SetContentIntent(pendingIntent);
return builder.Build();
}
}
}
Code of SplashActivity class:
namespace AltBeaconLibrarySample.Droid
{
[Activity(Label = "AltBeaconLibrarySample.Droid",
Icon = "#mipmap/icon",
Theme = "#style/MainTheme",
MainLauncher = true,
NoHistory = true,
LaunchMode = Android.Content.PM.LaunchMode.SingleInstance,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class SplashActivity : Activity
{
static readonly string TAG = "X:" + typeof(SplashActivity).Name;
public override void OnCreate(Bundle savedInstanceState, PersistableBundle persistentState)
{
base.OnCreate(savedInstanceState, persistentState);
}
// Launches the startup task
protected override void OnResume()
{
base.OnResume();
Task startupWork = new Task(() => { SimulateStartup(); });
startupWork.Start();
}
// Simulates background work that happens behind the splash screen
async void SimulateStartup()
{
Log.Debug(TAG, "Performing some startup work that takes a bit of time.");
await Task.Delay(50); // Simulate a bit of startup work.
Log.Debug(TAG, "Startup work is finished - starting MainActivity.");
StartActivity(new Intent(Application.Context, typeof(MainActivity)));
}
}
}
Android manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:versionCode="1" android:versionName="1.0" package="com.companyname.AltBeaconLibrarySample" android:installLocation="auto">
<uses-sdk android:minSdkVersion="21" android:targetSdkVersion="28" />
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application android:label="AltBeaconLibrarySample.Android">
<service android:enabled="true" android:exported="false" android:isolatedProcess="false" android:label="Beacon" android:name="org.altbeacon.beacon.service.BeaconService"></service>
<service android:enabled="true" android:exported="false" android:name="org.altbeacon.beacon.BeaconIntentProcessor"></service>
<receiver android:name="org.altbeacon.beacon.startup.StartupBroadcastReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
<action android:name="android.intent.action.ACTION_POWER_DISCONNECTED" />
</intent-filter>
</receiver>
</application>
</manifest>
Code of MainActivity class:
namespace AltBeaconLibrarySample.Droid
{
[Activity(Label = "AltBeaconLibrarySample.Droid",
Icon = "#mipmap/icon",
Theme = "#style/MainTheme",
MainLauncher = false,
LaunchMode = Android.Content.PM.LaunchMode.SingleInstance,
ConfigurationChanges = ConfigChanges.ScreenSize | ConfigChanges.Orientation)]
public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsAppCompatActivity, IBeaconConsumer
{
protected override void OnCreate(Bundle savedInstanceState)
{
TabLayoutResource = Resource.Layout.Tabbar;
ToolbarResource = Resource.Layout.Toolbar;
base.OnCreate(savedInstanceState);
Xamarin.Essentials.Platform.Init(this, savedInstanceState); // add this line to your code, it may also be called: bundle
CrossCurrentActivity.Current.Init(this, savedInstanceState);
global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
LoadApplication(new App());
}
public override void OnRequestPermissionsResult(int requestCode, string[] permissions, [GeneratedEnum] Android.Content.PM.Permission[] grantResults)
{
Xamarin.Essentials.Platform.OnRequestPermissionsResult(requestCode, permissions, grantResults);
PermissionsImplementation.Current.OnRequestPermissionsResult(requestCode, permissions, grantResults);
base.OnRequestPermissionsResult(requestCode, permissions, grantResults);
}
#region IBeaconConsumer Implementation
public void OnBeaconServiceConnect()
{
}
#endregion
protected override void OnDestroy()
{
base.OnDestroy();
DependencyService.Get<IAltBeaconService>().OnDestroy();
}
protected override void OnResume()
{
base.OnResume();
}
protected override void OnPause()
{
base.OnPause();
}
}
}
BeaconManager code snippet:
BeaconManager bm = BeaconManager.GetInstanceForApplication(Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity);
var iBeaconParser = new BeaconParser();
// Estimote > 2013
iBeaconParser.SetBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24");
bm.BeaconParsers.Add(iBeaconParser);
bm.BackgroundMode = false;
bm.Bind((IBeaconConsumer)Plugin.CurrentActivity.CrossCurrentActivity.Current.Activity);
I have spinner and webviewer in the same activity. I need the webviewer change when I select item from the spinner. I find the code but i try it and the webviwer not showing anything please help me to find the error in this code.
String:
<string-array name="Ragol">
<item value ="https://www.google.com.eg">link1</item>
<item value ="https://www.facebook.com">link2</item>
<item value ="https://www.riwaya.ml">link3</item>
<item value ="https://cooltext.com/">link4</item>
</string-array>
The Activity code:
<Spinner
android:id="#+id/spinner"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:dropDownSelector="#android:color/darker_gray"
android:dropDownWidth="#android:dimen/thumbnail_width"
tools:layout_editor_absoluteX="8dp"
tools:layout_editor_absoluteY="0dp" />
<WebView
android:id="#+id/webview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#android:color/darker_gray"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
tools:layout_editor_absoluteY="61dp">
</WebView>
The Java Code
public class WebScreen extends Activity implements OnItemSelectedListener {
String starturl = "http://www.google.com.eg", selected;
Spinner s1;
WebView webView;
#SuppressLint("SetJavaScriptEnabled")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_web_screen);
String sp1 = getIntent().getStringExtra("keyName");
if (sp1.contentEquals("Ragol")) {
s1 = (Spinner) findViewById(R.id.spinner);
ArrayAdapter<CharSequence>
adapter = ArrayAdapter.createFromResource(this,
R.array.Ragol, R.layout.my_spinner);
adapter.setDropDownViewResource(R.layout.spinner_dropdown_item);
s1.setAdapter(adapter);
s1.setOnItemSelectedListener(this);
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id)
{
selected = parent.getItemAtPosition(pos).toString();
webView = (WebView) findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient());
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webView.loadUrl(selected);
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
webView.loadUrl(starturl);
}
});
}
}
Can somebody tell me what am I missing. I have a webview app. It works fine except this, when I close app onesignal notification arrives fine, but when I click notification app does not open. Here is some code related to this problem.
I have been searching for solution but what ever I have tried it does not work.
When app is running notification comes and opens fine, but when it is closed it wont start app.
Thanks.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
OneSignal.startInit(this)
.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification)
.unsubscribeWhenNotificationsAreDisabled(true)
.setNotificationOpenedHandler(new
OneSignal.NotificationOpenedHandler() {
#Override
public void notificationOpened(OSNotificationOpenResult
result) {
String launchURL =
result.notification.payload.launchURL;
Intent intent = new Intent(getApplicationContext(),
NotificationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT
| Intent.FLAG_ACTIVITY_NEW_TASK);
intent.putExtra("url", launchURL);
startActivity(intent);
}
})
.init();
}
public class NotificationExtender extends NotificationExtenderService {
#Override
protected boolean onNotificationProcessing(OSNotificationReceivedResult notification) {
OverrideSettings overrideSettings = new OverrideSettings();
overrideSettings.extender = new NotificationCompat.Extender() {
#Override
public NotificationCompat.Builder extend(NotificationCompat.Builder builder) {
// Sets the background notification color to Green on Android 5.0+ devices.
return builder.setColor(new BigInteger("#005aaa", 16).intValue())
.setSmallIcon(R.drawable.ic_stat_onesignal_default);
}
};
OSNotificationDisplayedResult displayedResult = displayNotification(overrideSettings);
Log.d("OneSignalExample", "Notification displayed with id: " + displayedResult.androidNotificationId);
return true;
}
}
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".NotificationExtender"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="false">
<intent-filter>
<action android:name="com.onesignal.NotificationExtender" />
</intent-filter>
</service>
<activity
android:name=".NotificationActivity"
android:parentActivityName=".MainActivity"/>
<meta-data android:name="com.onesignal.NotificationOpened.DEFAULT" android:value="DISABLE" />
I solved it.
It seams you do not need NotificationOpenedHandler, just NotificationExtender extends NotificationExtenderService. It look like this:
public class NotificationExtender extends NotificationExtenderService {
public NotificationExtender() {
super();
}
#Override
protected boolean onNotificationProcessing(OSNotificationReceivedResult receivedResult) {
Intent intent = new Intent(getApplicationContext(), NotificationActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
intent.putExtra("url", receivedResult.payload.launchURL);
PendingIntent pendingIntent = PendingIntent.getActivity(
getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT | PendingIntent.FLAG_ONE_SHOT);
Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.ic_stat_onesignal_default)
.setSound(uri)
.setContentTitle(receivedResult.payload.title)
.setContentText(receivedResult.payload.body)
.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_onesignal_large_icon_default))
.setColor(getResources().getColor(R.color.logo_color))
.setAutoCancel(true)
.setContentIntent(pendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(0, notificationBuilder.build());
return true;
}
}
I'm developing an app using Xamarin forms, I have a Broadcast receiver which monitors connectivity change. It works perfectly when application is active, but when I close my application(just slide it out from the recent apps tray) the Broadcast receiver stops working.I'm not able find where i'm committing mistake.
Below is my manifest file :
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.ETMS.taskmanagement.permission.C2D_MESSAGE" />
<permission android:name="com.ETMS.taskmanagement.permission.C2D_MESSAGE" android:protectionLevel="signature" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
<uses-permission android:name="android.permission.ACCESS_MOCK_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.CHANGE_NETWORK_STATE" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE" />
below is my Broadcast Receiver :
namespace ETMS.Droid.Receiver
{
[BroadcastReceiver(Enabled = true,Exported = true)]
[IntentFilter(new string[] { "android.net.conn.CONNECTIVITY_CHANGE" })]
class ConnectivityReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Log.Debug("ETMS CONNECTIVITY ", "Reached Connectivity");
LocalPreferenceManager mManager = new LocalPreferenceManager(context);
bool hasNetwork = !intent.GetBooleanExtra(ConnectivityManager.ExtraNoConnectivity, false);
if (hasNetwork)
{
bool authenticate = GeofenceSPService.AuthenticateSp();
if (authenticate)
{
GeofenceSPService.SyncGeofenceToServer(mManager);
GeofenceSPService.LogTrace("Raj", "Connectivity Receiver : " + authenticate);
}
}
else
{
Log.Error("ETMS CONNECTIVITY ", "Reached Connectivity");
}
}
public bool IsConnected(Context context)
{
ConnectivityManager cm = (ConnectivityManager) context.GetSystemService(Context.ConnectivityService);
NetworkInfo activeNetwork = cm.ActiveNetworkInfo;
bool isConnected = activeNetwork != null && activeNetwork.IsConnectedOrConnecting;
return isConnected;
}
private void SendNotification(string networkDetails, Context context)
{
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(context, typeof(MainActivity));
// Construct a task stack
TaskStackBuilder stackBuilder = TaskStackBuilder.Create(context);
// Add the main Activity to the task stack as the parent.
stackBuilder.AddParentStack(Java.Lang.Class.FromType(typeof(MainActivity)));
// push the content Intent onto the stack.
stackBuilder.AddNextIntent(notificationIntent);
// Get a PendingINtent containing the entire backstack
PendingIntent notificationPendingIntent = stackBuilder.GetPendingIntent(0, PendingIntentFlags.UpdateCurrent);
// Get a notification builder that's compatible with platform versions >= 4
Notification.Builder builder = new Notification.Builder(context);
//Define the notification settings.
builder.SetSmallIcon(Resource.Drawable.networkoff)
.SetContentTitle(networkDetails)
.SetContentText("Network Connectivity")
.SetContentIntent(notificationPendingIntent);
// Dismiss the notification once the user touches it.
builder.SetAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) context.GetSystemService(Context.NotificationService);
mNotificationManager.Notify(0, builder.Build());
}
}
}
I have two fragments in my main Activity.
Each fragment should play different youtube video.
But In my code,both the fragments are playing same video although I passes different url to the two instances of YouTubePlayerSupportFragment class.
MainActivity-
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
VideoFragment f1=VideoFragment.newInstance("kXYiU_JCYtU");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container1, f1).commit();
VideoFragment f2 = new VideoFragment();
f2=VideoFragment.newInstance("k4V3Mo61fJM");
getSupportFragmentManager().beginTransaction().replace(R.id.fragment_container2, f2).commit();
}
activity_main.xml-
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
tools:context=".MainActivity"
>
<FrameLayout
android:id="#+id/fragment_container1"
android:layout_width="fill_parent"
android:layout_height="150dp"
>
</FrameLayout>
<FrameLayout
android:id="#+id/fragment_container2"
android:layout_width="fill_parent"
android:layout_height="150dp"
android:layout_alignParentLeft="true"
android:layout_below="#+id/fragment_container1"
>
</FrameLayout>
</RelativeLayout>
VideoFragment class-
public VideoFragment() { }
public static VideoFragment newInstance(String url) {
VideoFragment f = new VideoFragment();
Bundle b = new Bundle();
b.putString("url", url);
f.setArguments(b);
f.init();
return f;
}
private void init() {
initialize("AIzaSyDM2vaVDpwGGFEcQCcD_hA38ZQo2Tqa06o", new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(getArguments().getString("url"));
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
});
}
I would be grateful if anyone could help me.
Its impossible. Youtube player based on singletone patern, so every time you will get same player