AndroidRuntime:FATAL EXCEPTION:AsyncTask#1

时间:2017-04-02 08:11:56

标签: java android android-asynctask

在Android设备上构建代码时出错。

当我点击按钮开始获取坐标时,显示器上会显示坐标,但我的应用程序已停止,并且不会在我的服务器上发送数据坐标。

Android Studio的错误报告:

--------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: AsyncTask #1
  Process: id.codefun.gps, PID: 2418
  java.lang.RuntimeException: An error occurred while executing doInBackground()
      at android.os.AsyncTask$3.done(AsyncTask.java:325)
      at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:354)
      at java.util.concurrent.FutureTask.setException(FutureTask.java:223)
      at java.util.concurrent.FutureTask.run(FutureTask.java:242)
      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607)
      at java.lang.Thread.run(Thread.java:761)
   Caused by: java.lang.ClassCastException: com.android.okhttp.internal.huc.HttpURLConnectionImpl cannot be cast
to javax.net.ssl.HttpsURLConnection
      at id.codefun.gps.BackgroundTask.doInBackground(BackgroundTask.java:41)
      at id.codefun.gps.BackgroundTask.doInBackground(BackgroundTask.java:19)
      at android.os.AsyncTask$2.call(AsyncTask.java:305)
      at java.util.concurrent.FutureTask.run(FutureTask.java:237)
      at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:243) 
      at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1133) 
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:607) 
      at java.lang.Thread.run(Thread.java:761)  I/Choreographer: Skipped 41 frames!  The application may be doing too
much work on its main thread. Application terminated.

MainActivity.java

import android.Manifest; import android.content.BroadcastReceiver;
import android.content.Context; import android.content.Intent; import
android.content.IntentFilter; import
android.content.pm.PackageManager; import android.os.Build; import
android.support.annotation.NonNull; import
android.support.v4.content.ContextCompat; import
android.support.v7.app.AppCompatActivity; import android.os.Bundle;
import android.view.View; import android.widget.Button; import
android.widget.TextView;

public class MainActivity extends AppCompatActivity {

    private Button btn_start, btn_stop;
    private TextView textView;
    private BroadcastReceiver broadcastReceiver;
    String dataf;

    @Override
    protected void onResume() {
        super.onResume();
        if(broadcastReceiver == null){
            broadcastReceiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {

                    textView.append("\n" +intent.getExtras().get("coodinates"));

                    dataf = intent.getExtras().get("coodinates").toString();
                    System.out.println(dataf);
                    String method = "dataKirim";
                    BackgroundTask backgroundTask = new BackgroundTask(this);
                    backgroundTask.execute(method,dataf);
                    finish();
                }
            };
        }
        registerReceiver(broadcastReceiver, new IntentFilter("location_update"));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(broadcastReceiver != null){
            unregisterReceiver(broadcastReceiver);
        }
    }

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

        btn_start = (Button) findViewById(R.id.button);
        btn_stop  = (Button) findViewById(R.id.button2);
        textView  = (TextView) findViewById(R.id.textView);

        if(!runtime_permissions())
            enable_buttons();
    }

    private void enable_buttons() {
        btn_start.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Intent i =new Intent(getApplicationContext(),gps.class);
                startService(i);
            }
        });
        btn_stop.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view){
                Intent i =new Intent(getApplicationContext(),gps.class);
                stopService(i);
            }
        });
    }

    private boolean runtime_permissions(){
        if(Build.VERSION.SDK_INT >=23 && ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_FINE_LOCATION) !=
PackageManager.PERMISSION_GRANTED &&
ContextCompat.checkSelfPermission(this,
Manifest.permission.ACCESS_COARSE_LOCATION) !=
PackageManager.PERMISSION_GRANTED){
            requestPermissions(new String[]{Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.ACCESS_COARSE_LOCATION},100);
            return true;
        }
        return false;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults){
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if(requestCode==100){
            if(grantResults[0]==PackageManager.PERMISSION_GRANTED && grantResults[1]==PackageManager.PERMISSION_GRANTED){
                enable_buttons();
            }else{
                runtime_permissions();
            }
        }
    } }

gps.java

import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 
import android.support.annotation.Nullable;

public class gps extends Service {

    private LocationListener listener;
    private LocationManager locationManager;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        listener = new LocationListener() {
            @Override
            public void onLocationChanged(Location location){
                Intent i = new Intent("location_update");
                i.putExtra("coodinates",location.getLongitude()+"-"+location.getLatitude()+"-");
                sendBroadcast(i);
            }

            @Override
            public void onProviderDisabled(String s) {
                Intent i = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(i);
            }
        };
        locationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
        //noinspection MissingPermission
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,3000,0,listener);

    }
}

BackgroundTask.java

import android.content.BroadcastReceiver; import
android.content.Context; import android.os.AsyncTask; import
android.widget.Toast;

import java.io.BufferedWriter; import java.io.IOException; import
java.io.InputStream; import java.io.OutputStream; import
java.io.OutputStreamWriter; import java.net.MalformedURLException;
import java.net.URL; import java.net.URLEncoder;

import javax.net.ssl.HttpsURLConnection;

import static android.widget.Toast.makeText;


public class BackgroundTask extends AsyncTask<String, Void, String> {

    BroadcastReceiver ctx;
    BackgroundTask(BroadcastReceiver ctx){
        this.ctx = ctx;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }

    @Override
    protected String doInBackground(String... params) {
        String post_url = "http://codefun.id/jajal_query_mysqli.php";
        String method = params[0];
        System.out.println(method);
        System.out.println(params[1]);
        if(method.equals("dataKirim")){
            String datag = params[1];
            try {
                URL url = new URL(post_url);
                HttpsURLConnection httpsURLConnection = (HttpsURLConnection)url.openConnection();
                httpsURLConnection.setRequestMethod("POST");
                httpsURLConnection.setDoOutput(true);
                OutputStream OS = httpsURLConnection.getOutputStream();
                BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(OS,"UTF-8"));
                String Data = URLEncoder.encode("latlon","UTF-8") +"="+ URLEncoder.encode(datag,"UTF-8");
                bufferedWriter.write(Data);
                bufferedWriter.flush();
                bufferedWriter.close();
                OS.close();
                InputStream IS = httpsURLConnection.getInputStream();
                IS.close();
                return "kirim sukses";
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    @Override
    protected void onProgressUpdate(Void... values) {
        super.onProgressUpdate(values);
    }

    @Override
    protected void onPostExecute(String result) {
        //makeText(ctx, result,Toast.LENGTH_LONG).show();
    }

}

请帮忙。

1 个答案:

答案 0 :(得分:0)

请注意,您的网址协议是HTTP而非HTTPS。尝试使用java.net.HttpURLConnection对象或“https:// ...”URL。

 import javax.net.ssl.HttpsURLConnection;

替换为

 java.net.HttpURLConnection