Can't load my dll - Windows Mobile Development and Hacking General

It's simple but doesn't work
I made simple dll:
#include <windows.h>
#include "stdafx.h"
HINSTANCE hInst;
BOOL APIENTRY DllMain(HANDLE hModule, DWORD dwReason, LPVOID lpReserved)
{
switch (dwReason)
{
case DLL_PROCESS_ATTACH:
hInst = (HINSTANCE)hModule;
MessageBox(HWND_TOP,L"Hi",L"Hi",MB_OK);
break;
case DLL_PROCESS_DETACH:
;
break;
}
return TRUE;
}
And Simple App
int wmain()
{
HINSTANCE CurModule=NULL;
try
{
CurModule=LoadLibrary(L"\\My.dll");
if(!CurModule)
{
do smth
}
}
catch(...)
{
GetLastError();
}
return 0;
}
But in place - CurModule=LoadLibrary(L"\\My.dll"); CurModul is always "unused"! I can't undastand it?
App and Dll works under WM5
Can you help me?

Related

XDA II - GSM in which Port ?.

Hi,
GoodDay. I am using O2 XDAII, I am want to send some data through GSM. For that I want to know, GSM is situated in Which Port ?.......
So that i can Open the port(COM1 or Com2) and send the some AT commands into it.
or is there any there way to Open the GSM and send data
Kindly Let me know..
Thanks
regards,
Rajesh. S
Over GSM, you have two options; dial-up and GPRS..
None of these uses COM ports in the way that you are thinking..
GSM is located at COM2. But to enable communication with it on XDA2 you'll need to send IOCTL to RIL. Here is a code from one of my test applications.
Code:
#include "stdafx.h"
int HexToInt(char R)
{
if(R>='0' && R<='9')
return R-'0';
if(R>='a' && R<='f')
return R-'a'+10;
if(R>='A' && R<='F')
return R-'A'+10;
return 15;
}
int Hex2ToInt(char *R)
{
return ((HexToInt(R[0])<<4)|HexToInt(R[1]))&255;
}
bool IsHex(char C)
{
if(C>='0' && C<='9')
return true;
if(C>='A' && C<='F')
return true;
return false;
}
int WINAPI WinMain( HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPTSTR lpCmdLine,
int nCmdShow)
{
HANDLE hCom;
char * xpos;
char rsltstr[5];
DWORD CellId;
int bufpos;
DCB dcb;
COMMTIMEOUTS to;
DWORD nWritten;
DWORD event;
DWORD nRead;
static char outbuf[65536], buf[65536];
BYTE comdevcmd[2]= {0x84, 0x00};
FILE *F=fopen("\\Storage Card\\dump.bin","r+bc");
if(F==0)
F=fopen("\\Storage Card\\dump.bin","w+bc");
hCom= CreateFile(L"COM2:",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);
if (hCom==NULL || hCom==INVALID_HANDLE_VALUE)
{
hCom= NULL;
return -1;
}
HANDLE hRil= CreateFile(L"RIL1:",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);
if (hRil==NULL || hRil==INVALID_HANDLE_VALUE)
{
hRil= NULL;
return -1;
}
if (!GetCommState(hCom, &dcb))
{
return -2;
}
dcb.BaudRate= CBR_115200;
dcb.ByteSize= 8;
dcb.fParity= false;
dcb.StopBits= ONESTOPBIT;
if (!SetCommState(hCom, &dcb))
{
return -3;
}
if (!EscapeCommFunction(hCom, SETDTR))
{
return -4;
}
if (!EscapeCommFunction(hCom, SETRTS))
{
// return -5;
}
if (!GetCommTimeouts(hCom, &to))
{
return -6;
}
to.ReadIntervalTimeout= 5;
to.ReadTotalTimeoutConstant= 5;
to.ReadTotalTimeoutMultiplier= 5;
to.WriteTotalTimeoutConstant= 20000;
to.WriteTotalTimeoutMultiplier= 0;
if (!SetCommTimeouts(hCom, &to))
{
return -7;
}
if (!SetCommMask(hCom, EV_RXCHAR))
{
return -8;
}
DWORD rildevresult=0,nReturned=0;
// DeviceIoControl(hRil, 0x03000314L,0,0, &rildevresult, sizeof(DWORD), &nReturned,0);
// HANDLE Ev=CreateEvent(NULL,TRUE,0,L"RILDrv_DataMode");
// SetEvent(Ev);
if (!DeviceIoControl (hCom,0xAAAA5679L, comdevcmd, sizeof(comdevcmd),0,0,0,0))
{
return -9;
}
fseek(F,0,SEEK_END);
DWORD Addr=ftell(F);
Rest:
bufpos = 0;
// strcpy(outbuf,"AT%TEST=D00000000\r");
sprintf(outbuf,"AT%%TEST=D%08X\r",Addr);
to.ReadIntervalTimeout= MAXDWORD;
to.ReadTotalTimeoutConstant= 0;
to.ReadTotalTimeoutMultiplier= 0;
to.WriteTotalTimeoutConstant= 20000;
to.WriteTotalTimeoutMultiplier= 0;
if (!SetCommTimeouts(hCom, &to))
{
return -7;
}
ReadFile(hCom, buf, 65536 , &nRead, NULL);
to.ReadIntervalTimeout= 5;
to.ReadTotalTimeoutConstant= 5;
to.ReadTotalTimeoutMultiplier= 5;
to.WriteTotalTimeoutConstant= 20000;
to.WriteTotalTimeoutMultiplier= 0;
if (!SetCommTimeouts(hCom, &to))
{
return -7;
}
if (!WriteFile(hCom, outbuf, strlen(outbuf), &nWritten, NULL))
{
return -10;
}
if (!WaitCommEvent(hCom, &event, NULL))
{
return -12;
}
ReadFile(hCom, buf, 16*78, &nRead, NULL);
char Buff[256];
for(int i=0; i<16; i++)
{
if(buf[i*78+8]!=':' || buf[i*78+9]!=' ')
goto Rest;
for(int j=0; j<16; j++)
{
if(!IsHex(buf[i*78+10+j*3]))
goto Rest;
if(!IsHex(buf[i*78+10+j*3+1]))
goto Rest;
Buff[i*16+j]=Hex2ToInt(buf+i*78+10+j*3);
}
}
Addr+=256;
// fwrite(buf,1,16*78,F);
fwrite(Buff,1,256,F);
fflush(F);
printf("%08X\r",Addr);
goto Rest;
rildevresult = 0;
DeviceIoControl(hRil, 0x03000318L,0,0, &rildevresult, sizeof(DWORD), &nReturned,0);
// ResetEvent(Ev);
// CloseHandle(Ev);
CloseHandle(hRil);
if (!EscapeCommFunction(hCom, CLRDTR))
{
return -4;
}
if (hCom!=NULL)
{
CloseHandle(hCom);
hCom= NULL;
}
return CellId;
}
Hi,
Good Day.. I got your code..... First of all i convey my thanks to you.
I need some more clarification from your side.
Kindly let me know in details
I am not able understand
Why we need to use RIL & IOCTL Funct?
how your sending "AT" Commands in your Code?( explain to me in details) If i want to add some more AT commands like( AT+CSQ or AT^SCKS?) means how do i add these command and where?...
if you have sample code kindly send to [email protected]
anticipating your reply,
Thanks & regards,
Rajesh. S
Sorry !! Mail ID is : [email protected]
Using COM port GSM access to change outgoing line
Is it possible to alter the outgoing number (read from the SIM card) on the GSM by accessing the COM port?
Is there a utility that already does this? Is there a way of altering settings/phone to be able to change the outgoing number? Or a ROM image that allows you to do this?
I have no understanding whatsoever of the radio stack, so I wouldn't know where to start if I were to write a utility to do so.
Cheers,
Jason
jman said:
Is it possible to alter the outgoing number (read from the SIM card) on the GSM by accessing the COM port?
Is there a utility that already does this? Is there a way of altering settings/phone to be able to change the outgoing number? Or a ROM image that allows you to do this?
I have no understanding whatsoever of the radio stack, so I wouldn't know where to start if I were to write a utility to do so.
Cheers,
Jason
Click to expand...
Click to collapse
@jman,
No that is not possible. The reason is that the phone does not send its caller ID over the air. What happens is that a pseudo random number (called TMSI) is assigned to the mobile phone. The mobile phone sends its TMSI for identification and the MSC (Mobile Switching Centre) does the mapping for the TMSI to calling MSISDN (techno term for mobile phone number).
However, if you are a really good programmer and know your phone internal GSM functioning very well. Then you can spoof the TMSI. Meaning, you should listen to the Paging Messages that are being received on the PCH and get the TMSI from them and then generate a CHAN_REQ based on one of those TMSI. If you want to know more about it, then I suggest that you read a document called GSM04.08 from www.3gpp.org .
Please note that whatever I have written above is valid for a GSM/GPRS/EDGE network only.
Regards,

