Android m run time permission for reading from external storage - android-6.0-marshmallow

I have a dialog that loads tabLayout with 5 sections and its content are loaded using ViewPager with View Pager adapter. Now, in one of the sections, I have to load images from the gallery. I have written the runtime permission, but I cannot use the callback of the permission as I have implemented this dialog in a class that doesn't have an activity. I have no idea how to implement the callback method of permissions in an activity-less class.
public void makePermissionRequest(){
if(ContextCompat.checkSelfPermission(showEditorActivity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(showEditorActivity,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, permission_request_code);
}else{
fetchImagesFromDevice();
}
}
and for callback..
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
switch (requestCode) {
case permission_request_code: {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.i("permission..link", "allowed");
fetchImagesFromDevice();
}else{
Log.i("permission..link", "denied");
if (ContextCompat.checkSelfPermission(showEditorActivity, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(showEditorActivity, Manifest.permission.READ_EXTERNAL_STORAGE)) {
showMessageOKCancel("You need to allow access to your Internal Memory", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
//log to find out answer..
if (which == -1) {
makePermissionRequest();
}
}
});
}
}
}
}
}
}

Related

app get crashed on android 8.0 when foreground service starts xamarin.form android

I start the foreground service, when my app is going to background. On that time I go to setting page and change the permission status to Deny on Camera. My app get crashed on android 8.0.
My foreground service code like below:
namespace MyProj.Droid.Services
{
[Service]
public class MyProjService : Service
{
CancellationTokenSource _cts;
private static ILogger logger = DependencyService.Get<ILogManager>().GetLog();
public const string LOCATION_CHANNEL = "default";
NotificationManager manager;
NotificationCompat.Builder notification;
public override void OnCreate()
{
base.OnCreate();
manager = (NotificationManager)Forms.Context.GetSystemService("notification");
}
public override IBinder OnBind(Intent intent)
{
return null;
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
StartLocationServiceForeground();
return StartCommandResult.Sticky;
}
void StartLocationServiceForeground()
{
try
{
if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
{
var chan1 = new NotificationChannel(LOCATION_CHANNEL,
new Java.Lang.String("Primary"), NotificationImportance.High);
manager.CreateNotificationChannel(chan1);
notification = new NotificationCompat.Builder(Forms.Context, LOCATION_CHANNEL);
notification.SetOngoing(true)
.SetSmallIcon(Resource.Drawable.icon_transparent)
.SetContentTitle("MyProj 24x7 Trucker is running background")
.SetContentText("Tab for more information or to stop the app")
.SetColor(0x9c6114)
.SetPriority(NotificationCompat.PriorityHigh);
StartForeground(1, notification.Build());
}
}
catch(System.Exception ex)
{
}
}
public override void OnDestroy()
{
StopForeground(true);
if (manager!=null)
{
manager.CancelAll();
}
base.OnDestroy();
}
}
}
Can anyone please help to resolve this issue.

Filter Data from RecyclerView Firebase

