jeudi 28 mai 2015

App crashes when loading image from gallery

In my app ,i have two buttons ,one for loading the image from gallery(from device )and another one for taking pictures by accesing the camera of the device,My code is working properly on some devices ,bt in some devices ,the app crashes when clicking an image in the gallery.Can anybody help me to find out the actual propblem??

public class MainActivity extends ActionBarActivity {
private static int RESULT_LOAD_IMAGE = 1;
private static final int CAMERA_REQUEST = 1888;
private ImageView imageView;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Button buttonLoadImage = (Button) findViewById(R.id.buttonLoadPicture);
    buttonLoadImage.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {

            Intent i = new Intent(
                    Intent.ACTION_PICK,
                    android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

            startActivityForResult(i, RESULT_LOAD_IMAGE);
        }
    });
    this.imageView = (ImageView)this.findViewById(R.id.imgView);
    Button photoButton = (Button) this.findViewById(R.id.button2);
    photoButton.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
            startActivityForResult(cameraIntent, CAMERA_REQUEST);
        }
    });
}

And the xml is

<LinearLayout xmlns:android="http://ift.tt/nIICcg" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent">
<ImageView android:id="@+id/imgView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_weight="1"></ImageView>
<RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:background="@android:color/black" >
<Button android:id="@+id/buttonLoadPicture"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"

    android:layout_weight="0"
    android:text="Load Picture"
    android:layout_gravity="center"></Button>
    <Button
        android:id="@+id/button2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Take Picture"
        android:layout_alignParentRight="true"/>

</RelativeLayout>

Android won't stop GPS intent

I want to ask for the GPS location, even when the app is in the background. Therefore I used a PendingIntent as follows:

final Intent intent = new Intent(this, LocationReceiver.class);
mLocationIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, mLocationIntent);

It works great. However, the GPS location is still updating, even when the MainActivity is destroyed. The Intent Service won't stop. I tried to stop the Intent in the onDestroyed method of the MainActivity like this:

@Override
protected void onDestroy() {
    LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, mLocationIntent);
}

...but this method won't get called.

How can I stop the Intent when the MainActivity is destroyed?

Why do we need Intents for transition to new Activity/Service?

I was asked the following question in an interview :

Why do we need Intents to start new Activity or Service? Alternatively, why don't we start Activity by creating a new object and calling activity_obj.onCreate(..); on it.

I could count the benefits of intents like transferring data and intent-filters targeting appropriate activities, but except that I couldn't come up with a satisfying answer.

Is it related to life cycle callback handling of Activities ? I can't find a good answer anywhere. Please suggest!!

Share Texts to Whats up using Intent, Whats up is not finish after share Text sucessfully,and not return back to my app

this is my code.

Intent sendIntent = new Intent();
sendIntent.setAction(Intent.ACTION_SEND);
sendIntent.putExtra(Intent.EXTRA_TEXT, "This is my text to send.");
sendIntent.setType("text/plain");
startActivity(Intent.createChooser(sendIntent,getResources().getText(R.string.send_to)));

when choose share app whats up, after share text ,i can not return to my app.

FullScreenIntent only appears if I clear the notification

I'm trying to launch a FullScreenIntent from a service working in the background, but I realised that the intent would not be shown another time if I do not clear the notification from the task bar. I have tried removing the notification by removing

.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("Notification")
.setContentText("A client is calling")

but that just removes my option of clearing the notification. Can somebody help?

My code is as shown:

                    NotificationCompat.Builder mBuilder =
                            new NotificationCompat.Builder(this)
                                    .setSmallIcon(R.drawable.ic_launcher)
                                    .setContentTitle("Notification")
                                    .setContentText("A client is calling")
                                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                                    .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000 })
                                    .setAutoCancel(true);
                    Intent resultIntent = new Intent(this, MainActivity.class);
                    String strName = ((String) message).substring(9);
                    resultIntent.putExtra("Msg",strName);
    // Because clicking the notification opens a new ("special") activity, there's
    // no need to create an artificial back stack.
                    PendingIntent resultPendingIntent =
                            PendingIntent.getActivity(
                                    this,
                                    0,
                                    resultIntent,
                                    PendingIntent.FLAG_CANCEL_CURRENT
                            );

                    mBuilder.setFullScreenIntent(resultPendingIntent,true);
                    int mNotificationId = 001;
    // Gets an instance of the NotificationManager service
                    NotificationManager mNotifyMgr =
                            (NotificationManager)this.getSystemService(this.NOTIFICATION_SERVICE);
    // Builds the notification and issues it.
                    Notification m = mBuilder.build();
                    m.flags = Notification.FLAG_AUTO_CANCEL;
                    mNotifyMgr.notify(mNotificationId, m);

