2016-08-10 2 views
0

BroadcastReceiver에서 푸시 메시지를 수신 할 때 메시지를 가져올 수 있지만 느린 다른 서비스를 생성합니다. 예를 들어 푸시 메시지를받을 때 "메시지가 전송되었습니다"를 웹 서비스로 보냈지 만 할 수 있습니다. 'T는 내 웹 서비스 나 테이크 메시지를 브로드 캐스트 리시버를 듣고 내가 브로드 캐스트 리시버를 삭제할 때 나는 매우 fastlyBroadCast 수신기가 다른 서비스에 천천히 작동합니다.

package jsonparse; 

import android.app.Activity; 
import android.app.AlertDialog; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.content.SharedPreferences; 
import android.net.ConnectivityManager; 
import android.net.NetworkInfo; 
import android.os.AsyncTask; 
import android.os.Handler; 
import android.os.HandlerThread; 
import android.os.Looper; 
import android.os.Message; 
import android.telephony.TelephonyManager; 
import android.util.Log; 
import android.view.LayoutInflater; 
import android.view.View; 
import android.view.View.OnClickListener; 
import android.view.ViewGroup; 
import android.widget.BaseAdapter; 
import android.widget.Button; 
import android.widget.TextView; 
import android.widget.Toast; 

import com.androidhive.pushnotifications.MapsActivity; 
import com.androidhive.pushnotifications.R; 
import com.androidhive.pushnotifications.ServerUtilities; 
import com.androidhive.pushnotifications.WakeLocker; 
import com.daasuu.ahp.AnimateHorizontalProgressBar; 
import com.google.android.gcm.GCMRegistrar; 

import org.json.JSONException; 
import org.json.JSONObject; 

import java.util.ArrayList; 
import java.util.HashMap; 
import java.util.List; 

import static com.androidhive.pushnotifications.CommonUtilities.DISPLAY_MESSAGE_ACTION; 
import static com.androidhive.pushnotifications.CommonUtilities.EXTRA_MESSAGE; 
import static com.androidhive.pushnotifications.CommonUtilities.SENDER_ID; 


public class ListViewAdapter extends BaseAdapter implements OnClickListener{ 

    // Declare Variables 
    Context context; 
    LayoutInflater inflater; 
    ArrayList<HashMap<String, String>> data; 
    ImageLoader imageLoader; 
    HashMap<String, String> resultp = new HashMap<String, String>(); 
    //ProgressBar mprogressBar; 
    TextView fulness; 
    TextView location_info; 
    TextView descrip; 
    JSONObject jsonobject; 

    private Handler mHandler = new Handler(); 
    private int mProgressStatus=0; 

    String get_enlem,get_boylam; 
    double dble_get_enlem,dble_get_boylam; 
    String dest_city_name,dest_state_name,dest_country_name; 

    NetworkInfo ni; 
    ConnectivityManager cm; 
    String get_location; 
    String device_id; 
    String sonuc; 
    SharedPreferences prefs; 
    String get_groupID, get_customerID; 

    String get_desc; 

    String get_toplam; 

    // Asyntask 
    AsyncTask<Void, Void, Void> mRegisterTask; 
    public static String name; 
    public static String email; 

    Context con; 

    public ListViewAdapter(Context context, 
      ArrayList<HashMap<String, String>> arraylist) { 
     this.context = context; 
     data = arraylist; 
     imageLoader = new ImageLoader(context); 
    } 

    @Override 
    public int getCount() { 
     return data.size(); 
    } 

    @Override 
    public Object getItem(int position) { 
     return null; 
    } 

    @Override 
    public long getItemId(int position) { 
     return 0; 
    } 

