Problem with "getScanResults()" - Android Q&A, Help & Troubleshooting

Hi,
I´ve a big problem with the "getScanResults()" function. I always get "0" as result.
Here is my Code (it´s a service):
Code:
public void onCreate() {
super.onCreate();
wifiMgr = (WifiManager)getSystemService(Context.WIFI_SERVICE);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
intentScan = new IntentFilter();
intentScan.addAction(WifiManager.SCAN_RESULTS_AVAILABLE_ACTION);
scanReceiver = new ScanReceiver();
screenOnReceiver = new ScreenOnReceiver();
registerReceiver(screenOnReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
screenOffReceiver = new ScreenOffReceiver();
registerReceiver(screenOffReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));
}
[user=439709]@override[/user]
public void onDestroy () {
unregisterReceiver(screenOnReceiver);
unregisterReceiver(screenOffReceiver);
}
[user=439709]@override[/user]
public void onStart(Intent intent, int startId) {
wifiMgr = (WifiManager)getSystemService(Context.WIFI_SERVICE);
registerReceiver(scanReceiver, intentScan);
showToasts = sharedPreferences.getBoolean("checkbox_notification", true);
autoSync = sharedPreferences.getBoolean("checkbox_autosync", true);
if(wifiMgr.getConnectionInfo().getNetworkId() == -1) {
if(wifiMgr.setWifiEnabled(true)) {
if(!wifiMgr.startScan()){
unregisterReceiver(scanReceiver);
}
}
}else{
if(showToasts)
Toast.makeText(this.getApplicationContext(),R.string.toast_nochange, Toast.LENGTH_SHORT).show();
}
}
public class ScanReceiver extends BroadcastReceiver {
[user=439709]@override[/user]
public void onReceive(Context context, Intent intent) {
Log.d("wifi", "ScanComplete - "+intent.getAction());
List<WifiConfiguration> wifiListSupplicant = wifiMgr.getConfiguredNetworks();
List<ScanResult> wifiListScan = wifiMgr.getScanResults();
Log.d("wifi", "LIST: "+wifiListScan.size());
} }
Somebody an idea?
Thanks"

Related

[Q] Android Maps draw path problem

I am developing an application which draws the path of the user as he moves and calculates the area .
This is the code i am trying my problem is at the start of recording the path the path is drawn even if the user has not moved and sometimes when even if user is moving the path is not drawn .
RouteOverlay class:
public class RouteOverlay extends Overlay {
private GeoPoint gp1;
private GeoPoint gp2;
private int mode = 1;
public RouteOverlay(GeoPoint paramGeoPoint1, GeoPoint paramGeoPoint2,int paramInt)
{
this.gp1 = paramGeoPoint1;
this.gp2 = paramGeoPoint2;
this.mode = paramInt;
}
public void draw(Canvas paramCanvas, MapView paramMapView,
boolean paramShadow)
{
super.draw(paramCanvas, paramMapView, paramShadow);
Projection projection = paramMapView.getProjection();
Paint mPaint = new Paint();
mPaint.setDither(true);
mPaint.setAntiAlias(true);
mPaint.setColor(Color.RED);
mPaint.setStyle(Paint.Style.FILL_AND_STROKE);
mPaint.setStrokeJoin(Paint.Join.ROUND);
mPaint.setStrokeCap(Paint.Cap.ROUND);
mPaint.setStrokeWidth(3);
mPaint.setAlpha(120);
Point p1 = new Point();
Point p2 = new Point();
Path path = new Path();
projection.toPixels(gp1, p1);
projection.toPixels(gp2, p2);
path.moveTo(p2.x,p2.y);
path.lineTo(p1.x,p1.y);
paramCanvas.drawPath(path, mPaint);
}
MainActivity:
public class MainActivity extends MapActivity {
public final LocationListener locationListener = new LocationListener() {
public void onLocationChanged(Location location) {
coordinates.add(location);
mapView.getController().animateTo(getGeoByLocation(location));
drawRoute(coordinates, mapView);
}
};
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_area_measurement);
this.mapView = ((MapView) findViewById(R.id.mapview));
this.mapView.setBuiltInZoomControls(false);
this.mapView.getController().setZoom(17);
this.coordinates = new ArrayList<Location>();
}
protected boolean isRouteDisplayed() {
return false;
}
private GeoPoint getGeoByLocation(Location location) {
GeoPoint gp = null;
try {
if (location != null) {
double geoLatitude = location.getLatitude() * 1E6;
double geoLongitude = location.getLongitude() * 1E6;
gp = new GeoPoint((int) geoLatitude, (int) geoLongitude);
}
} catch (Exception e) {
e.printStackTrace();
}
return gp;
}
public String getLocationProvider(LocationManager paramLocationManager) {
try {
Criteria localCriteria = new Criteria();
localCriteria.setAccuracy(1);
localCriteria.setAltitudeRequired(false);
localCriteria.setBearingRequired(false);
localCriteria.setCostAllowed(true);
localCriteria.setPowerRequirement(3);
String str = paramLocationManager.getBestProvider(localCriteria,
true);
return str;
} catch (Exception localException) {
while (true) {
localException.printStackTrace();
}
}
}
private void drawRoute(ArrayList<Location> paramArrayList,MapView paramMapView) {
List<Overlay> overlays = paramMapView.getOverlays();
//Changed for smooth rendering
overlays.clear();
for (int i = 1; i < paramArrayList.size(); i++) {
overlays.add(new RouteOverlay(getGeoByLocation(paramArrayList.get(i - 1)), getGeoByLocation(paramArrayList.get(i)),2));
}
}
public void startRecording() {
this.isMeasuring = true;
lm = (LocationManager) getSystemService(LOCATION_SERVICE);
lm.requestLocationUpdates(getLocationProvider(lm),500,2,this.locationListener);
/*if (lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER)){
gpsstatus.setText("Gps Is Enabled");
}else
{ gpsstatus.setText("Gps Is disabled");}*/
}
This probably has to do with the accuracy of the GPS. I didn't really look at your code but maybe you should add some kind of buffer. if (movement>5m){//draw stuff}

