2

着信番号を取得して AsyncTask を実行するブロードキャスト レシーバーがあります。onPreExecute では、サーバーに接続していることを知らせる通知を作成し、doInBackground では、json 形式でいくつかの情報をダウンロードするための http 要求を作成します。ダウンロードが完了したら、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 に答える