java—不应该出现的权限错误

jutyujz0  于 2021-06-30  发布在  Java
关注(0)|答案(2)|浏览(270)

活动代码:

package com.example.ma18uus.myapplication;

import java.io.IOException;
import java.io.InputStream;

import java.net.URL;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.SAXException;

public class weatherAPI {

    public static void main() throws Exception {

        //Main url
        String main_url = "http://api.weatherapi.com/v1/";

        //Live or Weekly forecast
        String live_weather = "current.xml?key=";
        //String sevendays_weather = "orecast.xml?key=";

        //API Key + q
        String API_Key = "APIKEY&q=";

        //Location Setters
        String location = "London";

        InputSource inSource = null;
        InputStream in = null;

        XMLReader xr = null;

        try
        {
            // Turn the string into a URL object
            String complete_url = main_url + live_weather + API_Key + location;
            URL urlObject = new URL(complete_url);

            // Open the stream (which returns an InputStream):
            in = urlObject.openStream();

            /**Now parse the data (the stream) that we received back***/

            // Create an XML reader
            SAXParserFactory parserFactory = SAXParserFactory.newInstance();
            SAXParser parser = parserFactory.newSAXParser();
            xr = parser.getXMLReader();

            // Tell that XML reader to use our special Google Handler
            Handler ourSpecialHandler = new Handler();
            xr.setContentHandler(ourSpecialHandler);

            // We have an InputStream, but let's just wrap it in
            // an InputSource (the SAX parser likes it that way)
            inSource = new InputSource(in);

            // And parse it!
            xr.parse(inSource);

        }
        catch(IOException ioe)
        {
            ioe.printStackTrace();
        }
        catch(SAXException se)
        {
            se.printStackTrace();
        }

    }
}

weatherview类:

package com.example.ma18uus.myapplication;

import android.os.AsyncTask;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import android.widget.TextView;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;

import java.io.IOException;
import java.io.InputStream;

import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

public class weatherView extends AppCompatActivity {

    //Main url
    static final String main_url = "http://api.weatherapi.com/v1/";
    //Live or Weekly forecast
    static final String live_weather = "current.xml?key=";
    //String sevendays_weather = "orecast.xml?key=";
    //API Key + q
    static final String API_Key = "c3bdfadb90d5452bb8003318201801&q=";
    //Location Setters
    static final String location = "London";

    //Complete url for todays forecast
    static final String URLT = main_url + live_weather + API_Key + location;

    //XML node keys
    static final String KEY_ITEM = "root";//parent node
    static final String KEY_NAME = "name";//name of city, string
    static final String KEY_WIND_MPH = "wind_mph";//wind mph, float
    static final String KEY_WIND_KPH = "wind_kph";//wind kph, float
    static final String KEY_C = "temp_c";//Temperature Celsius, int
    static final String KEY_C_FEELS = "feelslike_c";//Temperature feeling Celsius, float
    static final String KEY_F = "temp_f";//Temperature Fahrenheit, int
    static final String KEY_F_FEELS = "feelslike_f";//Temperature feeling Fahrenheit, float
    static final String KEY_HUMIDITY = "humidity";//Humidity Level, int
    static final String KEY_CONDITION_TEXT = "text";//Weather Condition i.e. cloudy, sunny, clear, string

    ArrayList<HashMap<String, String>> menuItems;

    private TextView txt;
    String xml;

    //@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_weather_view);

        menuItems = new ArrayList<HashMap<String, String>>();

        txt = (TextView) findViewById(R.id.weather_window);

