2017-03-10 16 views
0

是一位新手android開發人員。我試圖從Android中的服務調用URL(該URL返回json數據)。我已經能夠創建一項能夠每10或20秒觸發一次TOAST通知的服務。您能否告訴我如何在服務中實現URL調用,以便我可以在固定時間間隔觸發服務時從URL中檢索數據。下面是我添加URL調用後停止工作的代碼。來自Android服務的URL調用

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> 

回答

0

INTERNET需要去application以外的標籤:

<?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>