Запуск службы и автоматический вход из IntentService

У меня есть IntentService ниже, который должен запустить MessagingService.class, а затем автоматически войти в приложение и отправить уведомление. В настоящее время при получении сообщения GCM отправляется уведомление, но больше ничего, даже сообщения Toast в ранней части IntentService не появляются.

Почему это так?

ИнтентСервис:

public class GCMIntentService extends IntentService {

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

    // Logging stuff:
    protected static final int NOT_CONNECTED_TO_SERVICE = 0;
    protected static final int FILL_BOTH_USERNAME_AND_PASSWORD = 1;
    public static final String AUTHENTICATION_FAILED = "0";
    public static final String FRIEND_LIST = "FRIEND_LIST";
    protected static final int MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT = 2;
    protected static final int NOT_CONNECTED_TO_NETWORK = 3;

    private Manager imService;
    public static final int SIGN_UP_ID = Menu.FIRST;
    public static final int EXIT_APP_ID = Menu.FIRST + 1;

    // For GCM
    String regid;
    GoogleCloudMessaging gcm;
    AtomicInteger msgId = new AtomicInteger();
    SharedPreferences prefs;
    Context context;

    public static final String EXTRA_MESSAGE = "message";
    public static final String PROPERTY_REG_ID = "registration_id";
    private static final String PROPERTY_APP_VERSION = "appVersion";
    private final static int PLAY_SERVICES_RESOLUTION_REQUEST = 9000;
    // END logging in


    public GCMIntentService() {
        super("GcmIntentService");
    }

    public static final String TAG = "GCMNotificationIntentService";

    @Override
    protected void onHandleIntent(Intent intent) {

        // Start my service for messages:
        Intent beginMessageService = new Intent(getBaseContext(), MessagingService.class);
        startService(beginMessageService);

        // Try to log in:
        Toast.makeText(getApplicationContext(), "Successfully Relieved Feast GCM", Toast.LENGTH_LONG).show();

        // and log in automatically:
        //If not logged in already nad shared preferences exists as already logged in once:
        if (!SaveSharedPreference.getUserName(getApplicationContext()).isEmpty()) {

            //startService(new Intent(this, MessagingService.class));

            final String userName = SaveSharedPreference.getUserName(getApplicationContext());

            final String password = SaveSharedPreference.getPassword(getApplicationContext());

            Toast.makeText(getApplicationContext(), "SharedPref Username is " + userName + " and password " + password, Toast.LENGTH_LONG).show();

            Toast.makeText(getApplicationContext(), "The value of imService is: " + getApplicationContext(), Toast.LENGTH_LONG).show();

            if (imService == null) {
                Toast.makeText(getApplicationContext(),
                        R.string.not_connected_to_service,
                        Toast.LENGTH_LONG).show();
                // showDialog(NOT_CONNECTED_TO_SERVICE);
                //return;
            } else if (imService.isNetworkConnected() == false) {
                Toast.makeText(getApplicationContext(),
                        R.string.not_connected_to_network,
                        Toast.LENGTH_LONG).show();
                // showDialog(NOT_CONNECTED_TO_NETWORK);

            } else {

                Toast.makeText(getApplicationContext(), "SharedPref Username is " + userName + " and password " + password, Toast.LENGTH_LONG).show();

                Thread loginThread = new Thread() {
                    private Handler handler = new Handler();

                    @Override
                    public void run() {
                        String result = null;

                        try {
                            result = imService.authenticateUser(
                                    userName.trim(),
                                    password.trim());
                        } catch (UnsupportedEncodingException e) {

                            e.printStackTrace();
                        }
                        if (result == null
                                || result.equals(AUTHENTICATION_FAILED)) {
                                      /*
                                       * Authenticatin failed, inform the user
                                       */
                            handler.post(new Runnable() {
                                public void run() {
                                    Toast.makeText(
                                            getApplicationContext(),
                                            R.string.make_sure_username_and_password_correct,
                                            Toast.LENGTH_LONG).show();

                                    // showDialog(MAKE_SURE_USERNAME_AND_PASSWORD_CORRECT);
                                }
                            });

                        } else {                                      /*
                                       * if result not equal to authentication failed,
                                       * result is equal to friend and group list of
                                       * the user 0: is for friends, 1: is for groups
                                       */

                        }

                    }
                };
                loginThread.start();

            }


            //setResultCode(Activity.RESULT_OK);
        }

        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);

        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {
            if (GoogleCloudMessaging.MESSAGE_TYPE_SEND_ERROR
                    .equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_DELETED
                    .equals(messageType)) {
                sendNotification("Deleted messages on server: "
                        + extras.toString());
            } else if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE
                    .equals(messageType)) {

                for (int i = 0; i < 3; i++) {
                    Log.i(TAG,
                            "Working... " + (i + 1) + "/5 @ "
                                    + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }

                }

                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());

                sendNotification("Message Received from Google GCM Server: "
                        + extras.get(Config.MESSAGE_KEY));
                Log.i(TAG, "Received: " + extras.toString());

                // Start the background service:


                // Auto log the user in based on store preferences:



            }
        }
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    private void sendNotification(String msg) {
        Log.d(TAG, "Preparing to send notification...: " + msg);
        mNotificationManager = (NotificationManager) this
                .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.drawable.gcm_cloud)
                .setContentTitle("GCM Notification")
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg))
                .setContentText(msg);

        mBuilder.setContentIntent(contentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mBuilder.build());
        Log.d(TAG, "Notification sent successfully.");
    }
}

person Sauron    schedule 25.04.2015    source источник
comment
У вашей службы не будет доступа к потоку пользовательского интерфейса. Рассмотрите возможность использования операторов Log вместо оператора Toast. См. этот ответ: stackoverflow.com/a/21516064/1832900   -  person akodiakson    schedule 25.04.2015
comment
Можете ли вы вставить свой файл манифеста? Также убедитесь, что вы поместили свой GCMIntentService в основную папку. Не помещайте его ни в какую подпапку, и он будет работать.   -  person AniV    schedule 30.04.2015