2017-03-10 6 views
0

Bin ein Neuling Android Entwickler. Ich versuche, eine URL von einem Dienst in Android aufzurufen (die URL gibt JSON-Daten zurück). Ich konnte einen Dienst erstellen, der alle 10 oder 20 Sekunden eine TOAST-Benachrichtigung auslösen kann. Können Sie mir raten, wie Sie den URL-Aufruf im Dienst implementieren, damit ich in der Lage bin, Daten aus der URL abzurufen, wenn der Dienst in festgelegten Intervallen ausgelöst wird? Unten ist der Code, der nicht mehr funktioniert, nachdem ich die URL-Aufrufe hinzugefügt habe.URL Anruf von Android Service

MainActivity.java:

package com.example.android.myservice; 

import android.app.Activity; 
import android.app.AlarmManager; 
import android.app.Application; 
import android.app.PendingIntent; 
import android.content.Context; 
import android.content.Intent; 
import android.support.annotation.Nullable; 
import android.support.v7.app.AppCompatActivity; 
import android.os.Bundle; 
import android.view.View; 
import android.widget.Button; 

import java.util.Calendar; 

public class MainActivity extends AppCompatActivity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     Calendar calendar = Calendar.getInstance(); 
     calendar.setTimeInMillis(System.currentTimeMillis()); 
     calendar.add(Calendar.SECOND, 10); // first time 
     long frequency= 10 * 1000; 
     Intent i = new Intent(getBaseContext(), MyService.class); 
     PendingIntent recurring = PendingIntent.getService(getBaseContext(), 0, i, PendingIntent.FLAG_CANCEL_CURRENT); 
     AlarmManager alarms = (AlarmManager) getSystemService(Context.ALARM_SERVICE); 
     alarms.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), frequency, recurring); 

     finish();  
    } 

} 

MyService.java:

package com.example.android.myservice; 

import android.app.Service; 
import android.content.Intent; 
import android.os.IBinder; 
import android.util.Log; 
import android.widget.Toast; 

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.URL; 

public class MyService extends Service { 

    public MyService() { 
    } 

    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 




     HttpURLConnection urlConnection = null; 
     BufferedReader reader = null; 

     // Will contain the raw JSON response as a string. 
     String forecastJsonStr = null; 

     try { 

      URL url = new URL("http://api.openweathermap.org/data/2.5/forecast/daily?q=94043&mode=json&units=metric&cnt=7&appid=2de143494c0b295cca9337e1e96b00e0"); 

      // Create the request to OpenWeatherMap, and open the connection 
      urlConnection = (HttpURLConnection) url.openConnection(); 
      urlConnection.setRequestMethod("GET"); 
      urlConnection.connect(); 

      // Read the input stream into a String 
      InputStream inputStream = urlConnection.getInputStream(); 
      StringBuffer buffer = new StringBuffer(); 

      reader = new BufferedReader(new InputStreamReader(inputStream)); 

      String line; 
      while ((line = reader.readLine()) != null) { 

       buffer.append(line + "\n"); 
      } 

      forecastJsonStr = buffer.toString(); 

     } catch (IOException e) { 
      Log.e("PlaceholderFragment", "Error ", e); 

     } 
     Toast.makeText(this,"Service started - "+forecastJsonStr, Toast.LENGTH_LONG).show(); 


     return START_STICKY; 
    } 

    @Override 
    public void onDestroy() { 
     super.onDestroy(); 
     Toast.makeText(this,"Service started", Toast.LENGTH_LONG).show(); 
    } 

    @Override 
    public IBinder onBind(Intent intent) { 
     // TODO: Return the communication channel to the service. 
     return null; 
    } 
} 

AndroidManifest:

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

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme" 
     > 
     <uses-permission android:name="android.permission.INTERNET"/> 
     <activity android:name=".MainActivity"> 
      <intent-filter> 
       <action android:name="android.intent.action.MAIN" /> 

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <service 
      android:name=".MyService" 
      android:enabled="true" 
      android:exported="true" 
      android:permission="android.permission.INTERNET"></service> 
    </application> 

</manifest> 

Antwort

0

Die INTERNET Erlaubnis muss außerhalb des application Tags gehen:

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

    <!-- Move the permission here, outside of the application tag: --> 
    <uses-permission android:name="android.permission.INTERNET"/> 

    <application 
     android:allowBackup="true" 
     android:icon="@mipmap/ic_launcher" 
     android:label="@string/app_name" 
     android:supportsRtl="true" 
     android:theme="@style/AppTheme" 
     > 

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

       <category android:name="android.intent.category.LAUNCHER" /> 
      </intent-filter> 
     </activity> 

     <service 
      android:name=".MyService" 
      android:enabled="true" 
      android:exported="true" 
      android:permission="android.permission.INTERNET"></service> 
    </application> 

</manifest>