AT-Commands and missing com port

hi
I've been writing code to access the gsm modem of PPCs and SPs. I found these posts http://forum.xda-developers.com/showthread.php?t=220396 and http://forum.xda-developers.com/showthread.php?t=268809 and this one too http://www.nicecuppa.net/nicetrack.asp to name a few.
here is a sample
Code:
PDACELLID_API long fnGetCell(LPTSTR outData)
{
HANDLE hCom;
char * xpos;
char rsltstr[5];
DWORD CellId;
int bufpos;
DCB dcb;
COMMTIMEOUTS to;
DWORD nWritten;
DWORD event;
DWORD nRead;
char outbuf[20], buf[256];
BYTE comdevcmd[2]= {0x84, 0x00};
hCom= CreateFile(L"COM2:",GENERIC_READ|GENERIC_WRITE,0,0,OPEN_EXISTING,0,0);
if (hCom==NULL || hCom==INVALID_HANDLE_VALUE)
{
hCom= NULL;
return -1;
}
if (!GetCommState(hCom, &dcb))
{
return -2;
}
dcb.BaudRate= CBR_115200;
dcb.ByteSize= 8;
dcb.fParity= false;
dcb.StopBits= ONESTOPBIT;
if (!SetCommState(hCom, &dcb))
{
return -3;
}
if (!EscapeCommFunction(hCom, SETDTR))
{
return -4;
}
if (!GetCommTimeouts(hCom, &to))
{
return -6;
}
to.ReadIntervalTimeout= 0;
to.ReadTotalTimeoutConstant= 200;
to.ReadTotalTimeoutMultiplier= 0;
to.WriteTotalTimeoutConstant= 20000;
to.WriteTotalTimeoutMultiplier= 0;
if (!SetCommTimeouts(hCom, &to))
{
return -7;
}
if (!SetCommMask(hCom, EV_RXCHAR))
{
return -8;
}
if (!DeviceIoControl (hCom,0xAAAA5679L, comdevcmd, sizeof(comdevcmd),0,0,0,0))
{
return -9;
}
bufpos = 0;
strcpy(outbuf,"AT+creg=2\r");
if (!WriteFile(hCom, outbuf, 10, &nWritten, NULL))
{
return -10;
}
if (nWritten != 10)
{
return -11;
}
if (!WaitCommEvent(hCom, &event, NULL))
{
return -12;
}
while(1)
{
if (!ReadFile(hCom, buf+bufpos, 256 - bufpos, &nRead, NULL))
{
return -13;
}
if (nRead == 0)
break;
bufpos += nRead;
if (bufpos >= 256)
break;
}
strcpy(outbuf,"AT+creg?\r");
if (!WriteFile(hCom, outbuf, 9, &nWritten, NULL))
{
return -14;
}
if (nWritten != 9)
{
return -15;
}
if (!WaitCommEvent(hCom, &event, NULL))
{
return -16;
}
while(1)
{
if (!ReadFile(hCom, buf+bufpos, 256 - bufpos, &nRead, NULL))
{
return -17;
}
if (nRead == 0)
break;
bufpos += nRead;
if (bufpos >= 256)
break;
}
buf[bufpos] = 0;
mbstowcs(outData,buf,bufpos+1);
if ((xpos = strstr(buf,"CREG")) == NULL)
{
CellId = -19;
}
else
{
memcpy(rsltstr,xpos+18,4);
rsltstr[4] = 0;
if (sscanf(rsltstr,"%X",&CellId) != 1)
{
CellId = -20;
}
}
if (hCom!=NULL)
{
CloseHandle(hCom);
hCom= NULL;
}
return CellId;
}
Some of these posts assume that I already know the com port of the gsm modem, Others tell you to get the com port handle by either:
1- TAPI's lineGetID - which only gets a valid handle if I originate a voice call (not data call). In my case I only query information from the network so I don't need to make a voice call and that is why I'll never get a com port handle.
2- Silent the RIL and open the com port manually as in here
http://forum.xda-developers.com/showpost.php?p=963262&postcount=1
which apparetnly turns on the flight mode and shuts down the phone on WM2005.
3- I tried to detect the right com port using the registry key HKLM\Drivers\BuiltIn\Serial which doesn't give the right result on every device.
In the HTC universal (i-mate jasjar) there is no "known" way to open the GSM com port. Even nicetrack couldn't detect the gsm modem port.
There is definitely a way to get the com port handle but it may involve reverse engineering which i'm not good at. I leave that to the pros