    public View getView(final int position, View convertView, ViewGroup parent) { 
     // Declare Variables 
     /* 
      TextView rank; 
      TextView country; 
      TextView population; 
      ImageView flag; 
     */ 
     TextView location; 
     AnimateHorizontalProgressBar progressBar; 
     Button cop_toplandi; 



     inflater = (LayoutInflater) context 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     View itemView = inflater.inflate(R.layout.listview_item, parent, false); 
     // Get the position 
     resultp = data.get(position); 



     // Locate the TextViews in listview_item.xml 
     //rank = (TextView) itemView.findViewById(R.id.rank); 
     //country = (TextView) itemView.findViewById(R.id.country); 
     //population = (TextView) itemView.findViewById(R.id.population); 

     //Get Device IMEI number 
     TelephonyManager telephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE); 
     device_id = telephonyManager.getDeviceId(); 
     Log.i("IMEI NUMBER", device_id); 


     // Getting name, email from intent 
     Intent i = ((Activity) context).getIntent(); 

     name = i.getStringExtra("get_message_name"); 
     email = i.getStringExtra("email"); 



     Handler handler = new Handler(); 

     final Runnable r = new Runnable() { 
      public void run() { 

       // Make sure the device has the proper dependencies. 
       GCMRegistrar.checkDevice(context); 

       // Make sure the manifest was properly set - comment out this line 
       // while developing the app, then uncomment it when it's ready. 
       GCMRegistrar.checkManifest(context); 

       context.registerReceiver(mHandleMessageReceiver, new IntentFilter(
         DISPLAY_MESSAGE_ACTION)); 


       // Get GCM registration id 
       final String regId = GCMRegistrar.getRegistrationId(context); 

       // Check if regid already presents 
       if (regId.equals("")) { 
        // Registration is not present, register now with GCM 
        GCMRegistrar.register(context, SENDER_ID); 
       } else { 
        // Device is already registered on GCM 
        if (GCMRegistrar.isRegisteredOnServer(context)) { 
         // Skips registration. 
         //   Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_LONG).show(); 
        } else { 
         // Try to register again, but not in the UI thread. 
         // It's also necessary to cancel the thread onDestroy(), 
         // hence the use of AsyncTask instead of a raw thread. 
         final Context contextm = context; 
         mRegisterTask = new AsyncTask<Void, Void, Void>() { 

          @Override 
          protected Void doInBackground(Void... params) { 
           // Register on our server 
           // On server creates a new user 
           ServerUtilities.register(contextm, name, email, regId); 
           return null; 
          } 

          @Override 
          protected void onPostExecute(Void result) { 
           mRegisterTask = null; 
          } 

         }; 
         mRegisterTask.execute(null, null, null); 
        } 
       } 

      } 
     }; 

     handler.postDelayed(r, 1000); 





     prefs = context.getSharedPreferences("login_page", context.MODE_PRIVATE); 

     get_groupID = prefs.getString("user_groupID", "alınmadı"); 
     get_customerID = prefs.getString("user_customerID", "alınmadı"); 

     if (get_groupID.equals("null")) { 

      get_groupID = "0"; 
     } 

     if (get_customerID.equals("null")) { 

      get_customerID = "0"; 
     } 

     location = (TextView) itemView.findViewById(R.id.location); 
     progressBar = (AnimateHorizontalProgressBar) itemView.findViewById(R.id.animate_progress_bar); 
     fulness = (TextView) itemView.findViewById(R.id.txt_percentage_of_fulness); 
     descrip = (TextView) itemView.findViewById(R.id.txt_desc); 

     get_location = resultp.get(MainActivity.COUNTRY); 
     cop_toplandi = (Button) itemView.findViewById(R.id.secret_button); 
     cop_toplandi.setOnClickListener(new OnClickListener() { 
      @Override 
      public void onClick(View v) { 

       Toast.makeText(context.getApplicationContext(),"Başarıyla Gönderildi",Toast.LENGTH_SHORT).show(); 

       new Send_save_status().execute(); 

      } 
     }); 
     location_info = (TextView) itemView.findViewById(R.id.location_info); 

     // Locate the ImageView in listview_item.xml 
     //flag = (ImageView) itemView.findViewById(R.id.flag); 

