Java MultipartPloadRequest在向php服务器发送图像时正在为服务通知创建未知的无效通道
我已经创建了一个项目,需要使用android中的move_upload_文件将图像上传到PHP服务器。通过android,我使用MultipartPloadRequest将图像发送到服务器 首先错误出现在cursor变量上,当我删除该变量时,在添加权限后发生前台服务器错误some java.lang.RuntimeException:服务通知的通道无效 我的java代码Java MultipartPloadRequest在向php服务器发送图像时正在为服务通知创建未知的无效通道,java,android,multipartform-data,Java,Android,Multipartform Data,我已经创建了一个项目,需要使用android中的move_upload_文件将图像上传到PHP服务器。通过android,我使用MultipartPloadRequest将图像发送到服务器 首先错误出现在cursor变量上,当我删除该变量时,在添加权限后发生前台服务器错误some java.lang.RuntimeException:服务通知的通道无效 我的java代码 private Button buttonChoose; private Button buttonUpload; priva
private Button buttonChoose;
private Button buttonUpload;
private ImageView imageView;
private EditText editText;
//Image request code
private int PICK_IMAGE_REQUEST = 1;
//storage permission code
private static final int STORAGE_PERMISSION_CODE = 123;
//Bitmap to get image from gallery
private Bitmap bitmap;
//Uri to store the image uri
private Uri filePath;
private String UPLOAD_URL = "http://10.0.2.2/rest/seller/upload.php";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_send_image);
//Requesting storage permission
requestStoragePermission();
//Initializing views
buttonChoose = (Button) findViewById(R.id.buttonChoose);
buttonUpload = (Button) findViewById(R.id.buttonUpload);
imageView = (ImageView) findViewById(R.id.imageView);
editText = (EditText) findViewById(R.id.editTextName);
//Setting clicklistener
buttonChoose.setOnClickListener(this);
buttonUpload.setOnClickListener(this);
}
public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to show file chooser
private void showFileChooser() {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), PICK_IMAGE_REQUEST);
}
//handling the image chooser activity result
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null && data.getData() != null) {
filePath = data.getData();
try {
bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), filePath);
imageView.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
}
}
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
cursor.close();
return path;
}
//Requesting permission
private void requestStoragePermission() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED)
return;
if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
//If the user has denied the permission previously your code will come to this block
//Here you can explain why you need this permission
//Explain here why you need this permission
}
//And finally ask for the permission
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL_STORAGE}, STORAGE_PERMISSION_CODE);
}
//This method will be called when the user will tap on allow or deny
@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
//Checking the request code of our request
if (requestCode == STORAGE_PERMISSION_CODE) {
//If permission is granted
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
//Displaying a toast
Toast.makeText(this, "Permission granted now you can read the storage", Toast.LENGTH_LONG).show();
} else {
//Displaying another toast if permission is not granted
Toast.makeText(this, "Oops you just denied the permission", Toast.LENGTH_LONG).show();
}
}
}
@Override
public void onClick(View v) {
if (v == buttonChoose) {
showFileChooser();
}
if (v == buttonUpload) {
uploadMultipart();
}
}
我的Php代码
<?php
require_once 'config.php';
$upload_path = 'images/';
$server_ip = gethostbyname(gethostname());
$upload_url = 'http://' . $server_ip . '/rest/seller/' . $upload_path;
$response = array();
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
if (isset($_POST['name']) and isset($_FILES['image']['name']))
{
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Unable to Connect...');
$name = $_POST['name'];
$fileinfo = pathinfo($_FILES['image']['name']);
$extension = $fileinfo['extension'];
$file_url = $upload_url . getFileName() . '.' . $extension;
$file_path = $upload_path . getFileName() . '.' . $extension;
try
{
move_uploaded_file($_FILES['image']['tmp_name'], $file_path);
$sql = "INSERT INTO `uploadimagetoserver` (`id`, `url`, `name`) VALUES (NULL,
'$file_url', '$name');";
if (mysqli_query($con, $sql))
{
$response['error'] = false;
$response['url'] = $file_url;
$response['name'] = $name;
}
}
catch(Exception $e)
{
$response['error'] = true;
$response['message'] = $e->getMessage();
}
echo json_encode($response);
mysqli_close($con);
}
else
{
$response['error'] = true;
$response['message'] = 'Please choose a file';
}
}
function getFileName()
{
$con = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) or die('Unable to Connect...');
$sql = "SELECT max(id) as id FROM uploadimagetoserver";
$result = mysqli_fetch_array(mysqli_query($con, $sql));
mysqli_close($con);
if ($result['id'] == null) return 1;
else return ++$result['id'];
}
好的,我明白了,但是向上面的php服务器发送图像的最佳方式或实践是什么呢。请帮忙!
2020-10-14 13:19:59.878 8115-8115/market.example.marketapplication E/AndroidRuntime: FATAL EXCEPTION: main
Process: market.example.marketapplication, PID: 8115
android.app.RemoteServiceException: Bad notification for startForeground: java.lang.RuntimeException: invalid channel for service notification: Notification(channel=null pri=0 contentView=null vibrate=null sound=null defaults=0x0 flags=0x42 color=0x00000000 groupKey=net.gotev vis=PRIVATE)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1737)
at android.os.Handler.dispatchMessage(Handler.java:106)
at android.os.Looper.loop(Looper.java:193)
at android.app.ActivityThread.main(ActivityThread.java:6669)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2020-10-14 13:20:00.014 1917-1990/? E/InputDispatcher: channel '1d0ede
market.example.marketapplication/market.example.marketapplication.activity.SendImageActivity
(server)' ~ Channel is unrecoverably broken and will be disposed!
2020-10-14 13:20:00.014 1917-1990/? E/InputDispatcher: channel '3e9882b
market.example.marketapplication/market.example.marketapplication.activity.LoginMainActivity
(server)' ~ Channel is unrecoverably broken and will be disposed!