I am trying to implement a searchview in my action bar and for that to filter the RecyclerView Data that I retrieved from Firebase. Right now I am looking for the code that I need to add to the recycleradapter to be able to filter the retrieved data.
This is how I added the recyclerView to my MainActivity.
Query query = mRef.orderByChild("city");
// everything else
FirebaseRecyclerAdapter<City, CityViewHolder> firebaseRecyclerAdapter =
new FirebaseRecyclerAdapter<City, CityViewHolder>(
City.class,
R.layout.city_starter,
CityViewHolder.class,
query
) {
#Override
protected void populateViewHolder(CityViewHolder viewHolder, City city, int position) {
viewHolder.setDetails(getApplicationContext(),
city.getCity());
}
// for click of parent item
#Override
public CityViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
CityViewHolder viewHolder = super.onCreateViewHolder(parent, viewType);
viewHolder.setOnClickListener(new CityViewHolder.ClickListener() {
#Override
public void onItemClick(View view, int position) {
//get Data from Firebase
String cCity = getItem(position).getCity();
// pass this data to new activity
Intent secondMainActivity = new Intent(view.getContext(), SecondMainActivity.class);
secondMainActivity.putExtra("city", cCity);
startActivity(secondMainActivity);
}
#Override
public void onItemLongClick(View view, int position) {
// possible to implement another way of interacting for a long click
}
});
return viewHolder;
}
};
// set adapter to recyclerview
mRecyclerView.setAdapter(firebaseRecyclerAdapter);
}
Is there anybody who is able to help?
Thank you :)
This is what I found searching for solutions but I don't get it how to adapt it to my code:
public void filter(String text) {
items.clear();
if(text.isEmpty()){
items.addAll(itemsCopy);
} else{
text = text.toLowerCase();
for(PhoneBookItem item: itemsCopy){
if(item.name.toLowerCase().contains(text) || item.phone.toLowerCase().contains(text)){
items.add(item);
}
}
}
notifyDataSetChanged();
}
You can use android's Filterable interface..
Follow this link for example
Firstly implements Filterable to your adapter class.. You can use another array list of same type you are using for storing and showing filtered items.
Implements Filterable interface's method getFilter()
Example Code...
#Override
public Filter getFilter() {
return new Filter() {
#Override
protected FilterResults performFiltering(CharSequence charSequence) {
String charString = charSequence.toString();
if (charString.isEmpty()) {
contactListFiltered = contactList;
} else {
List<Contact> filteredList = new ArrayList<>();
for (Contact row : contactList) {
// name match condition. this might differ depending on your requirement
// here we are looking for name or phone number match
if (row.getName().toLowerCase().contains(charString.toLowerCase()) || row.getPhone().contains(charSequence)) {
filteredList.add(row);
}
}
contactListFiltered = filteredList;
}
FilterResults filterResults = new FilterResults();
filterResults.values = contactListFiltered;
return filterResults;
}
#Override
protected void publishResults(CharSequence charSequence, FilterResults filterResults) {
contactListFiltered = (ArrayList<Contact>) filterResults.values;
// refresh the list with filtered data
notifyDataSetChanged();
}
};
}
Add search view into your toolbar....
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
searchView = (SearchView) menu.findItem(R.id.action_search)
.getActionView();
searchView.setSearchableInfo(searchManager
.getSearchableInfo(getComponentName()));
searchView.setMaxWidth(Integer.MAX_VALUE);
// listening to search query text change
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
// filter recycler view when query submitted
mAdapter.getFilter().filter(query);
return false;
}
#Override
public boolean onQueryTextChange(String query) {
// filter recycler view when text is changed
mAdapter.getFilter().filter(query);
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_search) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBackPressed() {
// close search view on back button pressed
if (!searchView.isIconified()) {
searchView.setIconified(true);
return;
}
super.onBackPressed();
}

Can't start intent service in xamarin.android