     // Capture position and set results to the TextViews 
     //rank.setText(resultp.get(MainActivity.RANK)); 
     //country.setText(resultp.get(MainActivity.COUNTRY)); 
     //population.setText(resultp.get(MainActivity.POPULATION)); 
     location.setText(resultp.get(MainActivity.COUNTRY)); 
     location_info.setText(resultp.get(MainActivity.Location_info)); 


     String get_descrip = resultp.get(MainActivity.DESCB); 
     if(get_descrip != "0"){ 

      descrip.setText(resultp.get(MainActivity.DESCB)); 
      cop_toplandi.setVisibility(View.VISIBLE); 
     } 

     get_enlem = resultp.get(MainActivity.POPULATION); 
     get_boylam = resultp.get(MainActivity.FLAG); 

     get_toplam = resultp.get(MainActivity.Toplam); 

     //dble_get_enlem = Double.parseDouble(get_enlem); 
     //dble_get_boylam = Double.parseDouble(get_boylam); 

     // Capture position and set results to the ImageView 
     // Passes flag images URL into ImageLoader.class 
     //imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), flag); 
     // Capture ListView item click 
     String a = resultp.get(MainActivity.RANK); 
     int b = Integer.parseInt(a); 

     progressBar.setMax(100); 
     progressBar.setProgress(b); 



     //progressBar.setProgressWithAnim(b); 
     fulness.setText("%"+(b*1)); 
     //mprogressBar = (ProgressBar) itemView.findViewById(R.id.progressBar); 
     //mprogressBar.setProgress(b); 
/* 
     ObjectAnimator anim = ObjectAnimator.ofInt(mprogressBar, "progress", 0, 80); 
     anim.setDuration(5000); 
     anim.setInterpolator(new DecelerateInterpolator()); 
     anim.start(); 
*/ 

/* 
     //Get location name from latitude and longitude 
     Geocoder geocoder = new Geocoder(context, Locale.getDefault()); 
     List<Address> addresses = null; 
     try { 
      addresses = geocoder.getFromLocation(dble_get_enlem, dble_get_boylam, 1); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     dest_city_name = addresses.get(0).getAddressLine(0); 
     dest_state_name = addresses.get(0).getAddressLine(1); 
     dest_country_name = addresses.get(0).getAddressLine(2); 

     location_info.setText(dest_city_name + " " + dest_country_name); 
*/ 

