How do i lock phone programmatically android - java

Ho do i lock my android phone programmatically ?
I tried following this example. But when i click on the enable button the Activity pops up for few milliseconds and then closes automatically
The log shows no error just this log
Log.i("DeviceAdminSample", "Admin enable FAILED!");
Can any one tell me how to lock the android screen (Like the lock when make to many attempts in pattern lock and the phone locks down)
Any help is appreciated

You have to make your app as admin, Read something over here
Create a new empty project and create a class called MyAdminReceiver that extends DeviceAdminReceiver like this
import android.app.admin.DeviceAdminReceiver;
public class MyAdminReceiver extends DeviceAdminReceiver{
}
Create a new folder called xml and create an .xml file for your admin rights called admin.xml and add the policies, in you case its locking the screen
<device-admin xmlns:android="http://schemas.android.com/apk/res/android" >
<uses-policies>
<force-lock />
</uses-policies>
</device-admin>
In your manifest add the receiver under Application tag
<receiver
android:name="MyAdminReceiver"
android:permission="android.permission.BIND_DEVICE_ADMIN">
<meta-data
android:name="android.app.device_admin"
android:resource="#xml/admin"/>
<intent-filter>
<action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>
</intent-filter>
</receiver>
And in your MainActivity.java add code like this
import android.app.Activity;
import android.app.admin.DevicePolicyManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements OnClickListener {
private static final int ADMIN_INTENT = 15;
private static final String description = "Some Description About Your Admin";
private DevicePolicyManager mDevicePolicyManager;
private ComponentName mComponentName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mDevicePolicyManager = (DevicePolicyManager)getSystemService(
Context.DEVICE_POLICY_SERVICE);
mComponentName = new ComponentName(this, MyAdminReceiver.class);
Button btnEnableAdmin = (Button) findViewById(R.id.btnEnableAdmin);
Button btnDisableAdmin = (Button) findViewById(R.id.btnDisableAdmin);
Button btnLock = (Button) findViewById(R.id.btnLock);
btnEnableAdmin.setOnClickListener(this);
btnDisableAdmin.setOnClickListener(this);
btnLock.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btnEnableAdmin:
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, mComponentName);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION,description);
startActivityForResult(intent, ADMIN_INTENT);
break;
case R.id.btnDisableAdmin:
mDevicePolicyManager.removeActiveAdmin(mComponentName);
Toast.makeText(getApplicationContext(), "Admin registration removed", Toast.LENGTH_SHORT).show();
break;
case R.id.btnLock:
boolean isAdmin = mDevicePolicyManager.isAdminActive(mComponentName);
if (isAdmin) {
mDevicePolicyManager.lockNow();
}else{
Toast.makeText(getApplicationContext(), "Not Registered as admin", Toast.LENGTH_SHORT).show();
}
break;
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == ADMIN_INTENT) {
if (resultCode == RESULT_OK) {
Toast.makeText(getApplicationContext(), "Registered As Admin", Toast.LENGTH_SHORT).show();
}else{
Toast.makeText(getApplicationContext(), "Failed to register as Admin", Toast.LENGTH_SHORT).show();
}
}
}
}
Note: If you try to call the Intent for Admin Device other that from an Activity subclass there are chances you might get an error to use Intent.FLAG_ACTIVITY_NEW_TASK but when you use that your window might not pop like in your case so Try opening it from a subclass of an activity only
Also you cannot un-install your app unless it has not be unregistered as an admin

But when i click on the enable button the Activity pops up for few milliseconds and then closes automatically
The code shown in that sample will bring up the Settings application when clicked.
Can any one tell me how to lock the android screen
You use the code that you linked to. Here is my sample app showing the same basic thing.
Specifically:
You need to have a BroadcastReceiver in your manifest that is set up to be a device admin component
The user has to activate your app as a device admin
You then call lockNow() on DevicePolicyManager
Here is the developer documentation on the device admin APIs.

Related