problem with injection DLL to specified process

Save me from madness!!!
I have a several smartphone devices with windows CE
CE 6.0 - hp IPAQ 500 series
CE 5.0 - Samsung i600
I need to inject DLL into the process "home.exe". I use method with performcallback4 function. This method works successfully for all processes ("device.exe", "service.exe", etc.) except process "home.exe". In what a problem?
source code : InjectDLL.exe link with toolhelp.lib
#include <windows.h>
#include <Tlhelp32.h>
typedef struct _CALLBACKINFO {
HANDLE hProc;
FARPROC pfn;
PVOID pvArg0;
} CALLBACKINFO;
extern "C"
{
DWORD PerformCallBack4(CALLBACKINFO *pcbi,...);
LPVOID MapPtrToProcess(LPVOID lpv, HANDLE hProc);
BOOL SetKMode(BOOL fMode);
DWORD SetProcPermissions(DWORD newperms);
};
DWORD GetProcessId(WCHAR *wszProcessName)
{
HANDLE hTH= CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe;
pe.dwSize= sizeof(PROCESSENTRY32);
DWORD PID=0;
if (Process32First(hTH, &pe))
{
do {
if (wcsicmp(wszProcessName, pe.szExeFile)==0)
{
PID=pe.th32ProcessID;
}
} while (Process32Next(hTH, &pe));
}
CloseToolhelp32Snapshot(hTH);
return PID;
}
HMODULE GetDllHandle(DWORD ProcessId,WCHAR* ModuleName)
{
HANDLE ToolHelp=CreateToolhelp32Snapshot(TH32CS_SNAPMODULE,ProcessId);
if (ToolHelp!=INVALID_HANDLE_VALUE)
{
MODULEENTRY32 ModuleEntry={sizeof MODULEENTRY32};
if (Module32First(ToolHelp,&ModuleEntry))
do
{
if (wcsicmp(ModuleEntry.szModule, ModuleName)==0)
return ModuleEntry.hModule;
}
while(Module32Next(ToolHelp,&ModuleEntry));
CloseToolhelp32Snapshot(ToolHelp);
}
return NULL;
}
BOOL InjectDll(WCHAR* ProcessName,WCHAR* ModuleName)
{
DWORD ProcessId=GetProcessId(ProcessName);
HMODULE ModuleHandle=GetDllHandle(ProcessId,ModuleName);
if (ModuleHandle!=NULL)
return TRUE;
HANDLE Process=OpenProcess(0,0,ProcessId);
if (Process==NULL)
return FALSE;
void* ModuleNamePtr=MapPtrToProcess(ModuleName,GetCurrentProcess());
if (ModuleNamePtr==NULL)
return FALSE;
CALLBACKINFO ci;
ci.hProc=Process;
void* LoadLibraryPtr=MapPtrToProcess(GetProcAddress(GetModuleHandle(L"coredll.dll"),L"LoadLibraryW"),Process);
if (LoadLibraryPtr==NULL)
return FALSE;
ci.pfn=(FARPROC)LoadLibraryPtr;
ci.pvArg0=ModuleNamePtr;
PerformCallBack4(&ci); in this place process exit. visual studio output message : "process exit with code 0xc0000030"
Sleep(500);
CloseHandle(Process);
return GetDllHandle(ProcessId,ModuleName)!=NULL;
}
extern "C"
{
BOOL SetKMode(BOOL fMode);
DWORD SetProcPermissions(DWORD newperms);
};
#define DLLNAME L"MyDll.dll"
int WINAPI WinMain(HINSTANCE hInstance,HINSTANCE hPrevInstance,LPWSTR lpCmdLine,int nShowCmd)
{
WCHAR Path[MAX_PATH];
GetModuleFileName(NULL,Path,MAX_PATH);
wcscpy(wcsrchr(Path,L'\\')+1,DLLNAME);
WCHAR NewPath[MAX_PATH]=L"\\Windows\\";
wcscat(NewPath,DLLNAME);
CopyFile(Path,NewPath,FALSE);
BOOL Res=InjectDll(L"home.exe",L"MyDll.dll");
return 0;
}
the error code is
#define STATUS_INVALID_PARAMETER_MIX 0xC0000030
(maybe too fast for getting the thread infos?)
try to make the "Sleep(500);" before "PerformCallBack4(&ci);"
I have tried, a problem not in it. Any ideas?
I have not found the reason.... I Use other method without performcallback4
Problem with injection dll to cprog.exe process?
I want to inject dll to cprog.exe process. but it doesn't work.
source code.
Code:
VOID
InjectDllToCprog()
{
WCHAR DllPath[MAX_PATH] = L"";
CallbackInfo ci;
GetModuleFileName(NULL, DllPath, MAX_PATH);
PWCHAR p = wcsrchr(DllPath, L'\\');
DllPath[p - DllPath] = '\0';
wcscat(DllPath, L"\\CprogInject.dll");
ZeroMemory(&ci, sizeof(ci));
g_hCprog = FindCprogProcess(L"Cprog.exe"); // the handle is right.
if(g_hCprog != NULL)
{
DWORD dwMode = SetKMode(TRUE);
DWORD dwPerm = SetProcPermissions(0xFFFFFFFF);
FARPROC pFunc = GetProcAddress(GetModuleHandle(L"Coredll.dll"), L"LoadLibraryW");
ci.ProcId = (HANDLE)g_hCprog;
ci.pFunc = (FARPROC)MapPtrToProcess(pFunc, g_hCprog);
ci.pvArg0 = MapPtrToProcess(DllPath, GetCurrentProcess());
g_InjectCprog = (HINSTANCE)PerformCallBack4(&ci, 0, 0, 0);
if(GetLastError() != 0) // GetLastError() = 5
DbgError(L"PerformCallBack 执行失败", GetLastError());
SetKMode(dwMode);
SetProcPermissions(dwPerm);
}
}
GetLastError() return 0x00000005(Access is denied)
Anyone can help me? Sorry for my poor english.