     itemView.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View arg0) { 

       cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE); 
       ni = cm.getActiveNetworkInfo(); 

       if (ni != null && ni.isConnected()) { 


        Toast.makeText(context,context.getString(R.string.progressdialog_message), Toast.LENGTH_SHORT).show(); 

        // Get the position 
        resultp = data.get(position); 
        Intent intent = new Intent(context, MapsActivity.class); 
        // Pass all data rank 
        intent.putExtra("level", resultp.get(MainActivity.RANK)); 
        // Pass all data country 
        intent.putExtra("imei", resultp.get(MainActivity.COUNTRY)); 
        // Pass all data population 
        intent.putExtra("enlem",resultp.get(MainActivity.POPULATION)); 
        // Pass all data flag 
        intent.putExtra("boylam", resultp.get(MainActivity.FLAG)); 
        // Start SingleItemView Class 
        context.startActivity(intent); 


       }else{ 

        Toast.makeText(context.getApplicationContext(),context.getApplicationContext().getString(R.string.network_connection),Toast.LENGTH_SHORT).show(); 
       } 



      } 
     }); 
     return itemView; 
    } 


    @Override 
    public void onClick(View v) { 

     switch (v.getId()){ 



     } 
    } 


    /** 
    * Receiving push messages 
    * */ 

    private final BroadcastReceiver mHandleMessageReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context context, Intent intent) { 
      String newMessage = intent.getExtras().getString(EXTRA_MESSAGE); 
      // Waking up mobile if it is sleeping 
      WakeLocker.acquire(context); 

      //context.sendBroadcast(new Intent("com.google.android.intent.action.GTALK_HEARTBEAT")); 
      //context.sendBroadcast(new Intent("com.google.android.intent.action.MCS_HEARTBEAT")); 



      // Showing received message 
      //lblMessage.append(newMessage + "\n"); 
      //Toast.makeText(getApplicationContext(), "New Message: " + newMessage, Toast.LENGTH_LONG).show(); 



      //descrip.setText(newMessage); 

      // Intent go = new Intent(context.getApplicationContext(),IsEmri.class); 
      //context.startActivity(go); 


      AlertDialog.Builder builder = new AlertDialog.Builder(context); 

      builder.setTitle("Acil Durum!!!"); 

      builder.setMessage(newMessage) 
        .setCancelable(false) 
        .setPositiveButton("OK", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          // TODO: handle the OK 
         } 
        }) 
        .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
         public void onClick(DialogInterface dialog, int id) { 
          dialog.cancel(); 
         } 
        }); 

      AlertDialog alertDialog = builder.create(); 
      alertDialog.show(); 



      // Releasing wake lock 
      WakeLocker.release(); 


     } 
    }; 



    /* 
    Send GroupID and customerID every five minutes to services 
*/ 
    private class Send_save_status extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected void onPreExecute() { 
      super.onPreExecute(); 
      // Create a progressdialog 

     } 

     @Override 
     protected Void doInBackground(Void... params) { 




      //Toast.makeText(getApplicationContext(), getApplicationContext().getString(R.string.gprs_adres) + address, Toast.LENGTH_LONG).show(); 

      // make sure you close the gps after using it. Save user's battery power 
      //mGPSService.closeGPS(); 



      StringBuilder str_url = new StringBuilder(); 
      str_url.append("http://78.186.62.169:8090/TrackBinSvc.svc/saveStatus/"); 
      Log.i("str_url1", "" + str_url); 
      str_url.append(device_id + "/"); 
      Log.i("strl_url2", "" + str_url); 
      str_url.append(get_location + "/"); 
      Log.i("strl_url3", "" + str_url); 
      str_url.append("opened" + "/"); 
      Log.i("strl_url3", "" + str_url); 
      str_url.append(get_groupID + "/"); 
      Log.i("strl_url3", "" + str_url); 
      str_url.append(get_customerID); 
      Log.i("strl_url3", "" + str_url); 

      String str = str_url.toString(); 


//"http://192.168.0.39:8090/TrackBinSvc.svc/Get_All_Mobile/admin/1234" 
      try { 
       jsonobject = JSONfunctions 
         .getJSONfromURL(str); 
       // Locate the array name in JSON 
       sonuc = jsonobject.getString("SendUpdateCordinatesResult"); 


      } catch (JSONException e) { 

       Log.e("Error", e.getMessage()); 
       e.printStackTrace(); 

      } 


      return null; 

     } 

     @Override 
     protected void onPostExecute(Void args) { 


     } 
    } 

} 

답변

0

문제 내 웹 서비스에 메시지를 보낼 수 있습니다 때 매우 느리게 작동에 보내는 것은 : 당신이 등록하는 방송 수신기는 메인 스레드에서 구현됩니다. 브로드 캐스트 리시버 핸들러는 항상 MAIN THREAD에서 실행되므로 전체 프로세스가 느려집니다. 리시버 자신의 thread를 구현하려면, 독자적인 Handler thread를 제공하는 것으로 명시 적으로 실시 할 수가 있습니다.

이처럼 방송 수신기를 등록

HandlerThread receiverHandlerThread = new HandlerThread("threadName"); 
receiverHandlerThread.start(); 
Looper looper = receiverHandlerThread.getLooper(); 
Handler handler = new Handler(looper); 
context.registerReceiver(mHandleMessageReceiver,newIntentFilter(DISPLAY_MESSAGE_ACTION),null,handler); 
+0

안녕하세요, 전 처리기의 모든 등록 과정을했지만, 난 그것을 천천히 작동하는 동일한 오류가 발생, 나는 업데이트가 내 코드를했다, 당신은 최대 볼 수 있습니다. – Diego

관련 문제