我想通过json文件控制数字,但这不起作用

时间:2019-07-14 15:40:24

标签: java android alarmmanager alarm

嗨,我想通过json文件控制alarmManager时间 我从博客复制了此代码,但是没有用 我希望有人能帮助我解决这个问题,即使我添加了权限INTERNET和READ PHONE STATES,我也厌倦了很多尝试并且没有找到解决方案,这是我的代码:

  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.mypro.json/com.mypro.json.MainActivity}: java.lang.NumberFormatException: Invalid long: ""
  

brodreviv.java

import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.util.concurrent.ExecutionException;

public class brodreviv extends BroadcastReceiver {

    public brodreviv() {

    }   

    @Override
    public void onReceive(Context context, Intent intent) {

        String action = intent.getAction();
        if (Intent.ACTION_BOOT_COMPLETED.equals(action)) {
            startServiceByAlarm(context);
        }
    }

    public static void startServiceByAlarm(Context context) {

        AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(context, Sherlocs.class);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
        long startTime = System.currentTimeMillis();

        assert alarmManager != null;

        final ParseJson parsejsons = new ParseJson();
        try {
            parsejsons.execute().get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
           alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, startTime, Long.parseLong(parsejsons.getTimer1()), pendingIntent);
    }        

    }
  

Sherlocs.java

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;

import java.util.Objects;
import java.util.concurrent.ExecutionException;

public class Sherlocs extends Service {


    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        scheduleAlarm();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

    }

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

    @SuppressLint("NewApi")
    public void scheduleAlarm() {
        final ParseJson parsejsons = new ParseJson();
        try {
            parsejsons.execute().get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        if (isAlarmWorking()) {
            return;
        }

        ((AlarmManager) Objects.requireNonNull(getSystemService(ALARM_SERVICE))).setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), Long.parseLong(parsejsons.getTimer2()), PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(getApplicationContext(), AlarmReciever.class), 0));
    }

    private boolean isAlarmWorking() {
        boolean isWorking = false;
        if (PendingIntent.getBroadcast(getApplicationContext(), 0, new Intent(getApplicationContext(), AlarmReciever.class), PendingIntent.FLAG_UPDATE_CURRENT) == null) {
            isWorking = true;
        }
        return isWorking;
    }

}
  

ParseJson.java

import android.os.AsyncTask;
import android.util.Log;

import org.json.JSONObject;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;


public class ParseJson extends AsyncTask {

    private String timer1 = "";

    private String timer2 = "";

    @Override
    protected Object doInBackground(Object... params) {    

        this.parse();
        return this;    

    }

    private void parse()
    {

        Gethttp sh = new Gethttp();

         String url = "https://api.myjson.com/bins/14z1pr";
        String jsonStr = sh.makeServiceCall(url);

        try {
            JSONObject jsonRoot  = new JSONObject(jsonStr);

            timer1 = jsonRoot.getString("FirstAlarm");
            timer2 = jsonRoot.getString("SecondAlarm");

        }
        catch(Exception e)
        {
            Log.d("FirstAlarm : ", "exception");
            Log.d("SecondAlarm : ", "exception");
        }

    }

    public String getTimer1()
    {
        return timer1;
    }
    public String getTimer2()
    {
        return timer2;
    }

  public class Gethttp {

        private final String TAG = Gethttp.class.getSimpleName();

        public Gethttp() {
        }

        public String makeServiceCall(String reqUrl) {
            String response = null;
            try {
                URL url = new URL(reqUrl);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("GET");
                // read the response
                InputStream in = new BufferedInputStream(conn.getInputStream());
                response = convertStreamToString(in);
            } catch (MalformedURLException e) {
                Log.e(TAG, "MalformedURLException: " + e.getMessage());
            } catch (ProtocolException e) {
                Log.e(TAG, "ProtocolException: " + e.getMessage());
            } catch (IOException e) {
                Log.e(TAG, "IOException: " + e.getMessage());
            } catch (Exception e) {
                Log.e(TAG, "Exception: " + e.getMessage());
            }
            return response;
        }

        private String convertStreamToString(InputStream is) {
            BufferedReader reader = new BufferedReader(new InputStreamReader(is));
            StringBuilder sb = new StringBuilder();

            String line;
            try {
                while ((line = reader.readLine()) != null) {
                    sb.append(line).append('\n');
                }
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    is.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

            return sb.toString();
        }
}}
  

myjson.json

{
  "FirstAlarm": "20000",
  "SecondAlarm": "50000"
}

0 个答案:

没有答案