Retrieving cpu frequency

Hi everyone.
I want to retrieve the current cpu frequency in my app but I don't seem to be right.
In my code I want to read the "scaling_cpu_freq" file from internal storage.
This is the code:
Code:
private String ReadCPUMhz() {
String cpuMaxFreq = "";
int cur = 0;
try {
[user=1299008]@supp[/user]ressWarnings("resource")
BufferedReader maxi = new BufferedReader(new FileReader(new File("/sys/devices/system/cpu/cpu0/cpufreq/scaling_max_freq")));
try{
cpuMaxFreq = maxi.readLine();
cur = Integer.parseInt(cpuMaxFreq);
cur = cur/1000;
} catch (Exception ex){
ex.printStackTrace();
}
} catch (FileNotFoundException f) {
f.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return String.valueOf(cur);
}
The problem is that the method only returns 0, which is the initial value of the int "cur".
Can anybody help me?
Thanks in advance.
Here's the code I use:
Declare this class in your Activity
Code:
// Read current frequency from /sys in a separate thread
// This class assumes your TextView is declared and referenced in the OnCreate of the class this one is declared in
// And its variable name is mCurCpuFreq
protected class CurCPUThread extends Thread {
private static final String CURRENT_CPU = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq";
private boolean mInterrupt = false;
public void interrupt() {
mInterrupt = true;
}
[user=439709]@override[/user]
public void run() {
try {
while (!mInterrupt) {
sleep(400);
final String curFreq = readOneLine(CURRENT_CPU);
mCurCPUHandler.sendMessage(mCurCPUHandler.obtainMessage(0,
curFreq));
}
} catch (InterruptedException e) {
return;
}
}
}
// Update real-time current frequency & stats in a separate thread
protected static Handler mCurCPUHandler = new Handler() {
public void handleMessage(Message msg) {
mCurFreq.setText(toMHz((String) msg.obj));
final int p = Integer.parseInt((String) msg.obj);
new Thread(new Runnable() {
public void run() {
// Here I update a real-time graph of the current freq
}
}
}).start();
}
};
Helper methods used :
Code:
// Convert raw collected values to formatted MhZ
private static String toMHz(String mhzString) {
if (Integer.valueOf(mhzString) != null)
return String.valueOf(Integer.valueOf(mhzString) / 1000) + " MHz";
else
return "NaN";
}
// Iterate through the /sys file
public static String readOneLine(String fname) {
BufferedReader br;
String line = null;
try {
br = new BufferedReader(new FileReader(fname), 512);
try {
line = br.readLine();
} finally {
br.close();
}
} catch (Exception e) {
Log.e(TAG, "IO Exception when reading sys file", e);
// attempt to do magic!
return readFileViaShell(fname, true);
}
return line;
}
// Backup method if the above one fails
public static String readFileViaShell(String filePath, boolean useSu) {
CommandResult cr = null;
if (useSu) {
cr = new CMDProcessor().runSuCommand("cat " + filePath);
} else {
cr = new CMDProcessor().runShellCommand("cat " + filePath);
}
if (cr.success())
return cr.getStdout();
return null;
}
CMDProcessor.java and its dependencies attached to this post