Not able to launch device administrator activity from my service class (Android Lollipop)

I'm trying to prompt the user with the device administrator activity to enable my application as a device administrator. And here is the code which attempts to call the device administrator activity from my service class:

ComponentName deviceAdmin=new ComponentName(context,DeviceAdminReceiver.class);
Intent intent = new Intent(DevicePolicyManager.ACTION_ADD_DEVICE_ADMIN);
intent.putExtra(DevicePolicyManager.EXTRA_DEVICE_ADMIN, deviceAdmin);
intent.putExtra(DevicePolicyManager.EXTRA_ADD_EXPLANATION, "Make sure to accept in order to provide support for lock and wipe");
PendingIntent pendingIntent = PendingIntent.getActivity(context, DevicePolicyManagerLockWipeService.RESULT_ENABLE, intent, Intent.FLAG_ACTIVITY_NEW_TASK);
pendingIntent.send();

Android Manifest is as follows;

<receiver android:name=".DeviceAdminReceiver" android:label="DeviceAdminReceiver"
android:permission="android.permission.BIND_DEVICE_ADMIN" android:exported="true">
<meta-data android:name="android.app.device_admin" android:resource="@xml/device_admin"/>
<intent-filter>
   <action android:name="android.app.action.DEVICE_ADMIN_ENABLED"/>
</intent-filter>
</receiver>

This works perfectly on any 4.x android versions, but doesn't work on Lollipop version. In lollipop when I kick start my application it looks like it is opening the device admin activity, but immediately the activity animation stops and it closes without prompting the user to enable device admin. However, my application shows up in the settings->security->device administratior window, but it is unchecked as a device admin.

mercredi 27 mai 2015

How do I get a video from URI and compress it and convert it into base64 and send it to the server on Android?

I want to capturing video and sending it to the server in base64. Before sending it, I want to check the video length and video size. I am able to capture the video

        switch (v.getId()) {
            case R.id.camera_button:
                intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
                if (intent.resolveActivity(getPackageManager()) != null) {
                    startActivityForResult(intent, INTENT_VIDEO);
                }
                break;
            }
        }

and get the URI

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == INTENT_VIDEO && resultCode == RESULT_OK) {
            Uri uri = data.getData();
            videoView.setVideoURI(uri);
            videoView.start();
        }
    }

I am able to get a video path

    private String getPath(Uri video) {
        String path = video.getPath();
        String[] projection = {MediaStore.Video.Media.DATA};
        Cursor cursor = getContentResolver().query(media, projection, null, null, null);
        if (cursor.moveToFirst()) path = cursor.getString(cursor.getColumnIndexOrThrow(projection[0]));
        cursor.close();

        return path;
    }

How do I get a video object from that path so that I could compress, check video duration, file size? For image, it will be as simple as this BitmapFactory.decodeFile(photoPath);

and after that, I would like to convert it to base64. For image, it's as simple as this

    private String toBase64(Bitmap bitmap) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 60, outputStream);
        byte[] bytes = outputStream.toByteArray();

        return Base64.encodeToString(bytes, Base64.DEFAULT);
    }

Currently I am doing like this

    private String toBase64(Uri video) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            String path = getPath(video);
            File tmpFile = new File(path);
            BufferedInputStream in = new BufferedInputStream(new FileInputStream(tmpFile));
            long length = tmpFile.length();
            int inLength = (int) length;
            byte[] b = new byte[inLength];
            int bytesRead;
            while ((bytesRead = in.read(b)) != -1) {
                baos.write(b, 0, bytesRead);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return Base64.encodeToString(baos.toByteArray(), Base64.DEFAULT);
    }

I get the base64, though I don't know if it's the correct one. but, I could not check video size, duration, etc. and also when I try to send the base64 to the server, I get error Unexpected response code 500.