Android NFC reader gives "avc: denied"

I tried making a app with the instructions from here:
https://developer.android.com/guide/topics/connectivity/nfc/nfc
But when I compile the code and hold a card against my phone, I get a weird sound
My nfc is turned on, and I have a oneplus 6 running android 9
When I check logcat I see that I'm getting an error:
56:27.888 7834-7850/com.appname D/DecorView: onWindowFocusChangedFromViewRoot hasFocus: true, DecorView#6302a6f[MainActivity]
2019-10-12 22:56:27.913 7834-7834/com.appname W/RenderThread: type=1400 audit(0.0:2504791): avc: denied { read } for name="u:object_r:vendor_default_prop:s0" dev="tmpfs" ino=21655 scontext=u:r:untrusted_app:s0:c16,c257,c512,c768 tcontext=u:object_r:vendor_default_prop:s0 tclass=file permissive=0
2019-10-12 22:56:27.928 7834-7880/com.appname E/libc: Access denied finding property "vendor.debug.egl.swapinterval"
Why am I getting this error instead of the textview displaying the info of the nfc card im scanning (I tried mulitple nfc cards but its gives the same error)
I found someone with somewhat of the same problem. they say you should follow the link and then watch comment #3. and then they say it has something to do with not being allowed to write to a tmp directory due to a security issue.
Please help me resolve this issue, here is my MainActivity.java:
package com.packagename;
import androidx.appcompat.app.AppCompatActivity;
import android.content.Intent;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcAdapter.CreateNdefMessageCallback;
import android.nfc.NfcEvent;
import android.os.Bundle;
import android.os.Parcelable;
import android.renderscript.RenderScript;
import android.widget.TextView;
import android.widget.Toast;
import static android.nfc.NdefRecord.createMime;
public class MainActivity extends AppCompatActivity implements CreateNdefMessageCallback {
NfcAdapter nfcAdapter;
TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Check for available NFC Adapter
nfcAdapter = NfcAdapter.getDefaultAdapter(this);
if (nfcAdapter == null) {
Toast.makeText(this, "NFC is not available", Toast.LENGTH_LONG).show();
finish();
return;
}
// Register callback
nfcAdapter.setNdefPushMessageCallback(this, this);
}
#Override
public NdefMessage createNdefMessage(NfcEvent event) {
String text = ("Beam me up, Android!\n\n" +
"Beam Time: " + System.currentTimeMillis());
NdefMessage msg = new NdefMessage(
new NdefRecord[] { createMime(
"application/vnd.com.example.android.beam", text.getBytes())
/**
* The Android Application Record (AAR) is commented out. When a device
* receives a push with an AAR in it, the application specified in the AAR
* is guaranteed to run. The AAR overrides the tag dispatch system.
* You can add it back in to guarantee that this
* activity starts when receiving a beamed message. For now, this code
* uses the tag dispatch system.
*/
//,NdefRecord.createApplicationRecord("com.example.android.beam")
});
return msg;
}
#Override
public void onResume() {
super.onResume();
// Check to see that the Activity started due to an Android Beam
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent().getAction())) {
processIntent(getIntent());
}
}
#Override
public void onNewIntent(Intent intent) {
// onResume gets called after this to handle the intent
setIntent(intent);
}
/**
* Parses the NDEF Message from the intent and prints to the TextView
*/
void processIntent(Intent intent) {
textView = findViewById(R.id.textView);
Parcelable[] rawMsgs = intent.getParcelableArrayExtra(
NfcAdapter.EXTRA_NDEF_MESSAGES);
// only one message sent during the beam
NdefMessage msg = (NdefMessage) rawMsgs[0];
// record 0 contains the MIME type, record 1 is the AAR, if present
textView.setText(new String(msg.getRecords()[0].getPayload()));
}
}
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.packagename">
<uses-permission android:name="android.permission.NFC" />
<uses-feature android:name="android.hardware.nfc" />
<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>
</manifest>
and here a picture of my activity_main.xml:
Thanks!
As NFC reading is handled by the Android OS, this will always make a sound when the card is read.
Depending on what NDEF records on the card and what you application is trying to do determines what the OS does with the NFC data.
You can download a generic NFC Application like https://play.google.com/store/apps/details?id=com.wakdev.wdnfc&hl=en_US to check what is on the card and write some sample data for you application to read.
It looks like you are trying to run this app on 2 phones and get them to talk using the deprecated Android Beam functionality https://developer.android.com/reference/android/nfc/NfcAdapter.CreateNdefMessageCallback (Which I found was never reliable - which is why they are removing it)
But you say
Why am I getting this error instead of the textview displaying the
info of the nfc card im scanning
Which suggest you are trying to read an NFC card and the methods used are not for this.
The question is are you wanting to do with NFC?
1) Have a NFC card cause you APP to be launched by the Android OS?
Then use the data on the NFC some how.
If yes then you should just be putting the correct intent filters in your manifest and handle them in your MainActivity as you would do for any other intent, and the parsing the NDEF message from the intent data.
See https://developer.android.com/guide/components/intents-filters#ExampleFilters for some non NFC examples on how your App can register to the OS what Intent types it can handle.
2) In you App handle reading from the NFC card at certain times
This seems more what you are trying to do (and what my Apps do)
To do this you use enable the NFC Foreground dispatcher https://developer.android.com/reference/android/nfc/NfcAdapter.html#enableForegroundDispatch(android.app.Activity,%20android.app.PendingIntent,%20android.content.IntentFilter%5B%5D,%20java.lang.String%5B%5D%5B%5D)
I use the following type of code to do this in my Activity
public class ViewNFCCardsActivity extends AppCompatActivity {
private NfcAdapter mNfcAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_view_nfccards);
mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
}
#Override
protected void onResume() {
super.onResume();
IntentFilter tagDetected = new IntentFilter(NfcAdapter.ACTION_TAG_DISCOVERED);
IntentFilter ndefDetected = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
IntentFilter techDetected = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
IntentFilter[] nfcIntentFilter = new IntentFilter[]{techDetected,tagDetected,ndefDetected};
try {
ndefDetected.addDataType("*/*");
} catch (IntentFilter.MalformedMimeTypeException e) {}
PendingIntent pendingIntent = PendingIntent.getActivity(
this, 0, new Intent(this, getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
if(mNfcAdapter!= null)
mNfcAdapter.enableForegroundDispatch(this, pendingIntent, nfcIntentFilter, null);
}
#Override
protected void onPause() {
super.onPause();
if(mNfcAdapter!= null)
mNfcAdapter.disableForegroundDispatch(this);
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
TextView textView = (TextView) findViewById(R.id.MessageText);
// High level way to get Ndef records from what is already been read from the tag
if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction())) {
Parcelable[] rawMessages = intent.getParcelableArrayExtra(NfcAdapter.EXTRA_NDEF_MESSAGES);
if (rawMessages != null) {
// Only need the first message
NdefMessage msg = (NdefMessage) rawMessages[0];
// Only need the first record in message
String message = new String(msg.getRecords()[0].getPayload());
textView.setText(message);
}
}
}
The onResume stuff tells Android OS to send all NFC card type messages to my Application and the onNewIntent method gets the Intent passed to it by the OS and processes the Message if it is an NDEF message.
You can also when creating the Foreground Dispatcher in onResume add additional filters like
try {
ndefDetected.addDataType("custom/text");
} catch (IntentFilter.MalformedMimeTypeException e) {}
or remove filters for non NDEF cards (Usually add all types because I don't want other card types like contactless bank cards triggering other apps while my app is in the foreground)

ANDROID: How to receive broadcast of specific application's notifications?

I am creating an application which perform specific task on receiving broadcast notification from specific application like whats app, viber etc .I have searched about this but did not get any solution. is there any possibility exist to do this action? if exist then please guide me how? :)
Simple Only follow this code and read the documentation from this link
Manifest File
<receiver android:name=".callbroadcastreceiver"
android:exported="true"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE"/>
</intent-filter>
</receiver>
In Java callbroadcastreceiver file
public class callbroadcastreceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra( TelephonyManager.EXTRA_STATE);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
//Phone is ringing
}
else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
//Call received
Toast.makeText( context,"call received",Toast.LENGTH_SHORT ).show();
context.startService( new Intent( context,BoundService.class ) );
}
else if (state.equals( TelephonyManager.EXTRA_STATE_IDLE)) {
//Call Dropped or rejected
context.stopService( new Intent( context,BoundService.class ) );
}
}
}
You can check on the status bar notification but you can't read them. If it can be it really danger situation for vulnerabilty.
But using Accessibility Service, you can only listen to all notification on the notification bar. 
you can create a NotificationListenerService for this. Users may not be interested in giving your app the rights to monitor their notifications, though, which is why the user must manually enable this for your app.
but you can not read the content.
Try this to access your Notification form any Application
import android.accessibilityservice.AccessibilityService;
import android.accessibilityservice.AccessibilityServiceInfo;
import android.app.Notification;
import android.media.AudioManager;
import android.os.Parcelable;
import android.util.Log;
import android.view.accessibility.AccessibilityEvent;
import com.qna.vbage.Pref;
import static com.qna.vbage.FieldVerification.setRingerMode;
public class NotificationService extends AccessibilityService {
protected void onServiceConnected() {
AccessibilityServiceInfo info = new AccessibilityServiceInfo();
info.eventTypes = AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED;
info.feedbackType = AccessibilityServiceInfo.FEEDBACK_ALL_MASK;
info.notificationTimeout = 3000;
setServiceInfo(info);
}
#Override
public void onAccessibilityEvent(AccessibilityEvent e) {
//Toast.makeText(this, "onAccessibilityEvent", Toast.LENGTH_SHORT).show();
Log.d("VBage", "FML");
if (e.getEventType() == AccessibilityEvent.TYPE_NOTIFICATION_STATE_CHANGED) {
// Toast.makeText(this, "onAccessibilityEvent 2", Toast.LENGTH_SHORT).show();
Log.d("VBage", "Recieved event");
Parcelable data = e.getParcelableData();
if (data instanceof Notification) {
// Toast.makeText(this, "onAccessibilityEvent 3", Toast.LENGTH_SHORT).show();
Log.d("VBage", "Recieved notification");
Notification notification = (Notification) data;
Log.d("VBage", "ticker: " + notification.tickerText);
Log.d("VBage", "icon: " + notification.icon);
Log.d("VBage", "notification: " + e.getText());
}
}
}
#Override
public void onInterrupt() {
setRingerMode(NotificationService_API18.this, AudioManager.RINGER_MODE_SILENT);
}
}
Set Permission in your Manifest
<uses-permission
android:name="android.permission.BIND_ACCESSIBILITY_SERVICE"
tools:ignore="ProtectedPermissions" />
set Service in Manifest to Call when App Start
<service android:name=".NotificationService"
android:label="#string/app_name"
android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE" >
<intent-filter>
<action android:name="android.accessibilityservice.AccessibilityService" />
</intent-filter>
<meta-data
android:name="android.accessibilityservice"
android:resource="#xml/accessibilityservice" />
</service>
Create xml in you Values folder res/Values/xml/accessibilityservice.xml
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
android:accessibilityEventTypes="typeNotificationStateChanged"
android:accessibilityFeedbackType="feedbackSpoken"
android:notificationTimeout="100" />
You have to Enable Accessibility Manually for your App put below code in your Activity where you want to start Using this Service
if (!isAccessibilitySettingsOn(getApplicationContext())) {
AlertDialog.Builder dialog = new AlertDialog.Builder(mActivity);
dialog.setNegativeButton("Go!", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
startActivity(new Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS));
}
});
showCusDialog(dialog, "Warning!", R.drawable.ic_warning, getString(R.string.accessiblityString));
}
to Start Service from Activity
startService(new Intent(mActivity, NotificationService_API18.class));

