2016-03-11 5 views
0

я это руководство http://androidsrc.net/android-push-notification-using-google-cloud-messaging-gcm-part-1/ И после некоторых изменений (потому что я использую Android Studio) она отлично работает^_^Получать уведомления GCM в моем андроиде приложения

Я могу успешно зарегистрировать свои устройства в базе данных и получить уведомление от моего php-сервера ...

Проблема заключается в том, что устройство получает уведомление, которое оно появляется в панели уведомлений ... но я хочу получать уведомление внутри своего приложения ... потому что согласно сообщению (в уведомлении) мое приложение будет делать некоторые действия ... (Например, если сообщение «пожарный» сигнал будет быть обеденным ... и т. д.)

Как я могу это сделать? Получение уведомления в приложении?

Вот на стороне клиента ... (Приложение)

public class MainActivity extends Activity { 

    // Resgistration Id from GCM 
    private static final String PREF_GCM_REG_ID = "PREF_GCM_REG_ID"; 
    private SharedPreferences prefs; 
    // Your project number and web server url. Please change below. 
    private static final String GCM_SENDER_ID = "MY_PROJECT_ID"; 
    private static final String WEB_SERVER_URL = "WEB_PAGE"; 

    GoogleCloudMessaging gcm; 
    Button registerBtn; 
    TextView regIdView; 
    EditText test; 
    private static final int ACTION_PLAY_SERVICES_DIALOG = 100; 
    protected static final int MSG_REGISTER_WITH_GCM = 101; 
    protected static final int MSG_REGISTER_WEB_SERVER = 102; 
    protected static final int MSG_REGISTER_WEB_SERVER_SUCCESS = 103; 
    protected static final int MSG_REGISTER_WEB_SERVER_FAILURE = 104; 
    private String gcmRegId; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     registerBtn = (Button) findViewById(R.id.register_gcmserver); 
     registerBtn.setOnClickListener(new OnClickListener() { 

      @Override 
      public void onClick(View v) { 
       // Check device for Play Services APK. 
       if (isGoogelPlayInstalled()) { 
        gcm = GoogleCloudMessaging.getInstance(getApplicationContext()); 

        // Read saved registration id from shared preferences. 
        gcmRegId = getSharedPreferences().getString(PREF_GCM_REG_ID, ""); 

        if (TextUtils.isEmpty(gcmRegId)) { 
         handler.sendEmptyMessage(MSG_REGISTER_WITH_GCM); 
        }else{ 
         regIdView.setText(gcmRegId); 
         test.setText(gcmRegId); 
         Toast.makeText(getApplicationContext(), "Already registered with GCM", Toast.LENGTH_SHORT).show(); 
        } 
       } 

      } 
     }); 
     regIdView = (TextView) findViewById(R.id.regId); 
     test = (EditText) findViewById(R.id.editText); 

    } 

    private boolean isGoogelPlayInstalled() { 
     int resultCode = GooglePlayServicesUtil 
       .isGooglePlayServicesAvailable(this); 
     if (resultCode != ConnectionResult.SUCCESS) { 
      if (GooglePlayServicesUtil.isUserRecoverableError(resultCode)) { 
       GooglePlayServicesUtil.getErrorDialog(resultCode, this, 
         ACTION_PLAY_SERVICES_DIALOG).show(); 
      } else { 
       Toast.makeText(getApplicationContext(), 
         "Google Play Service is not installed", 
         Toast.LENGTH_SHORT).show(); 
       finish(); 
      } 
      return false; 
     } 
     return true; 

    } 

    private SharedPreferences getSharedPreferences() { 
     if (prefs == null) { 
      prefs = getApplicationContext().getSharedPreferences(
        "AndroidSRCDemo", Context.MODE_PRIVATE); 
     } 
     return prefs; 
    } 

    public void saveInSharedPref(String result) { 
     // TODO Auto-generated method stub 
     Editor editor = getSharedPreferences().edit(); 
     editor.putString(PREF_GCM_REG_ID, result); 
     editor.commit(); 
    } 

    Handler handler = new Handler() { 
     public void handleMessage(android.os.Message msg) { 
      switch (msg.what) { 
       case MSG_REGISTER_WITH_GCM: 
        new GCMRegistrationTask().execute(); 
        break; 
       case MSG_REGISTER_WEB_SERVER: 
        new WebServerRegistrationTask().execute(); 
        break; 
       case MSG_REGISTER_WEB_SERVER_SUCCESS: 
        Toast.makeText(getApplicationContext(), 
          "registered with web server", Toast.LENGTH_LONG).show(); 

        break; 
       case MSG_REGISTER_WEB_SERVER_FAILURE: 
        Toast.makeText(getApplicationContext(), 
          "registration with web server failed", 
          Toast.LENGTH_LONG).show(); 
        break; 
      } 
     }; 
    }; 

    private class GCMRegistrationTask extends AsyncTask<Void, Void, String> { 

     @Override 
     protected String doInBackground(Void... params) { 
      // TODO Auto-generated method stub 
      if (gcm == null && isGoogelPlayInstalled()) { 
       gcm = GoogleCloudMessaging.getInstance(getApplicationContext()); 
      } 
      try { 
       gcmRegId = gcm.register(GCM_SENDER_ID); 
      } catch (IOException e) { 
       // TODO Auto-generated catch block 
       e.printStackTrace(); 
      } 

      return gcmRegId; 
     } 

     @Override 
     protected void onPostExecute(String result) { 
      if (result != null) { 
       Toast.makeText(getApplicationContext(), "registered with GCM", 
         Toast.LENGTH_LONG).show(); 
       regIdView.setText(result); 
       saveInSharedPref(result); 
       handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER); 
      } 
     } 

    } 

    private class WebServerRegistrationTask extends AsyncTask<Void, Void, Void> { 

     @Override 
     protected Void doInBackground(Void... params) { 
      URL url = null; 
      try { 
       url = new URL(WEB_SERVER_URL); 
      } catch (MalformedURLException e) { 
       e.printStackTrace(); 
       handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_FAILURE); 
      } 
      Map<String, String> dataMap = new HashMap<String, String>(); 
      dataMap.put("regId", gcmRegId); 

      StringBuilder postBody = new StringBuilder(); 
      Iterator iterator = dataMap.entrySet().iterator(); 

      while (iterator.hasNext()) { 
       Entry param = (Entry) iterator.next(); 
       postBody.append(param.getKey()).append('=') 
         .append(param.getValue()); 
       if (iterator.hasNext()) { 
        postBody.append('&'); 
       } 
      } 
      String body = postBody.toString(); 
      byte[] bytes = body.getBytes(); 

      HttpURLConnection conn = null; 
      try { 
       conn = (HttpURLConnection) url.openConnection(); 
       conn.setDoOutput(true); 
       conn.setUseCaches(false); 
       conn.setFixedLengthStreamingMode(bytes.length); 
       conn.setRequestMethod("POST"); 
       conn.setRequestProperty("Content-Type", 
         "application/x-www-form-urlencoded;charset=UTF-8"); 

       OutputStream out = conn.getOutputStream(); 
       out.write(bytes); 
       out.close(); 

       int status = conn.getResponseCode(); 
       if (status == 200) { 
        // Request success 
        handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_SUCCESS); 
       } else { 
        throw new IOException("Request failed with error code " 
          + status); 
       } 
      } catch (ProtocolException pe) { 
       pe.printStackTrace(); 
       handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_FAILURE); 
      } catch (IOException io) { 
       io.printStackTrace(); 
       handler.sendEmptyMessage(MSG_REGISTER_WEB_SERVER_FAILURE); 
      } finally { 
       if (conn != null) { 
        conn.disconnect(); 
       } 
      } 

      return null; 
     } 
    } 

} 