        new weatherTask().execute();
       // weatherTask.parseXML();
    }

    private class weatherTask extends AsyncTask<Void, Void, Void>{

        @Override
        protected Void doInBackground(Void... voids) {
            parseXML();
            return null;
        }

        private void parseXML(){

            XmlPullParserFactory parserFactory;
            try {
                parserFactory = XmlPullParserFactory.newInstance();
                XmlPullParser parser = parserFactory.newPullParser();
                try {
                    InputStream is = new URL(URLT).openStream();
                    parser.setFeature(XmlPullParser.FEATURE_PROCESS_NAMESPACES, false);
                    parser.setInput(is, null);

                    processParsing(parser);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            } catch (XmlPullParserException e) {
                e.printStackTrace();
            }

        }

        private void processParsing(XmlPullParser parser) throws IOException, XmlPullParserException{

            ArrayList<WeatherConditions> weather = new ArrayList<>();
            int eventType = parser.getEventType();
            WeatherConditions currentWeather = null;

            while(eventType != XmlPullParser.END_DOCUMENT){

                String sName = null;

                switch(eventType){
                    case XmlPullParser.START_TAG:
                        sName = parser.getName();

                        if ("root".equals(sName)){
                            currentWeather = new WeatherConditions();
                            weather.add(currentWeather);
                        }else if (currentWeather != null){
                            if ("name".equals(sName)){
                                currentWeather.name = parser.nextText();
                            }
                            else if ("wind_mph".equals(sName)){
                                currentWeather.wind_mph = parser.nextText();
                            }else if ("wind_kph".equals(sName)){
                                currentWeather.wind_kph = parser.nextText();
                            }else if ("celsius".equals(sName)){
                                currentWeather.celsius = parser.nextText();
                            }else if ("feelsCelsius".equals(sName)){
                                currentWeather.feelsCelsius = parser.nextText();
                            }else if ("fahrenheit".equals(sName)){
                                currentWeather.fahrenheit = parser.nextText();
                            }else if ("feelsFahrenheit".equals(sName)){
                                currentWeather.feelsFahrenheit = parser.nextText();
                            }else if ("humidity".equals(sName)){
                                currentWeather.humidity = parser.nextText();
                            }else if ("text".equals(sName)){
                                currentWeather.condition_text = parser.nextText();
                            }
                        }
                        break;
                }

                eventType = parser.next();
            }

            printWeather(weather);
        }

        private void printWeather(ArrayList<WeatherConditions> weather){

            StringBuilder builder = new StringBuilder();

            for (WeatherConditions weatherC : weather){

                builder.append(weatherC.name).append("\n").append(weatherC.wind_mph).append("\n").append(weatherC.wind_kph).append("\n").append(weatherC.celsius).append("\n").append(weatherC.feelsCelsius).
                        append("\n").append(weatherC.fahrenheit).append("\n").append(weatherC.feelsFahrenheit).append("\n").append(weatherC.humidity).append("\n").append(weatherC.condition_text).append("\n");

            }

            txt.setText(builder.toString());
        }

    }

}

当前清单文件:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.ma18uus.myapplication">

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:networkSecurityConfig="@xml/network_security_config"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        android:usesCleartextTraffic="true">
        <meta-data
            android:name="com.google.android.actions"
            android:resource="@xml/network_security_config" />

        <activity android:name=".weatherView" />
        <activity android:name=".ClothesApp">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".HoodiesSweatShirts" />
        <activity android:name=".CoatsJackets" />
        <activity android:name=".Shirts" />
        <activity android:name=".Trousers" />
        <activity android:name=".Shoes" />
        <activity android:name=".Accessories" />
    </application>

</manifest>

电流误差输出:

01/24 16:15:28: Launching 'app' on Pixel 2 API 29.
$ adb shell am start -n "com.example.ma18uus.myapplication/com.example.ma18uus.myapplication.ClothesApp" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Waiting for process to come online...
Connected to process 22318 on device 'Pixel_2_API_29 [emulator-5554]'.
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/s.myapplicatio: Not late-enabling -Xcheck:jni (already on)
W/main: type=1400 audit(0.0:268): avc: granted { read } for name="u:object_r:net_dns_prop:s0" dev="tmpfs" ino=8398 scontext=u:r:untrusted_app_25:s0:c512,c768 tcontext=u:object_r:net_dns_prop:s0 tclass=file
E/s.myapplicatio: Unknown bits set in runtime_flags: 0x8000
W/s.myapplicatio: Unexpected CPU variant for X86 using defaults: x86
I/s.myapplicatio: The ClassLoaderContext is a special shared library.
D/libEGL: Emulator has host GPU support, qemu.gles is set to 1.
W/libc: Unable to set property "qemu.gles" to "1": connection failed; errno=13 (Permission denied)
W/RenderThread: type=1400 audit(0.0:269): avc: denied { write } for name="property_service" dev="tmpfs" ino=8445 scontext=u:r:untrusted_app_25:s0:c512,c768 tcontext=u:object_r:property_socket:s0 tclass=sock_file permissive=0
D/libEGL: loaded /vendor/lib/egl/libEGL_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv1_CM_emulation.so
D/libEGL: loaded /vendor/lib/egl/libGLESv2_emulation.so
W/s.myapplicatio: Accessing hidden method Landroid/view/View;->computeFitSystemWindows(Landroid/graphics/Rect;Landroid/graphics/Rect;)Z (greylist, reflection, allowed)
W/s.myapplicatio: Accessing hidden method Landroid/view/ViewGroup;->makeOptionalFitsSystemWindows()V (greylist, reflection, allowed)
D/HostConnection: HostConnection::get() New Host Connection established 0xdc973fa0, tid 22351
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0 
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 0 0
D/EGL_emulation: eglCreateContext: 0xe7fa9ac0: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0xe7fa9ac0: ver 3 0 (tinfo 0xe7fe50e0)
W/Gralloc3: mapper 3.x is not supported
D/HostConnection: createUnique: call
D/HostConnection: HostConnection::get() New Host Connection established 0xdc975cb0, tid 22351
D/HostConnection: HostComposition ext ANDROID_EMU_CHECKSUM_HELPER_v1 ANDROID_EMU_native_sync_v2 ANDROID_EMU_native_sync_v3 ANDROID_EMU_native_sync_v4 ANDROID_EMU_dma_v1 ANDROID_EMU_direct_mem ANDROID_EMU_host_composition_v1 ANDROID_EMU_host_composition_v2 ANDROID_EMU_vulkan ANDROID_EMU_deferred_vulkan_commands ANDROID_EMU_vulkan_null_optional_strings ANDROID_EMU_vulkan_create_resources_with_requirements ANDROID_EMU_YUV420_888_to_NV21 ANDROID_EMU_YUV_Cache ANDROID_EMU_async_unmap_buffer GL_OES_EGL_image_external_essl3 GL_OES_vertex_array_object GL_KHR_texture_compression_astc_ldr ANDROID_EMU_gles_max_version_3_0 
D/eglCodecCommon: allocate: Ask for block of size 0x1000
    allocate: ioctl allocate returned offset 0x3ff805000 size 0x2000