How to start NotificationListenerService?

Today I started writing for android. I want a simple (I think) app that waits for notification with specified title and then does something. I tried this code for service
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.service.notification.NotificationListenerService;
import android.service.notification.StatusBarNotification;
import android.util.Log;
import android.support.v4.content.LocalBroadcastManager;
import android.widget.Toast;
public class NotificationListener extends NotificationListenerService {
Context context;
public int onStartCommand(Intent intent, int flags, int startId) {
// Let it continue running until it is stopped.
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
return START_STICKY;
}
#Override
public void onCreate() {
Toast.makeText(this, "onCreate", Toast.LENGTH_LONG).show();
super.onCreate();
context = getApplicationContext();
}
#Override
public void onNotificationPosted(StatusBarNotification sbn) {
String pack = sbn.getPackageName();
Toast.makeText(this,"NOTIFICATION",Toast.LENGTH_SHORT).show();
String text = "";
String title = "";
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
Bundle extras = extras = sbn.getNotification().extras;
text = extras.getCharSequence("android.text").toString();
title = extras.getString("android.title");
}
Log.i("Package",pack);
Log.i("Title",title);
Log.i("Text",text);
}
#Override
public void onNotificationRemoved(StatusBarNotification sbn) {
Toast.makeText(this,"NOTIFICATION removed",Toast.LENGTH_SHORT).show();
Log.i("Msg","Notification was removed");
}
}
Then added this to manifest:
<service
android:name=".NotificationListener"
android:enabled="true"
android:label="#string/app_name"
android:permission="android.permission.BIND_NOTIFICATION_LISTENER_SERVICE">
<intent-filter>
<action android:name="android.service.notification.NotificationListenerService" />
</intent-filter>
</service>
finally started the service in MainActivity onCreate() startService(new Intent(context, NotificationListener.class));
onNotificationPosted does not work. It seems like service was started correctly, because toasts from onStartCommand and onCreate were shown. I tried on emulator and real device. I also allowed notification access in settings. Please help, I wasted 5 hours on that.