Help in android app developing

Please Can Someone help me to get hands on the error in this source code for 2 subjects gpa calculator as it is giving me Force Close
Here`s the source code
"
package com.gado.e001;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.Toast;
public class MainActivity extends Activity {
RadioButton gradea1, gradeb1, gradec1, graded1, gradea2, gradeb2, gradec2,
graded2;
EditText hours1, hours2;
Button calc;
float fgrade1, fgrade2, fhours1, fhours2;
float Result = fgrade1 + fgrade2 + fhours1 + fhours2;
public void Identify() {
gradea1 = (RadioButton) findViewById(R.id.radioButton1);
gradeb1 = (RadioButton) findViewById(R.id.radioButton2);
gradec1 = (RadioButton) findViewById(R.id.radioButton3);
graded1 = (RadioButton) findViewById(R.id.radioButton4);
gradea2 = (RadioButton) findViewById(R.id.radioButton5);
gradeb2 = (RadioButton) findViewById(R.id.radioButton6);
gradec2 = (RadioButton) findViewById(R.id.radioButton7);
graded2 = (RadioButton) findViewById(R.id.radioButton8);
hours1 = (EditText) findViewById(R.id.editText1);
hours2 = (EditText) findViewById(R.id.editText2);
calc = (Button) findViewById(R.id.button1);
}
public void getting() {
gradea1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade1 = 4f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
gradeb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade1 = 3f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
gradec1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade1 = 2f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
graded1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade1 = 1f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
gradea2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade2 = 4f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
gradeb2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade2 = 3f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
gradec2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade2 = 2f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
graded2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
@Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
if (isChecked) {
fgrade2 = 1f;
}
else{
Toast.makeText(getBaseContext(), "", Toast.LENGTH_SHORT).show();
}
}
});
fhours1 = Float.parseFloat(hours1.getText().toString());
fhours2 = Float.parseFloat(hours2.getText().toString());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
calc.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Identify();
getting();
Toast.makeText(getBaseContext(), "" + Result, Toast.LENGTH_LONG)
.show();
}
});
}
}
"
Please Help Me
You might be better off asking this question on Stackoverflow.
Run your app with your phone connected to your PC and Eclipse running, this way Eclipse will show you the error so you can tell us what is it.

[Q] Options menu problem

I'm trying to get a working option menu, and I can get it to work with any activity i got in my app, but not the Main one. that's mean, whenever i try to access the main activity from the option menu, i get an error. here is the main activity, maybe it'll help:
public class Main extends Activity {
private ContentResolver cResolver;
private Window window;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
loadPrefsBrightness();
SharedPreferences sp1 = getSharedPreferences("ButtonData", MODE_PRIVATE);
boolean cbValue = sp1.getBoolean("ButtonData", false);
if(cbValue){
Music.play(this, R.raw.japanese_garden);
Music.stoping();
}else{
Music.play(this, R.raw.japanese_garden);
}
SharedPreferences sp3 = getSharedPreferences("SleepData", MODE_PRIVATE);
boolean cbValue2 = sp3.getBoolean("SleepData", false);
if(cbValue2){
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}else{
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
}
}
public void loadPrefsBrightness() {
SharedPreferences sp2 = getSharedPreferences("BrightnessData", MODE_PRIVATE);
int bnessValue = sp2.getInt("BrightnessData", 150);
cResolver = getContentResolver();
window = getWindow();
android.provider.Settings.System.putInt(cResolver, android.provider.Settings.System.SCREEN_BRIGHTNESS, bnessValue);
LayoutParams layoutpars = window.getAttributes();
layoutpars.screenBrightness = bnessValue / (float)255;
window.setAttributes(layoutpars);
}
public void setting_onclick(View view) {
Intent i = new Intent("net.lirazarviv.Setting");
startActivity(i);
}
public void free_search_onclick(View view) {
Intent i = new Intent("net.lirazarviv.FreeSearch");
startActivity(i);
}
public void search_by_type_onclick(View view) {
Intent i = new Intent("net.lirazarviv.SearchByType");
startActivity(i);
}
public void search_by_difficulty_onclick(View view) {
Intent i = new Intent("net.lirazarviv.SearchByDifficulty");
startActivity(i);
}
public void info_onclick(View view) {
Intent i = new Intent("net.lirazarviv.Info");
startActivity(i);
}
@override
protected void onPause() {
if (this.isFinishing()){ //basically BACK was pressed from this activity
Music.stop();
}
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfo = am.getRunningTasks(1);
if (!taskInfo.isEmpty()) {
ComponentName topActivity = taskInfo.get(0).topActivity;
if (!topActivity.getPackageName().equals(context.getPackageName())) {
Music.stop();
}
}
super.onPause();
}
}
Why not post the logcat of eclipse? It will help to track down the bug easier
Sent from my GT-N7000 using xda app-developers app

Help for Avin App or Auxiliary in

I have a problem that my monkeyboard Dab receiver needs audio in. This can be switched with the avin app. But I only need the Audio switched not the video. Is it possible to make a Task with Tasker or similar to run some code or script to switch the audio.
Because also after boot the avin app is blocking the system. For example pppwidget starts only after exiting the avin app.
I also did take a look at the code of the app but I am a completely noob at java app programming and could not identify the code for switching the audio.
Can anyone understand and help me please?
Thanks
I am on malaysk kitkat rom.
here is the code i could decompile. Maybe it is useful for my Problem
MTCAVIN.apk com microntek avin AVINActivity.java
package com.microntek.avin;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.Settings.System;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager.LayoutParams;
import android.widget.ImageView;
public class AVINActivity extends Activity {
private static boolean activityVisible;
private static boolean statusbarshow;
private static boolean videoEnable;
private BroadcastReceiver AVINBootReceiver;
private final int MSG_CAPTURE_OFF;
private final int MSG_CAPTURE_ON;
private final int MSG_TIME_TICK;
private final int MSG_VIDEO_CHECK;
private AudioManager am;
private Handler mHandler;
private ImageView mImageBlack;
private ImageView mImageScreen;
private boolean mInChannel;
private boolean mIsSignal;
private View mTextWarning;
private View signalshow;
private int startbackflag;
private int statusbarhidetime;
/* renamed from: com.microntek.avin.AVINActivity.1 */
class C00001 extends Handler {
C00001() {
}
public void handleMessage(Message msg) {
super.handleMessage(msg);
switch (msg.what) {
case 65281:
AVINActivity.this.captureOn();
case 65282:
AVINActivity.this.captureOff();
case 65283:
AVINActivity.this.videoCheck();
case 65284:
AVINActivity.this.refresTick();
AVINActivity.this.mHandler.sendEmptyMessageDelayed(65284, 1000);
default:
}
}
}
/* renamed from: com.microntek.avin.AVINActivity.2 */
class C00012 implements OnClickListener {
C00012() {
}
public void onClick(View v) {
if (!AVINActivity.statusbarshow) {
AVINActivity.statusbarshow = true;
AVINActivity.this.mHandler.removeMessages(65284);
AVINActivity.this.mHandler.sendEmptyMessageDelayed(65284, 1000);
AVINActivity.this.statusbarhidetime = 0;
AVINActivity.this.resumeStatusBar();
} else if (AVINActivity.this.mIsSignal && AVINActivity.videoEnable) {
AVINActivity.statusbarshow = false;
AVINActivity.this.hideStatusBar();
}
}
}
/* renamed from: com.microntek.avin.AVINActivity.3 */
class C00023 extends BroadcastReceiver {
C00023() {
}
public void onReceive(Context arg0, Intent arg1) {
String action = arg1.getAction();
if (action.equals("com.microntek.bootcheck")) {
String classname = arg1.getStringExtra("class");
if (!classname.equals("com.microntek.avin") && !classname.equals("phonecallin") && !classname.equals("phonecallout")) {
AVINActivity.this.sendFinish();
}
} else if (action.equals("com.microntek.carstatechange")) {
if (AVINActivity.activityVisible && arg1.getStringExtra("type").equals("SAFE")) {
AVINActivity.videoEnable = AVINActivity.this.GetDrivingVideoEnable();
AVINActivity.this.mHandler.removeMessages(65283);
AVINActivity.this.mHandler.sendEmptyMessageDelayed(65283, 100);
}
} else if (action.equals("com.microntek.videosignalchange") && arg1.getStringExtra("type").equals("avin")) {
AVINActivity.this.mIsSignal = arg1.getBooleanExtra("sta", true);
AVINActivity.videoEnable = AVINActivity.this.GetDrivingVideoEnable();
AVINActivity.this.mHandler.removeMessages(65283);
AVINActivity.this.mHandler.sendEmptyMessageDelayed(65283, 100);
}
}
}
public AVINActivity() {
this.MSG_CAPTURE_ON = 65281;
this.MSG_CAPTURE_OFF = 65282;
this.MSG_VIDEO_CHECK = 65283;
this.MSG_TIME_TICK = 65284;
this.mImageBlack = null;
this.mTextWarning = null;
this.signalshow = null;
this.mImageScreen = null;
this.mIsSignal = true;
this.startbackflag = 0;
this.statusbarhidetime = 0;
this.am = null;
this.mInChannel = false;
this.mHandler = new C00001();
this.AVINBootReceiver = new C00023();
}
static {
videoEnable = false;
activityVisible = false;
statusbarshow = true;
}
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.startbackflag = getIntent().getIntExtra("start", 0);
if (this.startbackflag != 0) {
moveTaskToBack(true);
}
Intent it1 = new Intent("com.microntek.bootcheck");
it1.putExtra("class", "com.microntek.avin");
sendBroadcast(it1);
this.am = (AudioManager) getSystemService("audio");
this.statusbarhidetime = 0;
setContentView(R.layout.main);
this.signalshow = findViewById(R.id.signalshow);
this.mImageScreen = (ImageView) findViewById(R.id.screen);
this.mImageScreen.setOnClickListener(new C00012());
this.mImageBlack = (ImageView) findViewById(R.id.black);
this.mTextWarning = findViewById(R.id.safewarning);
IntentFilter itfl = new IntentFilter();
itfl.addAction("com.microntek.bootcheck");
itfl.addAction("com.microntek.carstatechange");
itfl.addAction("com.microntek.videosignalchange");
registerReceiver(this.AVINBootReceiver, itfl);
deviceOn();
sendCanBusAvinOn();
this.mHandler.sendEmptyMessageDelayed(65284, 1000);
}
private void sendFinish() {
deviceOff();
finish();
}
private void deviceOn() {
if (!this.mInChannel) {
this.am.setParameters("av_channel_enter=line");
this.mInChannel = true;
}
}
private void deviceOff() {
if (this.mInChannel) {
this.mInChannel = false;
this.am.setParameters("av_channel_exit=line");
}
}
private void sendCanBusAvinOn() {
Intent it1 = new Intent("com.microntek.canbusdisplay");
it1.putExtra("type", "avin-on");
sendBroadcast(it1);
}
private void sendCanBusAvinOff() {
Intent it1 = new Intent("com.microntek.canbusdisplay");
it1.putExtra("type", "avin-off");
sendBroadcast(it1);
}
public void onBackPressed() {
sendFinish();
}
private void refresTick() {
if (!this.mIsSignal) {
boolean en = GetDrivingVideoEnable();
if (videoEnable != en) {
videoEnable = en;
this.mHandler.removeMessages(65283);
this.mHandler.sendEmptyMessageDelayed(65283, 100);
}
}
if (this.statusbarhidetime < 10) {
this.statusbarhidetime++;
if (this.statusbarhidetime == 10 && videoEnable && statusbarshow) {
statusbarshow = false;
hideStatusBar();
}
}
}
private boolean GetDrivingVideoEnable() {
if (System.getInt(getContentResolver(), "DrivingVideoEN", 0) != 0) {
return true;
}
if (this.am.getParameters("sta_driving=").equals("true")) {
return false;
}
return true;
}
public void hideStatusBar() {
if (this.mIsSignal) {
Window win = getWindow();
LayoutParams winParams = win.getAttributes();
winParams.flags |= 1024;
win.setAttributes(winParams);
}
}
public void resumeStatusBar() {
Window win = getWindow();
LayoutParams winParams = win.getAttributes();
winParams.flags &= -1025;
win.setAttributes(winParams);
}
protected void onResume() {
super.onResume();
statusbarshow = true;
activityVisible = true;
resumeStatusBar();
captureOn();
videoEnable = GetDrivingVideoEnable();
this.mHandler.sendEmptyMessageDelayed(65283, 100);
sendBroadcast(new Intent("com.microntek.musicclockreset"));
}
protected void onPause() {
activityVisible = false;
captureOff();
super.onPause();
}
protected void onDestroy() {
this.mHandler.removeCallbacksAndMessages(null);
unregisterReceiver(this.AVINBootReceiver);
deviceOff();
sendCanBusAvinOff();
super.onDestroy();
}
protected void videoCheck() {
if (videoEnable) {
this.mTextWarning.setVisibility(4);
} else {
this.mTextWarning.setVisibility(0);
}
if (this.mIsSignal) {
this.signalshow.setVisibility(8);
return;
}
this.signalshow.setVisibility(0);
this.statusbarhidetime = 0;
if (!statusbarshow) {
resumeStatusBar();
}
statusbarshow = true;
}
protected void captureOn() {
this.am.setParameters("ctl_capture_on=line");
this.mImageBlack.setVisibility(4);
}
protected void captureOff() {
this.mImageBlack.setVisibility(0);
this.am.setParameters("ctl_capture_off=line");
}
}
Privacy Policy
Maybe simple shell command or something? Anyone?
I did a simple Tweak in the Avin app. Now it launches without Ui. For audio in only and only for kitkat roms.
I have a typo in the attached APK...
Hey there, sorry to disturb the old thread I need avin.apk only to show video input, and not cut audio in background for Spotify. Do you think I have a chance?
I suppose It is the direct oppossite of yours.
ivellios said:
Hey there, sorry to disturb the old thread I need avin.apk only to show video input, and not cut audio in background for Spotify. Do you think I have a chance?
I suppose It is the direct oppossite of yours.
Click to expand...
Click to collapse
2nd - if you're still around - can you recompile with this ?
Might be as simple as commenting out the this.am.setParameters calls
Sorry, this is not possible for me. I did not figure it out how to disable the video.

Camera2 API running in background service

Hello everybody
Unfortunately, I have too few post to make a thread in the " Android Software Development" forum. I would be very happy if this post can be moved to it.
I have used the Camera2 API to implement a background video recorder running as a service and recording from the front cam. For this I have created a new SurfaceView, set its size to 1x1 and moved it to the top left corner. My code is shown below. I'm using Android 5.1.
With the Camera API it worked very well but unfortunately the frame rate is only at 20 fps (and when I increase the exposure compensation it drops even more), although with the Open Camera app I have 30 fps also with increased exposure compensation. That is why I want to try Camera2 API (hoping to get higher fps). Unfortunately, I'm getting the following error:
MediaRecoder: setOutputFile called in an invalid state(2)
MediaRecorder: start called in an invalid state: 2
Click to expand...
Click to collapse
Here is my code:
Code:
public class RecorderServiceCamera2 extends Service implements SurfaceHolder.Callback {
private WindowManager windowManager;
private SurfaceView surfaceView;
private CameraDevice mCamera;
private MediaRecorder mediaRecorder = null;
private CaptureRequest mCaptureRequest;
private CameraCaptureSession mSession;
@Override
public void onCreate() {
// Create new SurfaceView, set its size to 1x1, move it to the top left corner and set this service as a callback
windowManager = (WindowManager) this.getSystemService(Context.WINDOW_SERVICE);
surfaceView = new SurfaceView(this);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
1, 1,
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT
);
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
windowManager.addView(surfaceView, layoutParams);
surfaceView.getHolder().addCallback(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, 0);
Notification notification = new NotificationCompat.Builder(this)
//.setSmallIcon(R.mipmap.app_icon)
.setContentTitle("Background Video Recorder")
.setContentText("")
.setContentIntent(pendingIntent).build();
startForeground(MainActivity.NOTIFICATION_ID_RECORDER_SERVICE, notification);
return Service.START_NOT_STICKY;
}
@Override
public void surfaceCreated(final SurfaceHolder surfaceHolder) {
mediaRecorder = new MediaRecorder();
try {
CameraManager manager = (CameraManager) getSystemService(CAMERA_SERVICE);
String[] cameras = manager.getCameraIdList();
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameras[1]);
StreamConfigurationMap configs = characteristics.get(
CameraCharacteristics.SCALER_STREAM_CONFIGURATION_MAP);
Size[] sizes = configs.getOutputSizes(MediaCodec.class);
final Size sizeHigh = sizes[0];
manager.openCamera(cameras[1], new CameraDevice.StateCallback() {
@Override
public void onOpened(@NonNull CameraDevice camera) {
mCamera = camera;
mediaRecorder.setPreviewDisplay(surfaceHolder.getSurface());
mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
mediaRecorder.setMaxFileSize(0);
mediaRecorder.setOrientationHint(0);
mediaRecorder.setOutputFile("test.mp4");
try { mediaRecorder.prepare(); } catch (Exception ignored) {}
List<Surface> list = new ArrayList<>();
list.add(surfaceHolder.getSurface());
try {
CaptureRequest.Builder captureRequest = mCamera.createCaptureRequest(CameraDevice.TEMPLATE_RECORD);
captureRequest.addTarget(surfaceHolder.getSurface());
mCaptureRequest = captureRequest.build();
} catch (CameraAccessException e) {
e.printStackTrace();
}
try {
mCamera.createCaptureSession(list, new CameraCaptureSession.StateCallback() {
@Override
public void onConfigured(@NonNull CameraCaptureSession session) {
mSession = session;
}
@Override
public void onConfigureFailed(@NonNull CameraCaptureSession session) {
mSession = session;
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
mediaRecorder.start();
try {
mSession.setRepeatingRequest(mCaptureRequest,
new CameraCaptureSession.CaptureCallback() {
@Override
public void onCaptureStarted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, long timestamp, long frameNumber) {
super.onCaptureStarted(session, request, timestamp, frameNumber);
}
@Override
public void onCaptureCompleted(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull TotalCaptureResult result) {
super.onCaptureCompleted(session, request, result);
}
@Override
public void onCaptureFailed(@NonNull CameraCaptureSession session, @NonNull CaptureRequest request, @NonNull CaptureFailure failure) {
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
@Override
public void onDisconnected(@NonNull CameraDevice camera) {
}
@Override
public void onError(@NonNull CameraDevice camera, int error) {
}
}, null);
} catch (CameraAccessException e) {
e.printStackTrace();
}
}
// Stop recording and remove SurfaceView
@Override
public void onDestroy() {
mediaRecorder.stop();
mediaRecorder.reset();
mediaRecorder.release();
mCamera.close();
mediaRecorder= null;
windowManager.removeView(surfaceView);
}
@Override
public void surfaceChanged(SurfaceHolder surfaceHolder, int format, int width, int height) {}
@Override
public void surfaceDestroyed(SurfaceHolder surfaceHolder) {}
@Override
public IBinder onBind(Intent intent) { return null; }
}
Hi, were you able to get this code to work without the errors?

Categories

Resources