Android 后台服务请求 php 并发送通知

Android Background Service request php and send notification

我有点困惑,为什么我无法为我的问题找到结果。

我想创建一个请求 php 文件 returns 一个 json 字符串的后台服务,然后发送一个包含此 json 字符串内容的通知。

所以我可以向我的用户发送类似的通知。

这怎么可能。

Windows Phone 那时有一个周期性的后台服务 运行 整整 30 分钟,当我想发送即时通知时,我不得不使用那里的服务。

您可以使用 Volley.

您可以使用此代码作为参考:

package com.exampfle.real; 

import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class RealService extends Service{

    private static final String TAG="RealService";
    private boolean isRunning=false;
    private IBinder mBinder=new MyBinder();
    private boolean intenetAccess=false;
/* Change here */ 
    private RequestQueue reQueue;
    private final String url="http://www.google.com";

    public boolean SendRequest() 
    {
/* Change here */
    reQueue = Volley.newRequestQueue(this); 
        StringRequest request=new StringRequest(com.android.volley.Request.Method.GET,
                url, 
                new Response.Listener<String>() {

            @Override 
            public void onResponse( 
                    String response) {

                intenetAccess=true;
            } 
        }, 

        new Response.ErrorListener() {

            @Override 
            public void onErrorResponse( 
                    VolleyError error) {

                intenetAccess=false;

            } 
        }); 

        try{ 
            reQueue.add(request);
        } 
        catch(Exception e){}

        return intenetAccess;

    } 

    @Override 
    public void onCreate() { 
        super.onCreate(); 
        Log.i(TAG, "Service onCreate");

        isRunning=true;

    } 



    @Override 
    public IBinder onBind(Intent intent) {
        Log.i(TAG, "Service onBind");
        return mBinder;
    } 

    @Override 
    public void onRebind(Intent intent) {
        Log.i(TAG, "Service onRebind");
        super.onRebind(intent);
    } 

    @Override 
    public boolean onUnbind(Intent intent) {
        Log.i(TAG, "Service onUnBind");
        return true; 
    } 

    @Override 
    public void onDestroy() { 

    isRunning=false;

        Log.i(TAG, "Service onDestroy");
        super.onDestroy(); 
    } 



    public class MyBinder extends Binder
    { 
        RealService getService() 
        { 
            return RealService.this;
        } 
    } 
} 

希望对你有帮助:)