简体   繁体   English

BroadcastReceiver在android中不起作用

[英]BroadcastReceiver not working in android

I am using this code to create a BroadcastReceiver that has to run even the application is not running. 我正在使用此代码创建即使应用程序未运行也必须运行的BroadcastReceiver。

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicHeader;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.util.Log;

public class ReminderClass extends BroadcastReceiver {
    SharedPreferences myPrefs;
    String prefuName, pref_usr_fname, prefdev_id, pref_usr_lname, pref_uid,
            pref_usr_email, ret, dates_btw;;
    String event_desc, e_time, s_time, event_title, day_event_id;
    ArrayList<String> day_data = new ArrayList<String>();
    ArrayList<String> st_time = new ArrayList<String>();
    ArrayList<String> et_time = new ArrayList<String>();
    ArrayList<String> day_eve_id = new ArrayList<String>();
    ArrayList<String> day_eve_title = new ArrayList<String>();
    int MILLIS_IN_FIFTEEN_MINS = 1000 * 60 * 15 ;

    SimpleDateFormat dateFormat = new SimpleDateFormat("hh:mm a");
    @Override
    public void onReceive(Context con, Intent _intent) {
        // TODO Auto-generated method stub
        Log.v("inside the broadcast receiver1 >>","broadcast1");
        if (_intent.getAction().equals("REMINDER")) {

        Log.v("inside the broadcast receiver2 >>","broadcast2");
        myPrefs = con.getSharedPreferences("myPrefs", 1);
        prefuName = myPrefs.getString("u_name", "");
        pref_usr_fname = myPrefs.getString("fname", "");
        prefdev_id = myPrefs.getString("dev_id", "");
        pref_usr_lname = myPrefs.getString("lname", "");
        pref_uid = myPrefs.getString("id", "");
        pref_usr_email = myPrefs.getString("email", "");

        Log.v("pref name>>> ", prefuName);
        Log.v("pref pass >>", pref_usr_fname);
        Log.v("prev devid >>", prefdev_id);
        Log.v("pref_usr_fname", pref_usr_fname);
        Log.v("pref_usr_lname", pref_usr_lname);
        Log.v("pref_uid", pref_uid);
        Log.v("pref_usr_email", pref_usr_email);

        try {
            HttpClient client = new DefaultHttpClient();
            HttpConnectionParams.setConnectionTimeout(client.getParams(), 10000); // Timeout
                                                                                    // Limit

            HttpResponse response;
            HttpPost post = null;
            JSONObject json = new JSONObject();

                post = new HttpPost("my_url");
                json.put("user_id", pref_uid);

                post.setHeader("Content-Type", "application/json");
                post.setHeader("Accept", "application/json");
                StringEntity se = new StringEntity(json.toString());
                se.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,
                        "application/json"));
                post.setEntity(se);
                response = client.execute(post);
                Log.v("Response >>>", response + "");
                ret = EntityUtils.toString(response.getEntity());
                Log.v("My calendar response", ret);
        } catch (UnsupportedEncodingException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (ClientProtocolException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (org.apache.http.ParseException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (JSONException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        } catch (IOException e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }           
    }
        else
        {
            Log.v("Broadcast not working >>","broadcast not working");
        }
    }

}

In my manifest, 在我的清单上

<receiver
            android:name=".ReminderClass"
            android:enabled="true"   android:permission="android.permission.INTERNET">
            <intent-filter>
                <action android:name="REMINDER" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </receiver>

My Broadcast is not been called. 未调用我的广播。 what I have done wrong? 我做错了什么?

Step #1: Delete android:permission from your <intent-filter> , unless you really are requiring that anyone sending the broadcast must hold the INTERNET permission. 步骤#1:从您的<intent-filter>删除android:permission ,除非您确实要求发送广播的任何人都必须拥有INTERNET权限。

Step #2: Use a unique action string, perhaps one that has your package name in it, instead of REMINDER . 步骤#2:使用唯一的操作字符串,而不是REMINDER ,可能是其中包含您的程序包名称的字符串。

Step #3: Move all of your code out of the BroadcastReceiver and into something else, like an IntentService . 步骤#3:将所有代码移出BroadcastReceiver并移至其他内容,例如IntentService Your current code is doing network I/O on the main application thread. 您当前的代码正在主应用程序线程上执行网络I / O。 Your code, therefore, will crash on Android 4.x devices, and is merely a very bad idea on earlier Android versions. 因此,您的代码将在Android 4.x设备上崩溃,并且在较早的Android版本上只是一个非常糟糕的主意。

I solved my problem. 我解决了我的问题。 I have added a Service, and called that service in a BroadcastReceiver, which checks when boot complete. 我添加了一个服务,并在BroadcastReceiver中调用了该服务,该服务检查启动完成的时间。 In Oncreate() method of the service, I implemented a thread which runs every minute. 在服务的Oncreate()方法中,我实现了一个每分钟运行一次的线程。 I used my code inside the run method of the thread. 我在线程的run方法中使用了我的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM