2

我有一个接收来电号码并执行 AsyncTask 的广播接收器。在 onPreExecute 我创建一个通知让我知道已连接到服务器,在 doInBackground 我发出一个 http 请求以下载一些关于 json 格式的信息。下载完成后,我使用 publishProgress 将下载的信息发送到通知,然后我下载图像,并在 OnPostExecute 上再次发送带有图像的通知。

问题是有时有效,有时无效

我用谷歌搜索了好几天试图找到解决方案,但我找不到:(

我非常感谢任何可以提供帮助的人

编辑:在通知异常出现“java.lang.NullPointerException”

public class SearchContact extends AsyncTask<String, String, Void> {

private Context context;
private NotificationManager manager;
private String dataSearch, resp, data1 = "", data2 = "", data3 = "", data4 = "", data5 = "", data6 = "";
private Boolean json_error, connect_error, has_photo;
private Bitmap default_photo, photo;

public SearchContact(Context context, String search){
    this.context = context;
    dataSearch = search;
    default_photo = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher_small_5);
}

@Override
protected void onPreExecute() {
    json_error = true;
    connect_error = false;
    has_photo = false;
    default_photo = BitmapFactory.decodeResource(context.getResources(), R.drawable.ic_launcher_small);
    manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    super.onPreExecute(); 
    createNotification("Pesquisando " + dataSearch + "...", dataSearch, "Pesquisando...", default_photo); //Searching...
}

@Override
protected Void doInBackground(String... params) {
    resp = ""; data1 = ""; data2 = ""; data3 = ""; data4 = ""; data5 = ""; data6 = "";
    if (!dataSearch.isEmpty() && dataSearch != null){
        json_error = false;
        connect_error = false;
        has_photo = false;
        try {
            dataSearch = URLEncoder.encode(dataSearch,
                    "utf-8");
            HttpClient httpClient = new DefaultHttpClient(); //getHttpClient();
            HttpGet httpGet = new HttpGet("http://myserver.net/base.php?search=" + dataSearch + "&format=json");
            HttpResponse response = httpClient.execute(httpGet);
            BufferedReader buf = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
            StringBuffer sb = new StringBuffer();
            String linha;

            while ((linha = buf.readLine()) != null){
                sb.append(linha);
            }
            resp = sb.toString();
        } catch (Exception e){
            connect_error = true;
            //publishProgress("Erro ao receber", dataSearch, "Não foi possível estabelecer conexão", "");
        }
        if (connect_error == false) {
            try {
                JSONObject json = new JSONObject(resp);
                JSONArray contatos = json.getJSONArray("contatos");
                if (contatos.getJSONObject(0).has("data1") == true) {
                    data1 = contatos.getJSONObject(0).getString("data1");
                    data5 = contatos.getJSONObject(0).getString("data5");
                    data2 = contatos.getJSONObject(0).getString("data2");
                    data3 = contatos.getJSONObject(0).getString("data3");
                    data4 = contatos.getJSONObject(0).getString("data4");
                    data6 = contatos.getJSONObject(0).getString("data6");
                }
            } catch (JSONException e) {
                json_error = true;
                //publishProgress("Erro de JSON", dataSearch, "Não foi possível decodificar JSON", "");
            }
            if (json_error == false){
                publishProgress("» " + data1 + " «", data1, (data3.isEmpty() ? data5 : data3), "");
                // ^ HERE, SOMETIMES DOESN'T APPEAR AND FREEZES NOTIFICATION
                if (!data2.contentEquals("1")) {
                    has_photo = true;
                    try {
                        photo = BitmapFactory.decodeStream((InputStream) new URL("http://graph.facebook.com/"+ data2 + "/picture?width=250&height=250").getContent());
                    } catch (Exception e){
                        has_photo = false;
                        photo = default_photo;
                    }
                    //publishProgress("", data1, (data3.isEmpty() ? data5 : data3), "true");
                } else {
                    photo = default_photo;
                    has_photo = false;
                }
                s.putBoolean("has_photo", has_photo);
                s.putParcelable("photo", photo);
            }
        }
    }
    return null;
}

@Override
protected void onProgressUpdate(String... values) {
    super.onProgressUpdate(values);
    createNotification(values[0], values[1], values[2], photo));
}

@Override
protected void onPostExecute(Void result) {
    //if (connect_error) createNotification("Problema de conexão", dataSearch, "Problema de conexão", default_photo); 
    //else 
        //if (json_error) createNotification("Número não encontrado!", dataSearch, "Número não encontrado na base de dados", default_photo); 
        //else 
            createNotification("» " + data1 + " «", data1, (!data3.isEmpty() ? data3 : data5), default_photo);
    super.onPostExecute(result);
}

public void createNotification(String bar, String title, String corpo, Bitmap photo) {
    try {
        Bitmap resized_photo;
        int height = (int) context.getResources().getDimension(android.R.dimen.notification_large_icon_height);
        int width = (int) context.getResources().getDimension(android.R.dimen.notification_large_icon_width);
        if (!has_photo) resized_photo = photo;
        else resized_photo = Bitmap.createScaledBitmap(photo, width, height, false);

        NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher_small);  
        if (!bar.isEmpty()) builder.setTicker(bar);
        if (!title.isEmpty()) builder.setContentTitle(title);
        if (!corpo.isEmpty()) builder.setContentText(corpo);
        if (has_photo == true) builder.setLargeIcon(resized_photo);

        if (has_photo == true){
            NotificationCompat.BigPictureStyle big = new NotificationCompat.BigPictureStyle();
            big.bigPicture(photo);
            big.bigLargeIcon(resized_photo);
            big.setBigContentTitle(title);
            big.setSummaryText(corpo);
            builder.setStyle(big);
        }
        builder.setContentInfo(data6);
        if (!data1.isEmpty()){
            Intent i = new Intent(Intent.ACTION_INSERT_OR_EDIT);
            i.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
            i.putExtra(ContactsContract.Intents.Insert.NAME, title);
            i.putExtra(ContactsContract.Intents.Insert.PHONE, dataSearch);              
            PendingIntent pendingActionAdd = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
            PendingIntent pendingActionView = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT);

            builder
            .addAction(R.drawable.ic_action_add_light, "Adicionar aos contato", pendingActionAdd)
            .setContentIntent(pendingActionView);
        }  
        //manager.cancel(R.string.app_name);
        manager.notify(R.string.app_name, builder.build());  
    } catch (Exception e){
        e.printStackTrace();
        Toast.makeText(context, e.toString(),Toast.LENGTH_SHORT).show();
    }
}
}

[第一次通知] 有时在这里冻结,并且不更新... 测试

4

1 回答 1

0

我通过从广播接收器更改为服务解决了:),我希望我已经帮助了一些人。

于 2014-10-06T04:26:31.087 回答