Call Camera class when input wrong password - java

I'm creating an Android app to capture image when input the wrong password so I created Camera class & Launcher class:
Camera.java
import android.app.Activity;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View;
import android.widget.ImageView;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class Camera extends Activity{
private static final int CAMERA_REQUEST = 1888;
private static final int ACTION_TAKE_PHOTO = 1;
ImageView mimageView;
String mCurrentPhotoPath;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
private boolean hasCamera() {
if (getPackageManager().hasSystemFeature(
PackageManager.FEATURE_CAMERA_FRONT)){
return true;
} else {
return false;
}
}
private void takePicture(int actionCode){
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
switch (actionCode){
case ACTION_TAKE_PHOTO:
boolean front_camera = hasCamera();
File f = null;
try {
if (front_camera){
f = setUpPhotoFile();
mCurrentPhotoPath = f.getAbsolutePath();
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
}
else {
return;
};
} catch (IOException e) {
e.printStackTrace();
f = null;
mCurrentPhotoPath = null;
}
break;
default:
break;
}
startActivityForResult(intent,CAMERA_REQUEST);
mimageView.setVisibility(View.INVISIBLE);
}
private File createImageFile() throws IOException {
// Create an image file name
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
String imageFileName = "JPEG_" + timeStamp + "_";
File storageDir = getExternalFilesDir(Environment.DIRECTORY_PICTURES);
File image = File.createTempFile(
imageFileName, /* prefix */
".jpg", /* suffix */
storageDir /* directory */
);
// Save a file: path for use with ACTION_VIEW intents
mCurrentPhotoPath = "file:" + image.getAbsolutePath();
return image;
}
private File setUpPhotoFile() throws IOException {
File f = createImageFile();
mCurrentPhotoPath = f.getAbsolutePath();
return f;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {
Bitmap mphoto = (Bitmap) data.getExtras().get("data");
mimageView.setImageBitmap(mphoto);
takePicture(ACTION_TAKE_PHOTO);
}
}
}
Launcher.java
import android.app.KeyguardManager;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.graphics.Typeface;
import android.os.IBinder;
import android.os.SystemClock;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.StreamCorruptedException;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Collections;
import java.util.Vector;
public class Launcher extends Service implements View.OnClickListener, View.OnTouchListener{
WindowManager windowManager;
WindowManager.LayoutParams layoutparams;
RelativeLayout relativeLayout;
TextView text;
String password;
String password_saved;
String hint;
Vector<Long> hold_time;
long down_time[];
Vector<Vector<Float>> pressure;
Vector pressure_num[];
Vector<Vector<Float>> size;
Vector size_num[];
Button nums[]=null;
ImageButton clear;
ImageButton ok;
Vector<Vector<Float>> vecs;
Vector<Float> H_2;
#Override
public IBinder onBind(Intent intent){
return null;
}
#Override
public void onCreate(){
super.onCreate();
Log.d("Launcher","onCreate()");
KeyguardManager.KeyguardLock keyguardLock;
KeyguardManager keyguardManager=(KeyguardManager)getSystemService(KEYGUARD_SERVICE);
keyguardLock=keyguardManager.newKeyguardLock("");
keyguardLock.disableKeyguard();
IntentFilter intentFilter=new IntentFilter("android.intent.action.SCREEN_OFF");
intentFilter.addAction("android.intent.action.SCREEN_ON");
registerReceiver(screenReceiver, intentFilter);
setUpLayout();
}
#Override
public int onStartCommand(Intent intent,int flags,int startId){
return Service.START_STICKY;
}
#Override
public void onDestroy(){
unregisterReceiver(screenReceiver);
Log.d("Service","Service stop!!!");
// startActivity(new Intent(Launcher.this,Launcher.class));
// KeyguardManager.KeyguardLock keyguardLock;
// KeyguardManager keyguardManager=(KeyguardManager)getSystemService(KEYGUARD_SERVICE);
// keyguardLock=keyguardManager.newKeyguardLock("");
// keyguardLock.reenableKeyguard();
super.onDestroy();
}
private BroadcastReceiver screenReceiver=new BroadcastReceiver() {
public boolean wasScreenOn=true;
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
Log.d("Launcher","action is "+action);
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){
wasScreenOn=false;
launchLock();
}else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
wasScreenOn=true;
}else if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)){
launchLock();
}
}
};
public int dpToPx(int dp) {
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
return Math.round(dp * (displayMetrics.xdpi / DisplayMetrics.DENSITY_DEFAULT));
}
public int spTpPx(int sp) {
DisplayMetrics displayMetrics = getApplicationContext().getResources().getDisplayMetrics();
return Math.round(sp * displayMetrics.scaledDensity);
}
private void setUpLayout(){
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
layoutparams= new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.RGBA_8888
);
nums=new Button[10];
relativeLayout = new RelativeLayout(this);
relativeLayout.setBackgroundResource(R.drawable.back);
int marginPix=dpToPx(-16);
int paddingPix=dpToPx(20);
RelativeLayout.LayoutParams params[]=new RelativeLayout.LayoutParams[10];
for (int i=0;i<10;i++){
params[i]=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
params[i].bottomMargin=marginPix;
nums[i]=new Button(this);
nums[i].setId(i);
nums[i].setPadding(paddingPix, paddingPix, paddingPix, paddingPix);
nums[i].setTextSize(TypedValue.COMPLEX_UNIT_SP, 35);
nums[i].setTypeface(null, Typeface.NORMAL);
nums[i].setTextColor(Color.parseColor("#a0333333"));
nums[i].setBackgroundColor(Color.parseColor("#00000000"));
nums[i].setOnClickListener(this);
nums[i].setOnTouchListener(this);
}
params[2].addRule(RelativeLayout.CENTER_IN_PARENT);
nums[2].setText(R.string.num_2);
params[5].addRule(RelativeLayout.CENTER_HORIZONTAL);
params[5].addRule(RelativeLayout.BELOW, 2);
nums[5].setText(R.string.num_5);
params[1].addRule(RelativeLayout.LEFT_OF, 2);
params[1].addRule(RelativeLayout.ABOVE,5);
nums[1].setText(R.string.num_1);
params[3].addRule(RelativeLayout.RIGHT_OF, 2);
params[3].addRule(RelativeLayout.ABOVE, 5);
nums[3].setText(R.string.num_3);
params[4].addRule(RelativeLayout.LEFT_OF, 2);
params[4].addRule(RelativeLayout.BELOW,2);
nums[4].setText(R.string.num_4);
params[6].addRule(RelativeLayout.RIGHT_OF, 2);
params[6].addRule(RelativeLayout.BELOW, 2);
nums[6].setText(R.string.num_6);
params[7].addRule(RelativeLayout.LEFT_OF, 5);
params[7].addRule(RelativeLayout.BELOW,5);
nums[7].setText(R.string.num_7);
params[8].addRule(RelativeLayout.BELOW, 5);
params[8].addRule(RelativeLayout.RIGHT_OF,4);
nums[8].setText(R.string.num_8);
params[9].addRule(RelativeLayout.BELOW, 5);
params[9].addRule(RelativeLayout.RIGHT_OF,5);
nums[9].setText(R.string.num_9);
params[0].addRule(RelativeLayout.BELOW, 8);
params[0].addRule(RelativeLayout.RIGHT_OF,7);
nums[0].setText(R.string.num_0);
RelativeLayout.LayoutParams clear_param=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
clear_param.addRule(RelativeLayout.BELOW,8);
clear_param.addRule(RelativeLayout.LEFT_OF, 8);
clear_param.setMargins(0, dpToPx(6), dpToPx(12), 0);
clear=new ImageButton(this);
clear.setId(R.id.clear);
clear.setImageResource(R.drawable.ic_action_cancel);
clear.setBackgroundColor(Color.parseColor("#00000000"));
clear.setPadding(paddingPix, paddingPix, paddingPix, paddingPix);
clear.setLayoutParams(clear_param);
clear.setOnClickListener(this);
RelativeLayout.LayoutParams ok_param=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
ok_param.addRule(RelativeLayout.BELOW,8);
ok_param.addRule(RelativeLayout.RIGHT_OF, 8);
ok_param.setMargins(dpToPx(12), dpToPx(6), 0, 0);
ok=new ImageButton(this);
ok.setId(R.id.ok);
ok.setImageResource(R.drawable.ic_action_accept);
ok.setBackgroundColor(Color.parseColor("#00000000"));
ok.setPadding(paddingPix, paddingPix, paddingPix, paddingPix);
ok.setLayoutParams(ok_param);
ok.setOnClickListener(this);
RelativeLayout.LayoutParams text_param=new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
text_param.addRule(RelativeLayout.CENTER_HORIZONTAL);
text_param.addRule(RelativeLayout.ABOVE,2);
text=new TextView(this);
text.setId(R.id.text);
text.setLayoutParams(text_param);
text.setTextSize(TypedValue.COMPLEX_UNIT_SP, 30);
text.setTypeface(null, Typeface.NORMAL);
text.setTextColor(Color.parseColor("#a0333333"));
text.setBackgroundColor(Color.parseColor("#00000000"));
text.setPadding(dpToPx(30),dpToPx(30),dpToPx(30),dpToPx(30));
for (int i=0;i<10;i++){
nums[i].setLayoutParams(params[i]);
}
for (int i=0;i<10;i++){
relativeLayout.addView(nums[i]);
}
relativeLayout.addView(clear);
relativeLayout.addView(ok);
relativeLayout.addView(text);
}
private void launchLock(){
try {
//load password and vecs from file
FileInputStream fileInputStream=openFileInput("password");
ObjectInputStream objectInputStream=new ObjectInputStream(fileInputStream);
password_saved=(String)objectInputStream.readObject();
vecs=(Vector<Vector<Float>>)objectInputStream.readObject();
H_2=(Vector<Float>)objectInputStream.readObject();
Log.d("password_saved",password_saved);
Log.d("vecs",vecs.toString());
Log.d("H_2",H_2.toString());
objectInputStream.close();
fileInputStream.close();
} catch (FileNotFoundException e) {
Log.d("window manager", "file not found");
try{
windowManager.removeView(relativeLayout);
}catch (IllegalArgumentException e1){
Log.d("window manager","has no layout");
}
return;
} catch (StreamCorruptedException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
password="";
hint="";
hold_time=new Vector<Long>();
down_time=new long[10];
pressure=new Vector<Vector<Float>>();
pressure_num=new Vector[10];
size=new Vector<Vector<Float>>();
size_num=new Vector[10];
text.setText(hint);
for (int i=0;i<10;i++){
pressure_num[i]=new Vector<Float>();
size_num[i]=new Vector<Float>();
}
try {
windowManager.addView(relativeLayout,layoutparams);
}catch (RuntimeException e){
// e.printStackTrace();
Log.d("window manager","layout has already been added");
}
}
#Override
public void onClick(View view) {
int id=view.getId();
if (id==R.id.ok){
Log.d("launcher","ok");
Log.d("password",password);
Log.d("hold time",hold_time.toString());
Log.d("pressure",pressure.toString());
Log.d("size",size.toString());
try {
//turn password to md5
byte[] bytes = password.getBytes("UTF-8");
MessageDigest md=MessageDigest.getInstance("MD5");
bytes=md.digest(bytes);
password=new String(bytes);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
Vector<Float> vec=new Vector<Float>();
for (long value:hold_time){
vec.add((float) value);
}
for (Vector<Float> values:pressure){
vec.add(Collections.max(values));
}
for (Vector<Float> values:size){
vec.add(Collections.max(values));
}
Log.d("vec",vec.toString());
Log.d("MD5",password);
boolean quit=true;
//if password is equal
Vector<Float> probs=new Vector<Float>();
if (password.equals(password_saved)){
for (int i=0;i<H_2.size();i++){
float p=0;
for (int j=0;j<vecs.size();j++){
//np.exp(-1./2.*(v_test[i]-v_train[i])**2/H_2[i])
p+=Math.exp(-1./2.*
(vec.elementAt(i)-vecs.elementAt(j).elementAt(i))*
(vec.elementAt(i)-vecs.elementAt(j).elementAt(i))/
H_2.elementAt(i)
);
}
p/=vecs.size();
probs.add(p*p);
}
Log.d("probs ",probs.toString());
Float sum_probs= new Float(0);
for (int i=0;i<probs.size()/3*2;i++){
sum_probs+=probs.elementAt(i);
}
Log.d("sum_probs ",sum_probs.toString());
if (sum_probs<0.25*probs.size()/3*2)
quit=false;
}else{
quit=false;
}
if (quit)
windowManager.removeView(relativeLayout);
else{
//if fail, then init
text.setText("Wrong password");
hint="";
password="";
hold_time=new Vector<Long>();
pressure=new Vector<Vector<Float>>();
size=new Vector<Vector<Float>>();
}
}else if (id==R.id.clear){
text.setText("Please enter again");
hint="";
password="";
hold_time=new Vector<Long>();
pressure=new Vector<Vector<Float>>();
size=new Vector<Vector<Float>>();
}else {
text.setText(hint+="*");
password+=Integer.toString(id);
Log.d("password",password);
}
}
#Override
public boolean onTouch(View view, MotionEvent motionEvent) {
int id=view.getId();
if(motionEvent.getActionMasked()==MotionEvent.ACTION_DOWN){
down_time[id]= SystemClock.uptimeMillis();
pressure_num[id]=new Vector<Float>();
size_num[id]=new Vector<Float>();
}else if(motionEvent.getActionMasked()==MotionEvent.ACTION_UP){
hold_time.add(SystemClock.uptimeMillis()-down_time[id]);
pressure.add((Vector<Float>)pressure_num[id]);
size.add((Vector<Float>)size_num[id]);
}
pressure_num[id].add(motionEvent.getPressure());
size_num[id].add(motionEvent.getSize());
return false;
}
}
The problem is that I don't know how to call Camera class in Launcher class

Related

textureview is not updating after coming back from another activity in onResume

I am trying to play some rtsp video on custom textureview.Video is playing for the first time but when I go to second activity where the same video is played (not reinstantiated,same session but with different textureview) there it is playing and coming back to first activity where I am setting the sureface again in onResume textureview is still showing the content where it was left for the first time.Interesting fact is like video is still playing, just it is not visible in the textureview and if I go to second screen like before it is showing.I tried both releasing the surfacetexture and not releasing, tried also releasing the surface which I am holding a reference in the first activity for future use, not any of those seems to work.What can be the possible reason?
in onResume I am checking if app is coming back from app drawer or full screen activity.Where making the app go to background by clicking home button and coming back to app from app drawer video is playing.Only when coming back from full screen it's not working.
StreamingActivity.java
package com.wiznsystems.android.activities;
import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.SurfaceTexture;
import android.os.AsyncTask;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.TextureView;
import android.view.View;
import android.view.Display;
import android.view.Surface;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.myeglu.android.R;
import com.myeglu.zoomview.ZoomTextureView;
import com.wiznsystems.android.App;
import com.wiznsystems.android.data.objects.FFMPEG;
import com.wiznsystems.android.utils.Constants;
import com.wiznsystems.android.utils.Events;
import com.wiznsystems.android.utils.FFMPEGPlayer;
import java.io.File;
import de.greenrobot.event.EventBus;
import hugo.weaving.DebugLog;
import timber.log.Timber;
/**
* An example full-screen activity that shows and hides the system UI (i.e.
* status bar and navigation/system bar) with user interaction.
*/
#SuppressWarnings("JniMissingFunction")
public class StreamingActivity extends Fragment implements TextureView.SurfaceTextureListener{
private static boolean loadedLibraries;
private boolean comingFromAppDrawer;
private boolean isComingFromFullScreen;
boolean anotherVideo=false;
boolean shouldTextureUpdate=false;
Surface surface;
public StreamingActivity(){
}
public static ZoomTextureView surfaceView;
private ProgressBar progressBar;
public static boolean isPlaying;
private int isInitialized;
public static int isFullScreenDisplayed=0;
private String url;
public boolean isFirstTime;
private FFMPEG ffmpeg;
private FrameLayout frameLayout;
private final String TAG=StreamingActivity.class.getSimpleName();
int w=0,h=0;
private boolean isFirstTimeForFullscreen=true;
private Button fullScreenButton;
FFMPEGPlayer ffmpegPlayer;
String buttonText="";
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
EventBus.getDefault().register(this);
url=getArguments().getString("url");
Log.d("ANURAN",url);
//getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_HARDWARE_ACCELERATED);
ffmpegPlayer=App.getFFMPEG();
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view=inflater.inflate(R.layout.activity_streaming,null,false);
surfaceView = (ZoomTextureView) view.findViewById(R.id.textureView);
frameLayout=(FrameLayout)view.findViewById(R.id.streaming_framelayout);
progressBar = ((ProgressBar)view.findViewById(R.id.progressBar));
fullScreenButton=(Button)view.findViewById(R.id.fullScreenButton);
fullScreenButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
isFullScreenDisplayed = 1;
isComingFromFullScreen = true;
shouldTextureUpdate=true;
if (isFirstTimeForFullscreen) {
//ffmpegPlayer.libSetSurface(null);
isFirstTimeForFullscreen = false;
}
//surfaceView.getSurfaceTexture().release();
//surface.release();
progressBar.setVisibility(View.INVISIBLE);
goFullScreen();
} catch (Exception throwable) {
throwable.printStackTrace();
}
}
});
progressBar.setVisibility(View.VISIBLE);
Log.d("ANURAN","onCreateView called");
surfaceView.setSurfaceTextureListener(this);
return view;
}
#Override
public void onViewCreated(#NonNull View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
//Log.d(TAG,url);
}
#DebugLog
private void postInit() {
Events.PlayButtonBGChanger playButtonBGChanger=new Events.PlayButtonBGChanger();
if (isInitialized==0) {
playButtonBGChanger.setShouldChange(true);
initPlay();
progressBar.setVisibility(View.GONE);
} else if(isInitialized==-999){
playButtonBGChanger.setShouldChange(false);
progressBar.setVisibility(View.INVISIBLE);
Snackbar.make(frameLayout,"Please make sure you have stopped other playing videos before playing this one.",Snackbar.LENGTH_LONG).show();
}
else {
playButtonBGChanger.setShouldChange(false);
Snackbar.make(frameLayout,"Something went wrong while live streaming.Please try again later.",Snackbar.LENGTH_LONG).show();
}
EventBus.getDefault().post(playButtonBGChanger);
}
private void initPlay() {
try {
int[] res = ffmpegPlayer.libGetVideoRes();
Log.d("ANURAN", "res width " + res[0] + ": height " + res[1]);
if (res[0] <= 0) {
res[0] = 480;
}
if (res[1] <= 0) {
res[1] = 320;
}
int[] screenRes = getScreenRes();
int width, height;
float widthScaledRatio = screenRes[0] * 1.0f / res[0];
float heightScaledRatio = screenRes[1] * 1.0f / res[1];
if (widthScaledRatio > heightScaledRatio) {
//use heightScaledRatio
width = (int) (res[0] * heightScaledRatio);
height = screenRes[1];
} else {
//use widthScaledRatio
width = screenRes[0];
height = (int) (res[1] * widthScaledRatio);
}
Log.d(TAG, "width " + width + ",height:" + height);
w=width;
h=height;
updateSurfaceView(width, height);
try{
ffmpegPlayer.libSetup(width,height);
if(this.surface == null){
Log.d("ANURAN","surface is null");
}
if(anotherVideo)
ffmpegPlayer.libSetSurface(null);
ffmpegPlayer.libSetSurface(surface);
Log.d("ANURAN","libsetsurface set initPlay()");
}catch (Exception throwable){
Toast.makeText(getActivity(),"Something went wrong while live streaming.Try again",Toast.LENGTH_SHORT).show();
}
playMedia();
}catch (Exception throwable){
throwable.printStackTrace();
}
}
public FFMPEGPlayer getFFMPEGPlayer(){
return this.ffmpegPlayer;
}
private void playMedia() {
if(progressBar.getVisibility()==View.VISIBLE){
progressBar.setVisibility(View.GONE);
}
try{
ffmpegPlayer.libPlay();
}catch (Exception throwable){
Toast.makeText(getActivity(),"Something went wrong while live streaming.Try again",Toast.LENGTH_SHORT).show();
}
isPlaying = true;
CamerasActivity.isPlaying=true;
}
#DebugLog
private void updateSurfaceView(int pWidth, int pHeight) {
//update surfaceview dimension, this will cause the native window to change
Log.d("ANURAN UPDATE SURFACE", "width " + pWidth + ",height:" + pHeight);
FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) surfaceView.getLayoutParams();
params.width = pWidth;
params.height = pHeight;
surfaceView.setLayoutParams(params);
surfaceView.requestLayout();
}
#DebugLog
#SuppressLint("NewApi")
private int[] getScreenRes() {
int[] res = new int[2];
Display display = getActivity().getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
res[0] = size.x;
res[1] = size.y;
return res;
}
public void stopPlaying() {
isPlaying = false;
try{
ffmpegPlayer.libStop();
// ffmpegPlayer.libSetSurface(null);
// surfaceView.getSurfaceTexture().release();
// surfaceView.getSurfaceTexture().detachFromGLContext();
}catch (Exception throwable){
}
}
#Override
public void onStop() {
// Toast.makeText(getActivity(),"onStop called",Toast.LENGTH_SHORT).show();
// stopPlaying();
comingFromAppDrawer=true;
// if(surfaceView.getSurfaceTexture() !=null){
// surfaceView.getSurfaceTexture().release();
//
// }
// if(surface !=null){
// surface.release();
// surface=null;
// }
// if(isFullScreenDisplayed==0){
// stopPlaying();
// }
Log.d("ANURAN onStop",surface.isValid()+"");
super.onStop();
}
#Override
public void onPause() {
// Toast.makeText(getActivity(),"onStop called",Toast.LENGTH_SHORT).show();
// stopPlaying();
isComingFromFullScreen=true;
super.onPause();
}
#Override
public void onResume() {
super.onResume();
if(isComingFromFullScreen){
progressBar.setVisibility(View.INVISIBLE);
if(surface !=null){
ffmpegPlayer.libSetSurface(null);
Log.d("ANURAN onResume","value of surface "+surface.isValid());
ffmpegPlayer.libSetSurface(surface);
}
}
else if(comingFromAppDrawer){
//stopPlaying();
progressBar.setVisibility(View.INVISIBLE);
if(surface !=null){
ffmpegPlayer.libSetSurface(null);
//ffmpegPlayer.libSetup(w,h);
ffmpegPlayer.libSetSurface(surface);
}
}
}
#Override
public void onDestroy() {
super.onDestroy();
stopPlaying();
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
if(this.surface !=null) {
this.surface.release();
this.surface=null;
}
this.surface=new Surface(surface);
Log.d("ANURAN","surfacetexture available streaming activity");
new PlayVideo().execute();
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
Log.d("ANURAN","surfacetexturesize changed streaming activity");
try{
w=width;
h=height;
this.surface.release();
this.surface=null;
this.surface=new Surface(surface);
if(isComingFromFullScreen){
//surfaceView.getHolder().getSurface().release();
updateSurfaceView(width, height);
ffmpegPlayer.libSetup(width,height);
ffmpegPlayer.libSetSurface(this.surface);
}
}catch (Exception throwable){
Toast.makeText(getActivity(),"Something went wrong while live streaming.Try again",Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
Log.d("ANURAN","surfacetexture destroyed streaming activity");
// surfaceView.getSurfaceTexture().release();
// if(this.surface !=null){
// this.surface.release();
// this.surface=null;
// }
return false;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
Log.d("ANURAN","surfacetexture updated streaming activity");
if(this.surface !=null){
this.surface.release();
this.surface=null;
this.surface=new Surface(surface);
}else{
this.surface=new Surface(surface);
}
}
public class PlayVideo extends AsyncTask<Void,Void,Void>{
#Override
protected Void doInBackground(Void... voids) {
try{
isInitialized=ffmpegPlayer.libInit(url);
}catch (Exception e){
e.printStackTrace();
Snackbar.make(frameLayout,"Exception Occured",Snackbar.LENGTH_SHORT).show();
}
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
isFirstTime=false;
postInit();
this.cancel(true);
}
}
public void onEvent(FFMPEG ffmpeg){
url = ffmpeg.getUrl();
progressBar.setVisibility(View.VISIBLE);
//stopPlaying();
anotherVideo=true;
new PlayVideo().execute();
}
public void onEvent(Events.UpdateUrl newurl){
url=newurl.getUrl();
}
public void onEvent(Events.StopPlayback event){
stopPlaying();
}
public void onEvent(Events.NotifyPlayer notifyPlayer){
Snackbar.make(frameLayout,"Please stop any running video before playing another one",Toast.LENGTH_SHORT).show();
}
private void goFullScreen(){
Intent intent=new Intent(getContext(),FullScreenActivity.class);
Bundle bundle=new Bundle();
bundle.putString("url",url);
intent.putExtras(bundle);
getActivity().startActivity(intent);
}
}
FullScreenActivity.java
package com.wiznsystems.android.activities;
import android.annotation.SuppressLint;
import android.graphics.Matrix;
import android.graphics.Point;
import android.graphics.RectF;
import android.graphics.SurfaceTexture;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.TextureView;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Toast;
import com.myeglu.android.R;
import com.myeglu.zoomview.AngleView;
import com.myeglu.zoomview.MatrixChangeListener;
import com.myeglu.zoomview.ZoomTextureView;
import com.wiznsystems.android.App;
import com.wiznsystems.android.data.objects.FFMPEG;
import com.wiznsystems.android.utils.FFMPEGPlayer;
import uk.copywitchshame.senab.photoview.gestures.PhotoViewAttacher;
import hugo.weaving.DebugLog;
/**
* Created by anuran on 9/3/18.
*/
#SuppressWarnings("JniMissingFunction")
public class FullScreenActivity extends AppCompatActivity implements TextureView.SurfaceTextureListener, PhotoViewAttacher.OnMatrixChangedListener {
private ZoomTextureView surfaceView;
public static AngleView angleView;
private ProgressBar progressBar;
private PhotoViewAttacher photoViewAttacher;
public static boolean isPlaying;
private boolean isInitialized;
private String url;
private FrameLayout frameLayout;
Surface surface;
private final String TAG=StreamingActivity.class.getSimpleName();
public int backCounter=0;
FFMPEGPlayer ffmpegPlayer;
boolean fromADorSL=false;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
getWindow().requestFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.activity_fullscreen);
surfaceView = (ZoomTextureView) findViewById(R.id.textureView);
angleView=(AngleView)findViewById(R.id.render_angle_view);
surfaceView.setSurfaceTextureListener(this);
frameLayout=(FrameLayout)findViewById(R.id.streaming_framelayout);
progressBar = ((ProgressBar)findViewById(R.id.progressBar));
progressBar.setVisibility(View.VISIBLE);
url=getIntent().getExtras().getString("url");
//new PlayVideo().execute();
ffmpegPlayer= App.getFFMPEG();
Log.d("ANURAN","fullscreen onCreate");
}
// #DebugLog
// private void postInit() {
// if (isInitialized) {
// initPlay();
// progressBar.setVisibility(View.GONE);
// } else {
// finish();
// }
// }
// private void initPlay() {
//
// try{
// int[] res = FFMPEGPlayer.libGetVideoRes();
// Log.d("ANURAN", "res width " + res[0] + ": height " + res[1]);
// if (res[0] <= 0) {
// res[0] = 480;
// }
// if (res[1] <= 0) {
// res[1] = 320;
// }
// int[] screenRes = getScreenRes();
// int width, height;
// float widthScaledRatio = screenRes[0] * 1.0f / res[0];
// float heightScaledRatio = screenRes[1] * 1.0f / res[1];
// if (widthScaledRatio > heightScaledRatio) {
// //use heightScaledRatio
// width = (int) (res[0] * heightScaledRatio);
// height = screenRes[1];
// } else {
// //use widthScaledRatio
// width = screenRes[0];
// height = (int) (res[1] * widthScaledRatio);
// }
// Log.d(TAG, "width " + width + ",height:" + height);
// updateSurfaceView(width, height);
// FFMPEGPlayer.libSetup(width, height);
// playMedia();
//
// photoViewAttacher = new PhotoViewAttacher(surfaceView, width, height);
// photoViewAttacher.setScaleType(ImageView.ScaleType.CENTER_CROP);
// photoViewAttacher.setOnMatrixChangeListener(this);
// photoViewAttacher.update();
// }catch (Exception e){
//
// }
// }
// private void playMedia() {
//
// try{
// if(progressBar.getVisibility()==View.VISIBLE){
// progressBar.setVisibility(View.GONE);
// }
// FFMPEGPlayer.libPlay();
// isPlaying = true;
// CamerasActivity.isPlaying=true;
// }catch (Exception e){
//
// }
// }
// #DebugLog
// private void updateSurfaceView(int pWidth, int pHeight) {
// //update surfaceview dimension, this will cause the native window to change
// Log.d("ANURAN UPDATE SURFACE", "width " + pWidth + ",height:" + pHeight);
// FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) surfaceView.getLayoutParams();
// params.width = pWidth;
// params.height = pHeight;
// surfaceView.setLayoutParams(params);
// }
#Override
public void onBackPressed() {
if(backCounter==1){
super.onBackPressed();
}else{
//surface.release();
StreamingActivity.isFullScreenDisplayed=0;
surfaceView.getSurfaceTexture().release();
//ffmpegPlayer.libSetSurface(null);
if(this.surface !=null){
this.surface.release();
this.surface=null;
}
backCounter++;
Toast.makeText(FullScreenActivity.this,"Press back again to quit full screen",Toast.LENGTH_SHORT).show();
}
}
#DebugLog
#SuppressLint("NewApi")
private int[] getScreenRes() {
int[] res = new int[2];
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
res[0] = size.x;
res[1] = size.y;
return res;
}
private void stopPlaying() {
isPlaying = false;
try{
ffmpegPlayer.libStop();
}catch (Exception e){
}
}
#Override
public void onStop() {
super.onStop();
fromADorSL=true;
}
#Override
public void onResume() {
super.onResume();
if(fromADorSL){
ffmpegPlayer.libSetSurface(null);
ffmpegPlayer.libSetSurface(this.surface);
}
}
#Override
public void onStart() {
super.onStart();
}
#Override
public void onSurfaceTextureAvailable(SurfaceTexture surface, int width, int height) {
//Toast.makeText(FullScreenActivity.this,"SurfaceTexture available",Toast.LENGTH_SHORT).show();
//updateSurfaceView(width, height);
try{
this.surface=new Surface(surface);
ffmpegPlayer.libSetup(width, height);
ffmpegPlayer.libSetSurface(this.surface);
photoViewAttacher = new PhotoViewAttacher(surfaceView, width, height);
photoViewAttacher.setScaleType(ImageView.ScaleType.CENTER_CROP);
photoViewAttacher.setOnMatrixChangeListener(this);
photoViewAttacher.update();
progressBar.setVisibility(View.INVISIBLE);
angleView.setVisibility(View.VISIBLE);
}catch (Exception e){
}
}
#Override
public void onSurfaceTextureSizeChanged(SurfaceTexture surface, int width, int height) {
try{
Toast.makeText(FullScreenActivity.this,"SurfaceTexture changed",Toast.LENGTH_SHORT).show();
if (photoViewAttacher != null ) {
photoViewAttacher.update ();
}
if(this.surface !=null){
this.surface.release();
}
this.surface=null;
this.surface=new Surface(surface);
ffmpegPlayer.libSetup(width,height);
ffmpegPlayer.libSetSurface(this.surface);
}catch (Exception e){
}
}
#Override
public boolean onSurfaceTextureDestroyed(SurfaceTexture surface) {
try{
// this.surface.release();
// this.surface=null;
surfaceView.getSurfaceTexture().release();
if(this.surface !=null){
this.surface.release();
this.surface=null;
}
//ffmpegPlayer.libSetSurface(null);
}catch (Exception e){
}
return true;
}
#Override
public void onSurfaceTextureUpdated(SurfaceTexture surface) {
if(this.surface !=null){
this.surface.release();
this.surface=null;
this.surface=new Surface(surface);
}
}
#Override
public void onMatrixChanged(Matrix matrix, RectF rectF) {
float maxMovement = (rectF.width() - surfaceView.getWidth());
float middle = surfaceView.getWidth() * 0.5f + surfaceView.getLeft();
float currentMiddle = rectF.width() * 0.5f + rectF.left;
float angle=(-(int) ((currentMiddle - middle) * 100 / maxMovement));
Log.d("ANURAN",angle+"");
angleView.setCurrentProgress((int)angle);
}
// public class PlayVideo extends AsyncTask<Void,Void,Void> {
//
// #Override
// protected Void doInBackground(Void... voids) {
// try{
// isInitialized=(FFMPEGPlayer.libInit(url)==0);
// }catch (Exception e){
// e.printStackTrace();
// }
// return null;
// }
//
// #Override
// protected void onPostExecute(Void aVoid) {
// super.onPostExecute(aVoid);
// postInit();
// this.cancel(true);
// }
// }
}