класс GCMBroadcastReceiver

public class GCMBroadcastReceiver extends WakefulBroadcastReceiver{ 

    @Override 
    public void onReceive(Context context, Intent intent) { 
     // Attach component of GCMIntentService that will handle the intent in background thread 
     ComponentName comp = new ComponentName(context.getPackageName(), 
       GCMIntentService.class.getName()); 
     // Start the service, keeping the device awake while it is launching. 
     startWakefulService(context, (intent.setComponent(comp))); 
     setResultCode(Activity.RESULT_OK); 
    } 
} 

класс GCMIntentService

public class GCMIntentService extends IntentService { 

    public static final int NOTIFICATION_ID = 1000; 
    NotificationManager mNotificationManager; 
    NotificationCompat.Builder builder; 

    public GCMIntentService() { 
     super(GCMIntentService.class.getName()); 
    } 

    @Override 
    protected void onHandleIntent(Intent intent) { 
     Bundle extras = intent.getExtras(); 

     if (!extras.isEmpty()) { 

      // read extras as sent from server 
      String message = extras.getString("message"); 
      String serverTime = extras.getString("timestamp"); 
      sendNotification("Message: " + message + "\n" + "Server Time: " 
        + serverTime); 
     } 
     // Release the wake lock provided by the WakefulBroadcastReceiver. 
     GCMBroadcastReceiver.completeWakefulIntent(intent); 
    } 