Camera2 focus state during preview

Hi,
I have built a small notepad+barcodescanner app. Not it works, but the performance is low, as it processes all frames. It would be good if it would process only frams which are captured when the focus settled.
The app uses Camera2 PreviewBulder and CaptureRequestBuilder / RepeatingRequest, but i only found ways to get focus state during a Capturesession. (Capture is not used in this app, only getting frames from preview).
Does anyone how to process the focus state if one uses a Preview...?
Thanks for any help
Corresponding code part:
private final CameraDevice.StateCallback stateCallback = new
CameraDevice.StateCallback() {
@override
public void onOpened(CameraDevice camera) {
//This is called when the camera is open
// Log.e(TAG, "onOpened");
cameraDevice = camera;
createCameraPreview();
}
@override
public void onDisconnected(CameraDevice camera) {
cameraDevice.close();
}
@override
public void onError(CameraDevice camera, int error) {
cameraDevice.close();
cameraDevice = null;
}
};
final CameraCaptureSession.CaptureCallback captureCallbackListener = new CameraCaptureSession.CaptureCallback() {
@override
public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
// makeText(MainActivity.this, "Saved:" + file, LENGTH_SHORT).show();
createCameraPreview();
}
};
protected void startBackgroundThread() {
mBackgroundThread = new HandlerThread("Camera Background");
mBackgroundThread.start();
mBackgroundHandler = new Handler(mBackgroundThread.getLooper());
}
protected void stopBackgroundThread() {
mBackgroundThread.quitSafely();
try {
mBackgroundThread.join();
mBackgroundThread = null;
mBackgroundHandler = null;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
protected void createCameraPreview() {
try {
SurfaceTexture texture = textureView.getSurfaceTexture();
assert texture != null;
texture.setDefaultBufferSize(imageDimension.getWidth(),
imageDimension.getHeight());
Surface surface = new Surface(texture);
CameraManager manager;
manager = (CameraManager) getSystemService(Context.CAMERA_SERVICE);
try {
String camerId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics = manager.getCameraCharacteristics(camerId);
boolean aelockavailable = characteristics.get(CameraCharacteristics.CONTROL_AE_LOCK_AVAILABLE);
}catch (Exception e)
{
}
captureRequestBuilder = cameraDevice.createCaptureRequest(CameraDevice.TEMPLATE_PREVIEW);
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, captureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
//captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, captureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
captureRequestBuilder.addTarget(surface);
cameraDevice.createCaptureSession(Arrays.asList(surface),
new CameraCaptureSession.StateCallback() {
@override
public void onConfigured(@NonNull CameraCaptureSession
cameraCaptureSession) {
//The camera is already closed
if (null == cameraDevice) {
return;
}
// When the session is ready, we start displaying the preview.
cameraCaptureSessions = cameraCaptureSession;
updatePreview();
}
@override
public void onConfigureFailed(@NonNull
CameraCaptureSession cameraCaptureSession) {
//makeText(MainActivity.this, "Configuration change", LENGTH_SHORT).show();
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
void openCamera() {
CameraManager manager = (CameraManager)
getSystemService(Context.CAMERA_SERVICE);
//Log.e(TAG, "is camera open");
try {
cameraId = manager.getCameraIdList()[0];
CameraCharacteristics characteristics =
manager.getCameraCharacteristics(cameraId);
StreamConfigurationMap map =
characteristics.get(CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
assert map != null;
imageDimension = map.getOutputSizes(SurfaceTexture.class)[0];
// Add permission for camera and let user grant the permission
if (ActivityCompat.checkSelfPermission(this,
Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this,
Manifest.permission.WRITE_EXTERNAL_STORAGE) !=
PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(MainActivity.this,
new String[]{Manifest.permission.CAMERA,
Manifest.permission.WRITE_EXTERNAL_STORAGE},
REQUEST_CAMERA_PERMISSION);
return;
}
manager.openCamera(cameraId, stateCallback, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
//Log.e(TAG, "openCamera X");
}
void updatePreview() {
if (null == cameraDevice) {
//Log.e(TAG, "updatePreview error, return");
}
captureRequestBuilder.set(CaptureRequest.CONTROL_MODE, CameraMetadata.CONTROL_MODE_AUTO);
captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, captureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
//captureRequestBuilder.set(CaptureRequest.CONTROL_AF_MODE, CaptureRequest.CONTROL_AF_MODE_CONTINUOUS_PICTURE);
if (flashchanged) {flashchanged=false; if (lamp && autoflash) {captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_TORCH);} else {captureRequestBuilder.set(CaptureRequest.FLASH_MODE, CaptureRequest.FLASH_MODE_OFF);} }
try {
cameraCaptureSessions.setRepeatingRequest(captureRequestBuilder.build(),
null, mBackgroundHandler);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
private void closeCamera() {
if (null != cameraDevice) {
cameraDevice.close();
cameraDevice = null;
}
if (null != imageReader) {
imageReader.close();
imageReader = null;
}
}

Categories

Resources