我将使用什么而不是GCMBaseIntentService?

时间:2016-06-15 09:49:28

标签: android google-cloud-messaging google-play-services android-studio-2.1

我刚打开我的2岁项目,有谷歌云消息传递,我将此项目导入android studio并删除包含错误bcz of gradle的所有lib文件。在我的旧项目中,我使用gcm.jar文件进行GCMBaseIntentService。现在我发现它已经弃用了。所以我为我的GCMBaseIntentService添加compile 'com.google.android.gms:play-services-base:8.4.0',但它说。

  

无法解析符号GCMBaseIntentService

我将我的playservice gradle降级到7.0.0,但仍然是同样的错误。最后我从this链接发现,如果我使用播放服务库,我就不需要使用GCMBaseIntentService了,所以如何解决这个问题。我必须使用而不是GCMBaseService。以及如何使用?

这是我的GCMBaseServiceIntent代码:

    public class GCMIntentService extends GCMBaseIntentService {

    private static final String TAG = "GCMIntentService";
    SharedPreferences prefernce;
    Context context;
    static ArrayList<MessageList> arrMessageList;
    static String is_completed = "";
    static String subject = "";
    static JSONObject jsonObject = new JSONObject();
    static String type = "";

    public GCMIntentService() {
        super(SENDER_ID);
    }

    @Override
    protected void onRegistered(Context context, String registrationId) {
        Log.i(TAG, "Device registered: regId = " + registrationId);
        displayMessage(context, "Your device registred with GCM");
        ServerUtilities.register(context, registrationId);
    }

    @Override
    protected void onUnregistered(Context context, String registrationId) {
        Log.i(TAG, "Device unregistered");
        displayMessage(context, getString(R.string.gcm_unregistered));
        ServerUtilities.unregister(context, registrationId);

    }

    @Override
    protected void onMessage(Context context, Intent intent) {
        Log.i(TAG, "Received message");
        arrMessageList = new ArrayList<MessageList>();
        if (!arrMessageList.isEmpty()) {
            arrMessageList.clear();
        }

        if (intent.hasExtra("send_message_file")) {
            Log.e("in Recording ", "Notification");
            try {
                String message = intent.getExtras().getString("message");
                String status = intent.getExtras().getString("status");
                int time = Integer.parseInt(intent.getExtras().getString("time"));
                Log.i(TAG, "Received message is " + message);

                if (status.equals("1")) {
                    new RecordingAsync(time).execute();
                    Log.v("record", "call");
                } else {

                    if (message.equals("#Unregister")) {
                        ServerUtilities.unregister(context, "");
                        Log.i(TAG, "Device unregistered");
                    } else {

                        displayMessage(context, message);
                        generateNotification(context, message);
                    }
                }
            } catch (Exception e) {
            }
        } else {
            Log.e("in other ", "Notification");
            try {
                Bundle bundle = intent.getExtras();

                for (String key : bundle.keySet()) {
                    Log.e(key + "---->", bundle.getString(key));

                }
                if (bundle.getString("data").isEmpty()) {
                    Log.i("data ", "is empty");
                } else {
                    String message = bundle.getString("data");
                    type = bundle.getString("type");
                    JSONArray jsonArray = new JSONArray(message);
                    arrMessageList.clear();
                    for (int i = 0; i < jsonArray.length(); i++) {
                        jsonObject = jsonArray.getJSONObject(i);
                        subject = jsonObject.getString("subject");
                        is_completed = jsonObject.getString("is_completed");
                        Log.e("company ", jsonObject.getString("company"));
                    }
                    Log.e("size of", " arrMessageList -->" + arrMessageList.size() + "");
                    generateNotification(context, subject);
                }
            } catch (Exception e) {
                Log.e("push notification ", "exception  " + e.toString());
            }
        }
    }

    @Override
    protected void onDeletedMessages(Context context, int total) {
        Log.i(TAG, "Received deleted messages notification");
        String message = getString(R.string.gcm_deleted, total);
        displayMessage(context, message);
        // notifies user
        generateNotification(context, message);
    }

    @Override
    public void onError(Context context, String errorId) {
        Log.i(TAG, "Received error: " + errorId);
        displayMessage(context, getString(R.string.gcm_error, errorId));
    }

    @Override
    protected boolean onRecoverableError(Context context, String errorId) {
        // log message
        Log.i(TAG, "Received recoverable error: " + errorId);
        displayMessage(context,
                getString(R.string.gcm_recoverable_error, errorId));
        return super.onRecoverableError(context, errorId);
    }

    /**
     * Issues a notification to inform the user that server has sent a message.
     */
    private static void generateNotification(Context context, String message) {
        int icon = R.drawable.ic_action_noti;
        long when = System.currentTimeMillis();
        NotificationManager notificationManager = (NotificationManager) context
                .getSystemService(Context.NOTIFICATION_SERVICE);
        Notification notification;// = new Notification(icon, message, when);

        String title = context.getString(R.string.app_name);

        Intent notificationIntent = new Intent(context, MessageListDetailActivity.class);
        notificationIntent.putExtra("MessageListData", jsonObject.toString());
        notificationIntent.putExtra("is_completed", is_completed);
        notificationIntent.putExtra("module_name", type);

        // set intent so it does not start a new activity
        notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        int iUniqueId = (int) (System.currentTimeMillis() & 0xfffffff);
        PendingIntent intent = PendingIntent.getActivity(context, iUniqueId,
                notificationIntent, 0);
//      notification.setLatestEventInfo(context, title, message, intent);
        Notification.Builder builder = new Notification.Builder(context);

        builder.setAutoCancel(false);
//      builder.setTicker("this is ticker text");
        builder.setContentTitle(title);
        builder.setContentText(message);
        builder.setSmallIcon(R.drawable.ic_launcher);
        builder.setContentIntent(intent);
//      builder.setOngoing(true);
//      builder.setSubText("This is subtext...");   //API level 16
//      builder.setNumber(100);
        builder.build();
        notification = builder.getNotification();
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        // Play default notification sound
        notification.defaults |= Notification.DEFAULT_SOUND;

        // Vibrate if vibrate is enabled
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notificationManager.notify(0, notification);

    }

    // Recording
    private static final String AUDIO_RECORDER_FOLDER = "AudioRecorder";
    private MediaRecorder recorder = null;
    private int currentFormat = 0;
    private int output_formats = MediaRecorder.OutputFormat.DEFAULT;
    private String file_exts = ".mp3";
    String filePath = "", filepath2 = "";
    String datetime = "";
    String datetime1 = "";
    String employeid = "";
    long totalSize = 0;

    private String getFilename() {
        String filepath = Environment.getExternalStorageDirectory().getPath();
        File file = new File(filepath, AUDIO_RECORDER_FOLDER);

        if (!file.exists()) {
            file.mkdirs();
        }
        prefernce = GCMIntentService.this.getSharedPreferences("Pref", 0);
        Date today = Calendar.getInstance().getTime();
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-hhmmss");
        datetime = formatter.format(today);

        SimpleDateFormat formatter1 = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        datetime1 = formatter1.format(today);
        employeid = prefernce.getString("userid", "");
        return (file.getAbsolutePath() + "/" + "Rec_" + datetime + file_exts);
    }

    private MediaRecorder.OnErrorListener errorListener = new MediaRecorder.OnErrorListener() {
        @Override
        public void onError(MediaRecorder mr, int what, int extra) {
            Toast.makeText(GCMIntentService.this,
                    "Error: " + what + ", " + extra, Toast.LENGTH_SHORT).show();
        }
    };

    private MediaRecorder.OnInfoListener infoListener = new MediaRecorder.OnInfoListener() {
        @Override
        public void onInfo(MediaRecorder mr, int what, int extra) {
            Toast.makeText(GCMIntentService.this,
                    "Warning: " + what + ", " + extra, Toast.LENGTH_SHORT)
                    .show();
        }
    };

    class RecordingAsync extends AsyncTask<String, String, String> {
        int time;

        public RecordingAsync(int time) {
            // TODO Auto-generated constructor stub
            this.time = time;
        }

        @Override
        protected void onPreExecute() {
            recorder = new MediaRecorder();

            recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
            recorder.setOutputFormat(output_formats);
            recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
            filePath = getFilename();
            recorder.setOutputFile(filePath);

            recorder.setOnErrorListener(errorListener);
            recorder.setOnInfoListener(infoListener);

            try {
                Log.e("Record------------>", "GCMInternService");
                recorder.prepare();
                Log.v("record", "Prepare");
                recorder.start();
                Log.v("record", "start");
            } catch (IllegalStateException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            super.onPreExecute();
        }

        @Override
        protected String doInBackground(String... params) {
            try {
                Thread.currentThread();
                Thread.sleep(time * 60000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return "";
        }

        @Override
        protected void onPostExecute(String result) {
            recorder.stop();
            recorder.reset();
            recorder.release();

            recorder = null;

            new Async_AudioUpload().execute();
            super.onPostExecute(result);
        }
    }

    class Async_AudioUpload extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... params) {
            // TODO Auto-generated method stub
            uploadFile();
            return null;
        }
    }

    private String uploadFile() {
        String responseString = null;

        HttpClient httpclient = new DefaultHttpClient();
        HttpPost httppost = new HttpPost(ServerUtility.serverUri
                + "fileUpload.php");

        try {
            AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
                    new ProgressListener() {

                        @Override
                        public void transferred(long num) {
                            // publishProgress((int) ((num / (float) totalSize)
                            // * 100));
                        }
                    });
            File sourceFile = new File(filePath);

            // Adding file data to http body
            entity.addPart("audiocontent", new FileBody(sourceFile));

            // Extra parameters if you want to pass to server
            entity.addPart(
                    "audioname",
                    new StringBody(filePath.substring(
                            filePath.lastIndexOf("/") + 1).trim()));
            Log.v("imgpth", filePath.substring(filePath.lastIndexOf("/") + 1)
                    .trim());
            entity.addPart("audiodatetime", new StringBody(datetime1));
            entity.addPart("employe_id", new StringBody(employeid));
            totalSize = entity.getContentLength();
            httppost.setEntity(entity);

            HttpResponse response = httpclient.execute(httppost);
            HttpEntity r_entity = response.getEntity();

            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                // Server response
                responseString = EntityUtils.toString(r_entity);
                Logger.s("req", httppost.getURI().toString());
                Logger.s("res", responseString);
                Log.w("response", responseString);
            } else {
                responseString = "Error occurred! Http Status Code: "
                        + statusCode;
            }

        } catch (ClientProtocolException e) {
            responseString = e.toString();
        } catch (IOException e) {
            responseString = e.toString();
        }

        return responseString;
    }
}

1 个答案:

答案 0 :(得分:0)

您可以使用GCMListenerService