    private void sendNotification(String msg) { 
     mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 

     PendingIntent contentIntent = PendingIntent.getActivity(this, 0, 
       new Intent(this, MainActivity.class), 0); 

     NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(
       this).setSmallIcon(R.mipmap.ic_launcher) 
       .setContentTitle("Notification from GCM") 
       .setStyle(new NotificationCompat.BigTextStyle().bigText(msg)) 
       .setContentText(msg); 

     mBuilder.setContentIntent(contentIntent); 
     mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build()); 
    } 

} 

А вот файл PHP, который отправил сообщение ...

device_sendmsg.php

<?php 
if (isset($_POST["regId"]) && isset($_POST["message"])) { 
    $regId = $_POST["regId"]; 
    $message = $_POST["message"]; 

    include_once './gcm_sendmsg.php'; 

    $gcm = new GCM_SendMsg(); 

    $registatoin_ids = array($regId); 
    $message = array("message"=>$message, "timestamp"=>"04-01-2016"); 

    $result = $gcm->send_notification($registatoin_ids, $message); 

    echo $result; 
} 
?> 

gcm_sendmsg.php

<?php 

class GCM_SendMsg { 

    function __construct() { 

    } 

    /** 
    * send push notification 
    */ 
    public function send_notification($registatoin_ids, $message) { 

     include_once './config.php'; 

     // Set POST request variable 
     $url = 'https://android.googleapis.com/gcm/send'; 

     $fields = array(
      'registration_ids' => $registatoin_ids, 
      'data' => $message, 
     ); 

     $headers = array(
      'Authorization: key=' . GOOGLE_API_KEY, 
      'Content-Type: application/json' 
     ); 
     // Open connection 
     $ch = curl_init(); 

     // Set the url, number of POST vars, POST data 
     curl_setopt($ch, CURLOPT_URL, $url); 

     curl_setopt($ch, CURLOPT_POST, true); 
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); 
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); 

     // disable SSL certificate support 
     curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

     curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); 

     // execute post 
     $result = curl_exec($ch); 
     if ($result === FALSE) { 
      die('Curl failed: ' . curl_error($ch)); 
     } 

     // Close connection 
     curl_close($ch); 
     echo $result; 
    } 

} 

?> 

надежда кто-то может помочь мне^_^

+2

Это много кода ... см. [MCVE] (http://stackoverflow.com/help/mcve) –

ответ

0

Примечание: Вы должны использовать рекомендованную библиотеку GCM на андроид, игра-услуги -gcm доступна как часть Служб Google Play. См. Пример here.

К вашему конкретному вопросу: похоже, что вы получаете уведомление «в своем приложении», однако при получении вашего приложения генерируется системное уведомление.

Обратите внимание на метод onHandleIntent в вашем GCMIntentService, он вызывает метод sendNotification, который генерирует системное уведомление. Вы можете заменить вызов sendNotification с любым другим пользовательским поведением, которое вы хотите получить после получения сообщения.

Смежные вопросы