Can't start intent service
I am writing code for synch data for every 10 minute whenapp is in forground,background or sleep . I had write weakfulintentservice for it calling it from Alaramreceiver but AppService doesn't get call.
AppService
public class AppService : WakefulIntentService
{
public AppService() : base("AppService")
{
}
protected override void DoWakefulWork(Intent intent)
{
Toast.MakeText(this, "In service", ToastLength.Short).Show();
Log.Info("AppService", "I'm awake! I'm awake!");
}
}
WeakFulIntentService
abstract public class WakefulIntentService : IntentService
{
abstract protected void DoWakefulWork(Intent intent);
public static string NAME = "com.jondouglas.wakeful.WakefulIntentService";
public static string LAST_ALARM = "lastAlarm";
private static volatile PowerManager.WakeLock lockStatic = null;
[MethodImpl(MethodImplOptions.Synchronized)]
private static PowerManager.WakeLock GetLock(Context context)
{
if (lockStatic == null)
{
PowerManager manager = (PowerManager) context.GetSystemService(Context.PowerService);
lockStatic = manager.NewWakeLock(WakeLockFlags.Partial, NAME);
lockStatic.SetReferenceCounted(true);
}
return (lockStatic);
}
public static void SendWakefulWork(Context context, Intent intent)
{
GetLock(context.ApplicationContext); //Possibly use of acquire here
context.StartService(intent);
}
public static void SendWakefulWork(Context context, Type classService)
{
SendWakefulWork(context, new Intent(context, classService));
}
public static void ScheduleAlarms(IAlarmListener alarmListener, Context context)
{
ScheduleAlarms(alarmListener, context, true);
}
public static void ScheduleAlarms(IAlarmListener alarmListener, Context context, bool force)
{
ISharedPreferences preferences = context.GetSharedPreferences(NAME, 0);
long lastAlarm = preferences.GetLong(LAST_ALARM, 0);
if (lastAlarm == 0 || force ||
(DateTime.Now.Millisecond > lastAlarm &&
DateTime.Now.Millisecond - lastAlarm > alarmListener.GetMaxAge()))
{
AlarmManager manager = (AlarmManager) context.GetSystemService(Context.AlarmService);
Intent intent = new Intent(context, typeof(AlarmReceiver));
PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, intent, 0);
alarmListener.ScheduleAlarms(manager, pendingIntent, context);
}
}
public static void CancelAlarms(Context context)
{
AlarmManager manager = (AlarmManager) context.GetSystemService(Context.AlarmService);
Intent intent = new Intent(context, typeof (AlarmReceiver));
PendingIntent pendingIntent = PendingIntent.GetBroadcast(context, 0, intent, 0);
manager.Cancel(pendingIntent);
context.GetSharedPreferences(NAME, 0).Edit().Remove(LAST_ALARM).Commit();
}
public WakefulIntentService(string name) : base(name)
{
SetIntentRedelivery(true);
}
public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
{
PowerManager.WakeLock wakeLock = GetLock(this.ApplicationContext);
if (!lockStatic.IsHeld || (flags & StartCommandFlags.Redelivery) != 0)
{
wakeLock.Acquire();
}
return base.OnStartCommand(intent, flags, startId);
return (StartCommandResult.RedeliverIntent);
}
protected override void OnHandleIntent(Intent intent)
{
try
{
DoWakefulWork(intent);
}
finally
{
PowerManager.WakeLock wakeLock = GetLock(this.ApplicationContext);
if (wakeLock.IsHeld)
{
try
{
wakeLock.Release();
}
catch (Exception ex)
{
Log.Error(Class.SimpleName, "Exception when releasing wakelock", ex);
//Log exception when releasing wakelock
}
}
}
}
public interface IAlarmListener
{
void ScheduleAlarms(AlarmManager manager, PendingIntent pendingIntent, Context context);
void SendWakefulWork(Context context);
long GetMaxAge();
}
CallToAppService
public void SendWakefulWork(Context context)
{
WakefulIntentService.SendWakefulWork(context, typeof(AppService));
}
The call for AppService context.StartService(intent); from weakfulintentservice execute perfectly
but AppService cant start In xamarin.android.
Kindly help me to solve this issue.
The call for AppService context.StartService(intent); from weakfulintentservice execute perfectly but AppService cant start In xamarin.android.
You can refer to Started Services, in your Xamarin.Android code where you want to start your AppService, you can code as simply as this:
StartService (new Intent (this, typeof(AppService)));
If you want to start a service with an intent filter, you can refer to this part.
Also you may refer to the case I answered several days ago: Xamarin Android : Change UI TextView text from Service or Receiver.

onRequestPermissionsResult() does not finish before onViewCreated() conduct