How to make a swipe up on home button open a sliding drawer

I am working on a app that when you swipe up on the home button the app opens. I have everything else done bet the code to accomplish the open on swipe up on home button part. How do I do this?
Any help would be amazing.
Here's my java code if needed:
package com.d4a.toolbelt;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
public class QuickLaunch extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quick_launch);
}
/** Called when the user clicks the music button */
public void music(View view) {
Intent intent = new Intent("android.intent.action.MUSIC_PLAYER");
startActivity(intent);
}
/** Called when the user clicks the play button */
public void play(View view) {
Intent launchIntent = getPackageManager().getLaunchIntentForPackage("com.android.vending");
startActivity(launchIntent);
}
/** Called when the user clicks the web button */
public void web(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://google.com/"));
startActivity(browserIntent);
}
/** Called when the user clicks the email button */
public void email(View view) {
Intent intent = getPackageManager().getLaunchIntentForPackage("com.android.email");
startActivity(intent);
}
/** Called when the user clicks the sms button */
public void chat(View view) {
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.setComponent(new ComponentName("com.d4a.sms","de.ub0r.android.smsdroid.ConversationListActivity"));
intent.putExtra("grace", "Hi");
startActivity(intent);
}
/** Called when the user clicks the settings button */
public void settings(View view) {
Intent intent = getPackageManager().getLaunchIntentForPackage("com.android.settings");
startActivity(intent);
}
/** Called when the user clicks the camara button */
public void cam(View view) {
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
startActivityForResult(intent, 0);
}
/** Called when the user clicks the video camara button */
public void video_cam(View view) {
Intent intent = new Intent("android.media.action.VIDEO_CAPTURE");
startActivityForResult(intent, 0);
}
}
Thanks a million in advance guys!
I figured it out you need this line of code in the manifest:
<intent-filter>
<action android:name="android.intent.action.ASSIST" />
<category android:name="android.intent.category.DEFAULT"/>
</intent-filter>
Thanks to home launcher being open source I got my answer I hope this helps out anyone else who is in my shoes

