设备进入睡眠状态时如何继续服务?

时间:2017-08-02 07:30:45

标签: java android json service

我是android的新手。我想使用我的服务从服务器获取Json数据。当我打开我的应用程序然后一切正常但当我退出我的应用程序或我的设备进入睡眠状态时有一个Json exception.how我可以在后台每次运行我的服务。请指导解决此错误。

错误: -

     E/agdghdgdgdrgrdgrdg: dgdgd
     W/System.err: java.net.UnknownHostException: Unable to resolve host  
     "podgier-  
     woman.000webhostapp.com": No address associated with hostname
     W/System.err:     at         
     java.net.InetAddress.lookupHostByName(InetAddress.java:457)
     W/System.err:     at   
     java.net.InetAddress.getAllByNameImpl(InetAddress.java:252)
     W/System.err:     at 
     java.net.InetAddress.getAllByName(InetAddress.java:215)
     W/System.err:     at     
     org.apache.http.conn.DefaultClientConnectionOperator.openConnection
     (DefaultClientConnectionOperator.java:137)
     W/System.err:at org.apache.http.impl.conn.AbstractPoolEntry.open
     (AbstractPoolEntry.java:164)
     W/Systemerr:at 
     org.apache.http.impl.conn.AbstractPooledConnAdapter.open
     (AbstractPooledConnAdapter.java:119)
     W/System.err:     at    
     org.apache.http.impl.client.DefaultRequestDirector.execute
    (DefaultRequestDirector.java:360)
    W/System.err:at 
     org.apache.http.impl.client.AbstractHttpClient.execute
    (AbstractHttpClient.java:555)
    W/System.err:at  
    org.apache.http.impl.client.AbstractHttpClient.execute
   (AbstractHttpClient.java:487)
     W/System.err:at  
     org.apache.http.impl.client.AbstractHttpClient.execute
    (AbstractHttpClient.java:465)
    W/System.err:     at com.grover.jsonp.JSONParser.makeHttpRequest
   (JSONParser.java:62)
   W/System.err:at com.grover.jsonp.BackgroundService$gro.doInBackground
    (BackgroundService.java:50)
    W/System.err:     at   
    com.grover.jsonp.BackgroundService$gro.doInBackground
    (BackgroundService.java:41)
    W/System.err:at android.os.AsyncTask$2.call(AsyncTask.java:288)
    W/System.err:at java.util.concurrent.FutureTask.run
    (FutureTask.java:237)

   W/System.err:     at   
   android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
   W/System.err:     at java.util.concurrent.ThreadPoolExecutor.runWorker
   (ThreadPoolExecutor.java:1112)
   W/System.err:     at   

   java.util.concurrent.ThreadPoolExecutor
   $Worker.run(ThreadPoolExecutor.java:587)
   W/System.err:     at java.lang.Thread.run(Thread.java:818)
   W/System.err: Caused by: android.system.GaiException:     
   android_getaddrinfo    
   failed: EAI_NODATA (No address associated with hostname)
   W/System.err:     at libcore.io.Posix.android_getaddrinfo(Native   
   Method)
   W/System.err:     at   
   libcore.io.ForwardingOs.android_getaddrinfo(ForwardingOs.java:55) 
   W/System.err:     at     
   java.net.InetAddress.lookupHostByName(InetAddress.java:438)
   W/System.err:    ... 18 more
   E/Buffer Error: Error converting result java.io.IOException: Attempted  
   read   
   on closed stream.

BackgroundService.java

public class BackgroundService extends Service
{
public BackgroundService(){
}

private static String url ="https://podgier-woman.000webhostapp.com/table.php";
JSONParser jParser = new JSONParser();
ArrayList<String> bcv;

class gro extends AsyncTask<String, String, String> {
    protected void onPreExecute() {
        super.onPreExecute();

    }

    protected String doInBackground(String... args) {
        java.util.List<NameValuePair> pr = new ArrayList<NameValuePair>();

        JSONObject json = jParser.makeHttpRequest(url, "GET", pr);
        bcv = new ArrayList<String>();
        try {
            JSONArray code = json.getJSONArray("code");
            Log.d("list :",code.toString());
            for (int i = 0; i < code.length(); i++) {
                JSONObject c = code.getJSONObject(i);

                bcv.add(c.getString("name"));

                // adding each child node to HashMap key => value

                // adding contact to contact list
                JSONArray p = null;
            }
        }catch(JSONException e){

        }
        return null;

    }

    protected void onPostExecute(String file_url) {

        Log.v("sdg","sgfdg"+record.idName);

        if(record.idName < bcv.size()){
            int xx= bcv.size() - record.idName;

            Intent intent = new Intent(BackgroundService.this, record.class);

            PendingIntent pIntent = PendingIntent.getActivity(BackgroundService.this, (int) System.currentTimeMillis(),intent, 0);

            Log.d("SGsgzxv","dfgzdvv");
            Notification n = new Notification.Builder(getApplicationContext())
                    .setContentTitle("View "+xx+" updated data")
                    .setContentText("data pending ")
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentIntent(pIntent)
                    .setAutoCancel(true)

                    .addAction(R.mipmap.ic_launcher, "call", pIntent)
                    .addAction(R.mipmap.ic_launcher, "More", pIntent)
                    .addAction(R.mipmap.ic_launcher, "and more", pIntent)

                    .build();

            Uri so = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
            n.sound = so;
            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            nm.notify(0,n);
        }
        record.idName = bcv.size();
        bcv.clear();
    }
}

private static final String TAG = "BackgroundService";
private ThreadGroup myThreads = new ThreadGroup("ServiceWorker");


@Override
public void onCreate() {
    super.onCreate();
    Log.v(TAG, "in onCreate()");

}


@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    super.onStartCommand(intent, flags, startId);
    int counter = intent.getExtras().getInt("counter");



    Log.v(TAG, "in onStartCommand(), counter = " + counter +
            ", startId = " + startId);

    new Thread(myThreads, new ServiceWorker(counter), "BackgroundService")
            .start();


    return START_STICKY;
}


class ServiceWorker implements Runnable
{
    private int counter = -1;

    public ServiceWorker(int counter) {
        this.counter = counter;
    }

    public void run() {

        final String TAG2 = "ServiceWorker:" + Thread.currentThread().getId();
        // do background processing here...
        try {
            Log.e(TAG2, "sleeping for 5 seconds. counter = " + counter);

            while(true)
            {
                Thread.sleep(9000);
                Log.e("agdghdgdgdrgrdgrdg","dgdgd");
                new gro().execute();
            }
        } catch (InterruptedException e) {
            Log.e(TAG2, "... sleep interrupted");
        }
    }
}

@Override
public void onDestroy()
{

}
@Override
public IBinder onBind(Intent intent) {
    Log.v(TAG, "in onBind()");
    return null;
}
}

1 个答案:

答案 0 :(得分:2)

我不建议为此目的使用后台服务。我从经验中知道,我们永远不会确定这样的服务不会被系统破坏。

要执行任务(定期,单个),我建议使用Firebase Job Dispatcher。在我看来,在进行后台工作时,这是一种更可靠的机制。

以下是我给出的一个使用示例:https://stackoverflow.com/a/44489327/8119117