public class PdfRendererBasicFragment extends Fragment implements View.OnClickListener {
/**
* Key string for saving the state of current page index.
*/
private static final String STATE_CURRENT_PAGE_INDEX = "current_page_index";
public static final int EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE = 2;
/**
* File descriptor of the PDF.
*/
/**
* {#link android.graphics.pdf.PdfRenderer} to render the PDF.
*/
private PdfRenderer mPdfRenderer;
/**
* Page that is currently shown on the screen.
*/
private PdfRenderer.Page mCurrentPage;
/**
* {#link android.widget.ImageView} that shows a PDF page as a {#link android.graphics.Bitmap}
*/
private ImageView mImageView;
/**
* {#link android.widget.Button} to move to the previous page.
*/
private Button mButtonPrevious;
/**
* {#link android.widget.Button} to move to the next page.
*/
private Button mButtonNext;
private Bundle copySavedInstanceState;
public PdfRendererBasicFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_pdf_renderer_basic, container, false);
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Retain view references.
mImageView = (ImageView) view.findViewById(R.id.image);
mButtonPrevious = (Button) view.findViewById(R.id.previous);
mButtonNext = (Button) view.findViewById(R.id.next);
// Bind events.
mButtonPrevious.setOnClickListener(this);
mButtonNext.setOnClickListener(this);
mImageView.setOnClickListener(this);
copySavedInstanceState = savedInstanceState;
while (true) {
int rc = ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (rc == PackageManager.PERMISSION_GRANTED)
break;
}
// Show the first page by default.
int index = 0;
// If there is a savedInstanceState (screen orientations, etc.), we restore the page index.
if (null != copySavedInstanceState) {
index = copySavedInstanceState.getInt(STATE_CURRENT_PAGE_INDEX, 0);
}
Log.d("check","index : " + index);
showPage(index);
}
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
int rc = ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (rc == PackageManager.PERMISSION_GRANTED) {
try {
openRenderer(activity);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(activity, "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
activity.finish();
}
} else {
requestExternalStoragePermission();
}
}
#Override
public void onDetach() {
try {
closeRenderer();
} catch (IOException e) {
e.printStackTrace();
}
super.onDetach();
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
if (null != mCurrentPage) {
outState.putInt(STATE_CURRENT_PAGE_INDEX, mCurrentPage.getIndex());
}
}
private void requestExternalStoragePermission() {
final String[] permissions = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (!ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
ActivityCompat.requestPermissions(getActivity(), permissions, EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
return;
}
final Activity thisActivity = getActivity();
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View view) {
ActivityCompat.requestPermissions(thisActivity, permissions,
EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE);
}
};
}
#Override
public void onRequestPermissionsResult(int requestCode,
#NonNull String[] permissions,
#NonNull int[] grantResults) {
if (requestCode != EXTERNAL_STORAGE_PERMISSION_REQUEST_CODE) {
Log.d("TAG", "Got unexpected permission result: " + requestCode);
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
return;
}
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("TAG", "Camera permission granted - initialize the camera source");
// we have permission, so can read SD Card now.
try {
openRenderer(getActivity());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
getActivity().finish();
}
return;
}
Log.e("TAG", "Permission not granted: results len = " + grantResults.length +
" Result code = " + (grantResults.length > 0 ? grantResults[0] : "(empty)"));
DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
};
}
/**
* Sets up a {#link android.graphics.pdf.PdfRenderer} and related resources.
*/
private void openRenderer(Context context) throws IOException {
File file = new File("/sdcard/Download/test.pdf");
mPdfRenderer = new PdfRenderer(ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY));
}
/**
* Closes the {#link android.graphics.pdf.PdfRenderer} and related resources.
*
* #throws java.io.IOException When the PDF file cannot be closed.
*/
private void closeRenderer() throws IOException {
if (null != mCurrentPage) {
mCurrentPage.close();
}
mPdfRenderer.close();
}
/**
* Shows the specified page of PDF to the screen.
*
* #param index The page index.
*/
private void showPage(int index) {
if (mPdfRenderer.getPageCount() <= index) {
return;
}
// Make sure to close the current page before opening another one.
if (null != mCurrentPage) {
mCurrentPage.close();
}
// Use `openPage` to open a specific page in PDF.
mCurrentPage = mPdfRenderer.openPage(index);
// Important: the destination bitmap must be ARGB (not RGB).
Bitmap bitmap = Bitmap.createBitmap(mCurrentPage.getWidth(), mCurrentPage.getHeight(),
Bitmap.Config.ARGB_8888);
// Here, we render the page onto the Bitmap.
// To render a portion of the page, use the second and third parameter. Pass nulls to get
// the default result.
// Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
mCurrentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
// We are ready to show the Bitmap to user.
mImageView.setImageBitmap(bitmap);
updateUi();
}
/**
* Updates the state of 2 control buttons in response to the current page index.
*/
private void updateUi() {
int index = mCurrentPage.getIndex();
int pageCount = mPdfRenderer.getPageCount();
mButtonPrevious.setEnabled(0 != index);
mButtonNext.setEnabled(index + 1 < pageCount);
getActivity().setTitle(getString(R.string.app_name_with_index, index + 1, pageCount));
}
/**
* Gets the number of pages in the PDF. This method is marked as public for testing.
*
* #return The number of pages.
*/
public int getPageCount() {
return mPdfRenderer.getPageCount();
}
#Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.previous: {
// Move to the previous page
showPage(mCurrentPage.getIndex() - 1);
break;
}
case R.id.next: {
// Move to the next page
Log.d("name", mCurrentPage.getIndex() + "");
showPage(mCurrentPage.getIndex() + 1);
break;
}
case R.id.image: {
Log.d("name", mCurrentPage.getIndex() + "");
break;
}
}
}
}
HI, this is my code.
I try to fix. but it's not going well.
problem is this.
When I conduct this app. Android request permission, and I Approve.
but at that time android perform 'onViewCreated(View view, Bundle savedInstanceState)' method before 'openRenderer(activity)' is done.
so 'showPage(index)' raise some error. and after then (I mean permission already approved, and execute again) app doing well.
but I want to fix that.
I think
At the first time, onAttach(Activity activity) execute
and after permission approved,
onAttach(Activity activity) and
onViewCreated(View view, Bundle savedInstanceState)
methods seems to run at the same time.
Please advice me.
Thank you.
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// Retain view references.
Log.d("timeStamp", "onViewCreated ");
mImageView = (ImageView) view.findViewById(R.id.image);
mButtonPrevious = (Button) view.findViewById(R.id.previous);
mButtonNext = (Button) view.findViewById(R.id.next);
// Bind events.
mButtonPrevious.setOnClickListener(this);
mButtonNext.setOnClickListener(this);
mImageView.setOnClickListener(this);
Log.d("timeStamp", "onViewCreated 할당완료");
while (true) {
int rc = getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (rc == PackageManager.PERMISSION_GRANTED){
try {
openRenderer(getActivity());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
getActivity().finish();
}
break;
}
Log.d("timeStamp", "얼마나 기다리는겨");
}
// Show the first page by default.
int index = 0;
// If there is a savedInstanceState (screen orientations, etc.), we restore the page index.
if (null != savedInstanceState) {
index = savedInstanceState.getInt(STATE_CURRENT_PAGE_INDEX, 0);
}
Log.d("timeStamp", "showPage 호출 직전");
showPage(index);
}
}
I avoid this problem to add this code.
while (true) {
int rc = getActivity().checkSelfPermission(Manifest.permission.WRITE_EXTERNAL_STORAGE);
if (rc == PackageManager.PERMISSION_GRANTED){
try {
openRenderer(getActivity());
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(getActivity(), "Error! " + e.getMessage(), Toast.LENGTH_SHORT).show();
getActivity().finish();
}
break;
}
Log.d("timeStamp", "얼마나 기다리는겨");
}
but. this is not a best.
I figured this happen because onAttach method call requestPermissions method and end. onViewCreated start before User answer to request and onRequestPermissionsResult called (So openRenderer start).
So I suspend showPage method until PERMISSION_GRANTED.

Why could not access Session using asp.net web api?

In my ASP.NET Web API project, i could access Session object in local (both debug and release model).
But when i deploy it to the server, it doesn't work.
Global.asax
public override void Init()
{
this.PostAuthenticateRequest +=MvcApplication_PostAuthenticateRequest;
base.Init();
}
void MvcApplication_PostAuthenticateRequest(object sender, EventArgs e)
{
System.Web.HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
UserApiController.cs
[HttpGet]
public string GetVerificationCode(string mobileNumber)
{
if (!string.IsNullOrWhiteSpace(mobileNumber) &&
Regex.Match(mobileNumber, #"^1\d{10}$", RegexOptions.IgnoreCase).Success)
{
string VerificationCode = "1234";
if (HttpContext.Current.Session != null)
{
HttpContext.Current.Session["VerificationCode"] = VerificationCode;
}
return VerificationCode;
}
throw new ArgumentException("Phone number format is incorrect");
}
[HttpGet]
public string GetSessionString()
{
if (HttpContext.Current.Session != null)
{
return HttpContext.Current.Session["VerificationCode"].ToString();
}
return string.Empty;
}
Why it doesn't work?

Resources