Android Java: Modification of instance variable inside button click handler

There is a strange behaviour of assigning/modifying instance variable of the class inside Button OnClick() handlers.
As shown below, the instance variable "CurrentFile" is modified inside imgBtn.setOnClickListener() handlers. But when this variable is accessed in onActivityResult() method, this variable contains the value "null".
According to my understanding, the activity "GetPicActivity" will not be destroyed till the Camera activity returns. So, the instance variable "CurrentFile" should not be null.
Please help, if I am missing some basics.
import java.io.File;
import java.io.IOException;
import com.favoritepics.R;
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.Toast;
public class GetPicActivity extends Activity {
protected static final int ID_REQ_IMAGE_CAPTURE = 1;
protected static final int ID_REQ_PICK_PHOTO = 0;
protected File currentFile = null; /// Goal is "to modify this variable inside Button onClick handlers"
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setBackgroundDrawable(
new ColorDrawable(android.graphics.Color.DKGRAY));
setContentView(R.layout.activity_get_pic);
// set handler image gallery
ImageButton imgBtn = (ImageButton) findViewById(R.id.imgGallery);
imgBtn.setOnClickListener(new ImageButton.OnClickListener() {
#Override
public void onClick(View v) {
// create intent to take picture on camera
Intent pickPhoto = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(pickPhoto, ID_REQ_PICK_PHOTO);
}
});
// set handler for camera image
imgBtn = (ImageButton) findViewById(R.id.imgCamera);
imgBtn.setOnClickListener(new ImageButton.OnClickListener() {
#Override
public void onClick(View v) {
Intent takePicture = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File tempDir = Environment.getExternalStorageDirectory();
File tempFile = null;
try {
currentFile = File
.createTempFile("_jpeg_", ".jpg", tempDir);
} catch (IOException exception) {
Toast.makeText(
GetPicActivity.this,
"Problem occured during creation of temp file! "
+ exception.getMessage(),
Toast.LENGTH_SHORT).show();
}
if (currentFile != null) {
takePicture.putExtra(MediaStore.EXTRA_OUTPUT,
Uri.fromFile(currentFile));
startActivityForResult(takePicture, ID_REQ_IMAGE_CAPTURE);
}
}
});
// set handler for cancel button
Button btnCancel = (Button) findViewById(R.id.btnCancel);
btnCancel.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
finish();
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
switch (requestCode) {
case ID_REQ_IMAGE_CAPTURE:
if (resultCode == RESULT_OK) {
Intent newIntent = new Intent();
newIntent.putExtra("TYPE", requestCode);
newIntent.putExtra("PATH", currentFile.getAbsolutePath());
setResult(RESULT_OK, newIntent);
finish();
}
break;
default:
break;
}
}
}
click here to see Logcat messages
Steps what I intend to do:
1, Create a temporary file in External storage for the destination of Camera picture
2, Start Camera to take a picture by passing the URI of temporary file
3, OnActivityResult() from camera, return the (temporary) File path to previous activity for further process
But here what I see is,
As soon as the Camera is started & picture is taken, the GetPicActivity is created again. Because of this, the instance variable "CurrentFile" will be null & in OnActivityResult() , I could not get the File path of temporary file.
Why is the GetPicActivity destroyed after starting Camera?
When the camera is started, the Camera appears in the screen orientation "Landscape".
Even the orientation of already existing activity stack is changed to "Landscape" itseems.
So, When the result of Camera is returned to GetPicActivity method OnActivityResult(), the GetPicActivity is created again. But now, the instance variable "CurrentFile" is null. This, gives a NullPointerException.

Categories

Resources