D/EGL_emulation: eglMakeCurrent: 0xe7fa9ac0: ver 3 0 (tinfo 0xe7fe50e0)
D/eglCodecCommon: setVertexArrayObject: set vao to 0 (0) 1 0
W/ActivityThread: handleWindowVisibility: no activity for token android.os.BinderProxy@dffd53e
D/NetworkSecurityConfig: Using Network Security Config from resource network_security_config debugBuild: true
W/System.err: java.net.SocketException: socket failed: EPERM (Operation not permitted)
W/System.err:     at java.net.Socket.createImpl(Socket.java:492)
W/System.err:     at java.net.Socket.getImpl(Socket.java:552)
        at java.net.Socket.setSoTimeout(Socket.java:1180)
        at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:143)
        at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:116)
        at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:186)
        at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:128)
        at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:97)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:289)
W/System.err:     at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:232)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:465)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:411)
W/System.err:     at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getInputStream(HttpURLConnectionImpl.java:248)
        at java.net.URL.openStream(URL.java:1072)
        at com.example.ma18uus.myapplication.weatherView$weatherTask.parseXML(weatherView.java:85)
        at com.example.ma18uus.myapplication.weatherView$weatherTask.doInBackground(weatherView.java:73)
        at com.example.ma18uus.myapplication.weatherView$weatherTask.doInBackground(weatherView.java:68)
        at android.os.AsyncTask$3.call(AsyncTask.java:378)
        at java.util.concurrent.FutureTask.run(FutureTask.java:266)
        at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:289)
W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1167)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:641)
        at java.lang.Thread.run(Thread.java:919)
D/EGL_emulation: eglMakeCurrent: 0xe7fa9ac0: ver 3 0 (tinfo 0xe7fe50e0)

我得到了一个关于权限的错误,但是我已经在清单文件上设置了所需的权限,所以我不知道我做错了什么或者我必须修复什么,有人能解释一下情况吗?
另外,我在doinbackground上也犯了一些错误,我也不明白,是因为权限错误,我在那里也犯了错误,还是我做错了什么?
编辑#1:
似乎我用你给我的链接中的权限解决了这个问题,但现在看来我在weatherview类的doinbackground中出现了致命的异常。
编辑#2:当我使用清单1时,我得到了错误输出1,这给了我一个权限错误,但当我使用清单2,这摆脱了权限错误,我得到了一个标记错误:/
编辑#3:更新错误输出和清单文件以匹配当前文件,输出
提前谢谢!!

b4wnujal

b4wnujal1#

标记名 network_security_config 将其重命名为 network-security-config 编辑1:更改为: <?xml version="1.0" encoding="utf-8"?> <network-security-config> <domain-config cleartextTrafficPermitted="true"> <domain includeSubdomains="true">www.weatherapi.com</domain> </domain-config> </network-security-config> 编辑2:对于第二个错误输出,它告诉您使用的是(带下划线)而不是(带破折号),请确保它们在开始和结束标记中都是破折号。

2ledvvac

2ledvvac2#

将此属性放入应用程序标记的清单中

android:usesCleartextTraffic="true"

相关问题