从我创建的位置服务启动摄像头服务时出现错误,从主活动启动服务时未显示该错误。
这是在捕获成功时显示“应用程序传递空表面” 的消息:成功
错误未显示应用“应用传递空表面” :错误
此代码:
主要活动:
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
@BindView(R.id.ButtonUpload) Button btnupload;
@BindView(R.id.ButtonService2) Button btnservice;
@BindView(R.id.ButtonService3) Button btnservice2;
@BindView(R.id.longitude) TextView tvlongitude;
@BindView(R.id.latitude) TextView tvlatitude;
@BindView(R.id.derajat) TextView tvderajat;
private static final int REQUEST_PERMISSIONS = 101;
private String degree;
boolean boolean_permission;
Double latitude,longitude;
Geocoder geocoder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
geocoder = new Geocoder(this, Locale.getDefault());
ButterKnife.bind(this);
btnupload.setOnClickListener(this);
btnservice.setOnClickListener(this);
btnservice2.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.ButtonUpload:
startService(new Intent(MainActivity.this, CameraService.class));
break;
case R.id.ButtonService2:
if ((ActivityCompat.checkSelfPermission(getApplicationContext(), android.Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
&& (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED)
&& (ActivityCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED))
{
Intent intent = new Intent(getApplicationContext(), Location.class);
Toast.makeText(getApplicationContext(),"Service Berjalan",Toast.LENGTH_SHORT).show();
startService(intent);
} else {
ActivityCompat.requestPermissions(MainActivity.this, new String[]{android.Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CAMERA, Manifest.permission.WRITE_EXTERNAL_STORAGE}, REQUEST_PERMISSIONS);
}
break;
case R.id.ButtonService3:
Intent location = new Intent(getApplicationContext(), Location.class);
stopService(location);
break;
}
}
相机服务:
public class CameraService extends HiddenCameraService {
Bitmap bitmap;
String encodedImage;
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.CAMERA)== PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED &&
ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)== PackageManager.PERMISSION_GRANTED) {
if (HiddenCameraUtils.canOverDrawOtherApps(this)) {
CameraConfig cameraConfig = new CameraConfig()
.getBuilder(this)
.setCameraFacing(CameraFacing.REAR_FACING_CAMERA)
.setCameraResolution(CameraResolution.MEDIUM_RESOLUTION)
.setImageFormat(CameraImageFormat.FORMAT_JPEG)
.setCameraFocus(CameraFocus.AUTO)
.build();
startCamera(cameraConfig);
new android.os.Handler().postDelayed(new Runnable() {
@Override
public void run() {
Log.d("Camera","Capturing Camera");
takePicture();
}
}, 2000);
} else {
//Open settings to grant permission for "Draw other apps".
HiddenCameraUtils.openDrawOverPermissionSetting(this);
}
} else {
//TODO Ask your parent activity for providing runtime permission
Log.e("Camera", "Permission Not Available");
}
return START_NOT_STICKY;
}
@Override
public void onImageCapture(@NonNull File imageFile) {
Uri filepath = getImageContentUri(getApplicationContext(),imageFile);
try {
InputStream inputStream = getContentResolver().openInputStream(Objects.requireNonNull(filepath));
bitmap = BitmapFactory.decodeStream(inputStream);
}catch (Exception e){
e.printStackTrace();
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, urlUpload, new Response.Listener<String>() {
@Override
public void onResponse(String response) {
Toast.makeText(getApplicationContext(), "Succes : " + response, Toast.LENGTH_SHORT).show();
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), "Error : " + error.toString(), Toast.LENGTH_SHORT).show();
}
}){
@Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
String imageData = imageToString(bitmap);
params.put("image",imageData);
return params;
}
};
RequestQueue requestQueue = Volley.newRequestQueue(this);
requestQueue.add(stringRequest);
stopSelf();
}
private String imageToString(Bitmap bitmap){
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100, outputStream);
byte[] imageBytes = outputStream.toByteArray();
encodedImage = Base64.encodeToString(imageBytes,Base64.DEFAULT);
return encodedImage;
}
public static Uri getImageContentUri(Context context, File imageFile) {
String filePath = imageFile.getAbsolutePath();
Cursor cursor = context.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
new String[] { MediaStore.Images.Media._ID },
MediaStore.Images.Media.DATA + "=? ",
new String[] { filePath }, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.MediaColumns._ID));
cursor.close();
return Uri.withAppendedPath(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "" + id);
} else {
if (imageFile.exists()) {
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.DATA, filePath);
return context.getContentResolver().insert(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
} else {
return null;
}
}
}
@Override
public void onCameraError(@CameraError.CameraErrorCodes int errorCode) {
switch (errorCode) {
case CameraError.ERROR_CAMERA_OPEN_FAILED:
//Camera open failed. Probably because another application
//is using the camera
Toast.makeText(this, "Error cannot open", Toast.LENGTH_LONG).show();
break;
case CameraError.ERROR_IMAGE_WRITE_FAILED:
//Image write failed. Please check if you have provided WRITE_EXTERNAL_STORAGE permission
Toast.makeText(this, "Error cannot write", Toast.LENGTH_LONG).show();
break;
case CameraError.ERROR_CAMERA_PERMISSION_NOT_AVAILABLE:
//camera permission is not available
//Ask for the camera permission before initializing it.
Toast.makeText(this, "Error cannot get Permission", Toast.LENGTH_LONG).show();
break;
case CameraError.ERROR_DOES_NOT_HAVE_OVERDRAW_PERMISSION:
//Display information dialog to the user with steps to grant "Draw over other app"
//permission for the app.
HiddenCameraUtils.openDrawOverPermissionSetting(this);
break;
case CameraError.ERROR_DOES_NOT_HAVE_FRONT_CAMERA:
Toast.makeText(this, "Error no camera", Toast.LENGTH_LONG).show();
break;
}
stopSelf();
}
}
我要致电摄像头服务的位置服务:
public class Location extends Service implements LocationListener, SensorEventListener {
boolean isGPSEnable = false;
boolean isNetworkEnable = false;
double latitude, longitude;
LocationManager locationManager;
android.location.Location location;
private Handler mHandler = new Handler();
private Timer mTimer = null;
long notify_interval = 10 * 1000;
public static String str_receiver = "servicetutorial.service.receiver";
Intent intent;
private float currentDegree = 0f;
// device sensor manager
private SensorManager mSensorManager;
public Location() {
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
mTimer = new Timer();
mTimer.schedule(new TimerTaskToGetLocation(), 5, notify_interval);
intent = new Intent(str_receiver);
locationManager = (LocationManager) getApplicationContext().getSystemService(LOCATION_SERVICE);
fn_getlocation();
}
@Override
public void onLocationChanged(android.location.Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}
private void fn_getlocation() {
mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
isGPSEnable = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
isNetworkEnable = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
if(isNetworkEnable) {
location = null;
if (ActivityCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, notify_interval, 0, this);
if (locationManager!=null){
location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if (location!=null){
latitude = location.getLatitude();
longitude = location.getLongitude();
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME);
fn_update(location);
if(latitude<-5 & longitude<128) {
startService(new Intent(getBaseContext(), CameraService.class));
}
}
}
}
}
else if (isGPSEnable){
location = null;
if (ActivityCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getApplicationContext(),Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, notify_interval, 0, this);
if (locationManager!=null){
location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if (location!=null){
latitude = location.getLatitude();
longitude = location.getLongitude();
mSensorManager.registerListener(this, mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION), SensorManager.SENSOR_DELAY_GAME);
fn_update(location);
if(latitude<-5 & longitude<128) {
startService(new Intent(getBaseContext(), CameraService.class));
}
}
}
}
}
else {
stopSelf();
}
}