logcat file showing errors

package com.example.ishan.complainbox;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.AppCompatImageButton;
import android.view.View;
import android.widget.EditText;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.os.Environment;
import android.provider.MediaStore;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.Toast;
import android.support.v7.widget.AppCompatImageView;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import android.graphics.drawable.BitmapDrawable;
public class Crime extends MainActivity implements
View.OnClickListener,LocationListener {
GoogleMap googleMap;
private int REQUEST_CAMERA = 0, SELECT_FILE = 1;
private Button btnSelect;
private ImageView imgView,ivImage;
private String userChosenTask;
EditText street, city, pincode, detail;
Button btnsave;
crimeDBHandler dbHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isGooglePlayServicesAvailable()) {
finish();
setContentView(R.layout.activity_crime);
// Get References of Views
street = (EditText) findViewById(R.id.str);
city = (EditText) findViewById(R.id.city);
pincode = (EditText) findViewById(R.id.pin);
detail = (EditText) findViewById(R.id.detail);
imgView = (ImageView)findViewById(R.id.imgView);
btnsave = (Button) findViewById(R.id.save);
btnSelect = (Button) findViewById(R.id.uploadpic);
dbHandler = new crimeDBHandler(this, null, null, 1);
btnSelect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
String strt = street.getText().toString();
String cty = city.getText().toString();
String pin = pincode.getText().toString();
String det = detail.getText().toString();
Bitmap bitmap =
((BitmapDrawable)imageView.getDrawable()).getBitmap();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
byte[] imageInByte = baos.toByteArray();
btnsave = (Button) findViewById(R.id.save);
selectImage();
dbHandler.insertEntry(strt, cty, pin, det,imageInByte);
Toast.makeText(getApplicationContext(), "Complaint
Successfully Filed ", Toast.LENGTH_LONG).show();
}
});
ivImage = (ImageView) findViewById(R.id.img);
}
}
#Override
public void onRequestPermissionsResult ( int requestCode, String[]
permissions,
int[] grantResults){
switch (requestCode) {
case Utility.MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE:
if (grantResults.length > 0 && grantResults[0] ==
PackageManager.PERMISSION_GRANTED) {
if (userChosenTask.equals("Take Photo"))
cameraIntent();
else if (userChosenTask.equals("Choose from Library"))
galleryIntent();
} else
break;
}
}
private boolean isGooglePlayServicesAvailable() {
int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this);
if (ConnectionResult.SUCCESS == status) {
return true;
} else {
GooglePlayServicesUtil.getErrorDialog(status, this, 0).show();
return false;
}
}
private void selectImage() {
final CharSequence[] items = {"Take Photo", "Choose from Library",
"Cancel" };
AlertDialog.Builder builder = new AlertDialog.Builder(Crime.this);
builder.setTitle("Add Photo!");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
boolean result=userChosenTask.checkPermission(Crime.this);
if (items[item].equals("Take Photo"))
{
userChosenTask ="Take Photo";
if(result)
cameraIntent();
}
else if (items[item].equals("Choose from Library"))
{
userChosenTask ="Choose from Library";
if(result)
galleryIntent();
}
else if (items[item].equals("Cancel"))
{
dialog.dismiss();
}
}
});
builder.show();
}
private void galleryIntent()
{
Intent intent = new Intent();
intent.setType("image/*video/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select
File"),SELECT_FILE);
}
private void cameraIntent()
{
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent
data)
{
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == SELECT_FILE)
onSelectFromGalleryResult(data);
else if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new
File(Environment.getExternalStorageDirectory(),System.currentTimeMillis()
+ ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
ivImage.setImageBitmap(thumbnail);
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm =
MediaStore.Images.Media.getBitmap
(getApplicationContext().getContentResolver(), data.getData());
}
catch (IOException e) {
e.printStackTrace();
}
}
ivImage.setImageBitmap(bm);
}
#Override
public void onLocationChanged(Location location) {
TextView locationTv = (TextView) findViewById(R.id.latlongLocation);
double latitude = location.getLatitude();
double longitude = location.getLongitude();
LatLng latLng = new LatLng(latitude, longitude);
googleMap.addMarker(new MarkerOptions().position(latLng));
googleMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
googleMap.animateCamera(CameraUpdateFactory.zoomTo(15));
locationTv.setText("Latitude:" + latitude + ", Longitude:" + longitude);
}
#Override
public void onStatusChanged(String provider, int status, Bundle extras)
{
}
#Override
public void onProviderEnabled(String provider) {
}
#Override
public void onProviderDisabled(String provider) {
}
}
This is one activity class of my android project and this activity depends on another utility class....which is mentioned below:
The statement Bitmap bitmap = ((BitmapDrawable)imageView.getDrawable()).getBitmap(); shows an error in "imageView" and the statement boolean result=userChosenTask.checkPermission(Crime.this); shows an error on "checkPermission"...but I don't understand why...because checkPermission is already defined in the utility class....
package com.example.ishan.complainbox;
/**
* Created by ishan on 11/04/2017.
*/
import android.os.Build;
import android.content.Context;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AlertDialog;
import android.Manifest;
import android.content.pm.PackageManager;
import android.content.DialogInterface;
public class Utility {
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE = 123;
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public static boolean checkPermission(final Context context)
{
int currentAPIVersion = Build.VERSION.SDK_INT;
if(currentAPIVersion>=android.os.Build.VERSION_CODES.M)
{
if (ContextCompat.checkSelfPermission(context,
Manifest.permission.READ_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED)
{
if
(ActivityCompat.shouldShowRequestPermissionRationale((MainActivity) context,
Manifest.permission.READ_EXTERNAL_STORAGE))
{
AlertDialog.Builder alertBuilder = new
AlertDialog.Builder(context);
alertBuilder.setCancelable(true);
alertBuilder.setTitle("Permission necessary");
alertBuilder.setMessage("External storage permission is
necessary");
alertBuilder.setPositiveButton(android.R.string.yes, new
DialogInterface.OnClickListener() {
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public void onClick(DialogInterface dialog, int which) {
ActivityCompat.requestPermissions((MainActivity)
context, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
});
AlertDialog alert = alertBuilder.create();
alert.show();
} else
{
ActivityCompat.requestPermissions((MainActivity) context,
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL_STORAGE);
}
return false;
} else {
return true;
}
} else
{
return true;
}
}
}
In your manifests.xml, you need to include permission:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

Compress a picture

In my application there is a button to "upload a picture": taking a photo from camera or choosing from gallery.
On both options, there are 3 problems:
1) When clicking again to upload another picture - the application crushes
2) On the first "upload", the picture is rotated on the side (90 degrees counterclockwise)
3) The picture's size is the original size and I want it to be compressed to resolution of 125x125.
Please help (even if you have a solution to one problem)
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.app.Fragment;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStream;
import entities.Order;
public class SellABookFragment extends Fragment implements View.OnClickListener {
private ImageView ivBookPicture;
private EditText etBookName, etBookAuthor, etBookGenre, etBookPublishing, etQuantity, etBookPrice, etBookDetails;
private Button bUploadPicture, bAddBook;
public SellABookFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_sell_a_book, container, false);
ivBookPicture = (ImageView) view.findViewById(R.id.ivBook_Picture);
etBookName = (EditText) view.findViewById(R.id.etBook_Name);
etBookAuthor = (EditText) view.findViewById(R.id.etAuthor_Name);
etBookGenre = (EditText) view.findViewById(R.id.etGenre);
etBookPublishing = (EditText) view.findViewById(R.id.etPublishing_Year);
etQuantity = (EditText) view.findViewById(R.id.etBook_Quantity);
etBookPrice = (EditText) view.findViewById(R.id.etBook_Price);
etBookDetails = (EditText) view.findViewById(R.id.etBook_Details);
bUploadPicture = (Button) view.findViewById(R.id.bUpload_Picture);
bAddBook = (Button) view.findViewById(R.id.bAdd_Book);
bUploadPicture.setOnClickListener(this);
bAddBook.setOnClickListener(this);
return view;
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.bUpload_Picture:
selectPicture();
break;
case R.id.bAdd_Book:
addBook();
break;
}
}
private void addBook() {
try {
HomeActivity.backEnd.addOrder(new Order(HomeActivity.LoggedUser.getID(),
etBookGenre.getText().toString(),
etBookName.getText().toString(),
Integer.parseInt(etBookPublishing.getText().toString()),
etBookAuthor.getText().toString(),
Double.parseDouble(etBookPrice.getText().toString()),
(Integer) ivBookPicture.getTag()));
} catch (Exception e) {
Toast.makeText(getActivity().getApplicationContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
private void selectPicture() {
final CharSequence[] options = {
getResources().getString(R.string.take_photo),
getResources().getString(R.string.gallery_choose),
getResources().getString(R.string.cancel)};
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(getResources().getString(R.string.upload_picture));
builder.setItems(options, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
if (options[item].equals(getResources().getString(R.string.take_photo))) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "tmp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
} else if (options[item].equals(getResources().getString(R.string.gallery_choose))) {
Intent intent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 2);
} else
dialog.dismiss();
}
});
builder.show();
}
Bitmap bitmap;
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
OutputStream outFile;
String path = android.os.Environment.getExternalStorageDirectory()
+ File.separator
+ "MyApp";
File file;
if (resultCode == Activity.RESULT_OK) {
if (bitmap != null) {
ivBookPicture.setImageBitmap(null);
bitmap.recycle();
bitmap = null;
}
try {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File tmp : f.listFiles()) {
if (tmp.getName().equals("tmp.jpg")) {
f = tmp;
break;
}
}
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(), bitmapOptions);
ivBookPicture.setImageBitmap(bitmap);
if (f.delete()) {
file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
outFile = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getActivity().getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
bitmap = (BitmapFactory.decodeFile(picturePath));
Log.w("image path", picturePath);
ivBookPicture.setImageBitmap(bitmap);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
The ImageView which contains the uploaded picture:
<ImageView
android:id="#+id/ivBook_Picture"
android:layout_width="#dimen/sell_a_book_picture_size"
android:layout_height="#dimen/sell_a_book_picture_size"
android:src="#mipmap/ic_launcher" />
Thanks!
public Bitmap compressBySize(String pathName, int targetWidth,
int targetHeight) {
BitmapFactory.Options opts = new BitmapFactory.Options();
opts.inJustDecodeBounds = true;
Bitmap bitmap = BitmapFactory.decodeFile(pathName, opts);
int imgWidth = opts.outWidth;
int imgHeight = opts.outHeight;
int widthRatio = (int) Math.ceil(imgWidth / (float) targetWidth);
int heightRatio = (int) Math.ceil(imgHeight / (float) targetHeight);
if (widthRatio > 1 || heightRatio > 1) {
if (widthRatio > heightRatio) {
opts.inSampleSize = widthRatio;
} else {
opts.inSampleSize = heightRatio;
}
}
opts.inJustDecodeBounds = false;
bitmap = BitmapFactory.decodeFile(pathName, opts);
return bitmap;
}
Use this method to do the compress,just set the targetWidth&targetHeight yourself.
Also,you can use bitmap.compress(Bitmap.CompressFormat.JPEG, compressRate, byteOutputStream); to compress your bitmap by quality.
For the crash,it's because the picture bitmap takes too much memory.You should compress the picture and remember to release the memory after your first upload.You can consider using a WeakReference.

How can I stop music on an incoming call?

I have been trying to get my app to stop playing music when the phone is ringing, but it isn't working. I've tried everything, but it seems impossible. Here's the code.
package com.beanie.samples.streaming;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.beanie.samples.streaming.R;
import com.beanie.samples.streaming.MyService;
import android.app.Activity;
import android.app.IntentService;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
public class HomeActivity extends Activity implements OnClickListener {
private static final String TAG = "MyServices";
private final static String RADIO_STATION_URL = "http://195.154.237.162:8936/";
private static final String START_STICKY = null;
Button buttonPlay, buttonStopPlay;
/** Called when the activity is first created.
* Keep this here all the application will stop working */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay.setOnClickListener(this);
}
private ProgressBar playSeekBar;
private MediaPlayer player;
private InputStream recordingStream;
private RecorderThread recorderThread;
private boolean isRecording = false;
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
private void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Toast.makeText(this, "Buffering ", percent).show();
Log.i("Buffering", "" + percent);
}
public class GetCallerInfoActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
TelephonyManager telephonyManager = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE);
// register PhoneStateListener
PhoneStateListener callStateListener = new PhoneStateListener() {
public void onCallStateChanged(int state, String incomingNumber) {
// If phone ringing
if (state==TelephonyManager.CALL_STATE_RINGING) {
stopPlaying();
}
// If incoming call received
if (state==TelephonyManager.CALL_STATE_OFFHOOK) {
stopPlaying();
}
if (state==TelephonyManager.CALL_STATE_IDLE) {
Toast.makeText(getApplicationContext(),"phone is neither ringing nor in a call", Toast.LENGTH_LONG).show();
}
}
};
telephonyManager.listen(callStateListener,PhoneStateListener.LISTEN_CALL_STATE);
}
}
public void onClick(View v) {
if (v == buttonPlay) {
startPlaying();
player.setLooping(false); // Set looping
} else if (v == buttonStopPlay) {
Log.d(TAG, "onClick: stopping srvice");
stopPlaying();
}
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
stopRecording();
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private void startRecording() {
BufferedOutputStream writer = null;
try {
URL url = new URL(RADIO_STATION_URL);
URLConnection connection = url.openConnection();
final String FOLDER_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "Songs";
File folder = new File(FOLDER_PATH);
if (!folder.exists()) {
folder.mkdir();
}
writer = new BufferedOutputStream(new FileOutputStream(new File(FOLDER_PATH
+ File.separator + "sample.mp3")));
recordingStream = connection.getInputStream();
final int BUFFER_SIZE = 100;
byte[] buffer = new byte[BUFFER_SIZE];
while (recordingStream.read(buffer, 0, BUFFER_SIZE) != -1 && isRecording) {
writer.write(buffer, 0, BUFFER_SIZE);
writer.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
recordingStream.close();
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
try {
isRecording = false;
if (recordingStream != null) {
recordingStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class RecorderThread extends Thread {
#Override
public void run() {
isRecording = true;
startRecording();
}
};
}
Could someone please help and implement this? I would appreciate and it and it would help a lot. Also, I have even helped myself by trying.
You need to use the TelephonyManager
mTelephonyMgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
mTelephonyMgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
The listener object can be created like this
private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
// Test for incoming call, dialing call, active or on hold
if (state==TelephonyManager.CALL_STATE_RINGING || state==TelephonyManager.CALL_STATE_OFFHOOK)
{
stop(); // Put here the code to stop your music
}
super.onCallStateChanged(state, incomingNumber);
}
};
When stopping, or closing your app, remember to call this.
mTelephonyMgr.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);

Running My App In The Background

I have tried to get this working so that it plays in the background?? why won't it work it looks fine to me??
I am new to java/android development so hope someone can fix the issue and explain what I problem was so I can learn something
Yes I got it to stream so far but once you exit the app the music stops playing
For being new think im doing great must be since I have previous experience with PHP etc..
Thanks ;)
package com.beanie.samples.streaming;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import com.beanie.samples.streaming.R;
import com.beanie.samples.streaming.MyService;
import android.app.Activity;
import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;
;
public class HomeActivity extends Activity implements OnClickListener {
private static final String TAG = "MyServices";
private final static String RADIO_STATION_URL = "http://195.154.237.162:8936/";
private static final String START_STICKY = null;
Button buttonPlay, buttonStopPlay;
/** Called when the activity is first created.
* Keep this here all the application will stop working */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
initializeUIElements();
initializeMediaPlayer();
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay.setOnClickListener(this);
}
private ProgressBar playSeekBar;
private MediaPlayer player;
private InputStream recordingStream;
private RecorderThread recorderThread;
private boolean isRecording = false;
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
public void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
public void onClick(View v) {
if (v == buttonPlay) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onClick: starting srvice");
startService(new Intent(this, MyService.class));
startPlaying();
player.setLooping(false); // Set looping
} else if (v == buttonStopPlay) {
Log.d(TAG, "onClick: stopping srvice");
stopService(new Intent(this, MyService.class));
stopPlaying();
}
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
stopRecording();
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource(RADIO_STATION_URL);
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
private void startRecording() {
BufferedOutputStream writer = null;
try {
URL url = new URL(RADIO_STATION_URL);
URLConnection connection = url.openConnection();
final String FOLDER_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()
+ File.separator + "Songs";
File folder = new File(FOLDER_PATH);
if (!folder.exists()) {
folder.mkdir();
}
writer = new BufferedOutputStream(new FileOutputStream(new File(FOLDER_PATH
+ File.separator + "sample.mp3")));
recordingStream = connection.getInputStream();
final int BUFFER_SIZE = 100;
byte[] buffer = new byte[BUFFER_SIZE];
while (recordingStream.read(buffer, 0, BUFFER_SIZE) != -1 && isRecording) {
writer.write(buffer, 0, BUFFER_SIZE);
writer.flush();
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
recordingStream.close();
writer.flush();
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void stopRecording() {
try {
isRecording = false;
if (recordingStream != null) {
recordingStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
private class RecorderThread extends Thread {
#Override
public void run() {
isRecording = true;
startRecording();
}
};
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
well, it is stopping because you're asking it to stop.
When the activity goes to background it pauses.
You should run the stream from a service (that stays in the background without issues) and use a bound service to communicate between activity and service http://developer.android.com/guide/components/bound-services.html

Categories

Resources