从活动中启动BroadcastReceiver

时间:2015-03-28 11:13:36

标签: android android-intent android-manifest android-broadcast

我试图从一个活动中启动一个BroadcastReceiver - 看起来接收器没有启动,我在logCat中没有得到任何输出。 我试图通过这样做来启动接收器:

  Intent intent = new Intent();
                intent.setAction(getPackageName()+".mybroadcast");
                sendBroadcast(intent);

这里也是我的接收器类:

public class TriggerReceiver extends BroadcastReceiver implements
        GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener {

    private Vibrator v;

    private CountDownTimer timer;
    private final long INTERVAL = 1000;
    private final long TWO_MINUTES = INTERVAL * 60 * 2;

    // === variables


    private Context context;
    private final String TAG = TriggerReceiver.class.getSimpleName();

    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;

        Log.e(TAG, "Trigger receiver starting");

        v = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
        mRequestingLocationUpdates = false;
        buildGoogleApiClient();
        mGoogleApiClient.connect();
    }

    //

    private void startTimer(final Location location) {
        String message = context.getString(R.string.emergency_text).replace("/location here/", getMapLink(location));
        sendSMS(message);
        showNotification();
        Log.e(TAG, " sending sms and this is the location " + location.getLatitude() + " " + location.getLongitude());

        timer = new CountDownTimer(TWO_MINUTES, INTERVAL) {

            @Override
            public void onTick(long millisUntilFinished) {
                Log.e(TAG, "Tick " + (millisUntilFinished / 1000));
                int elapsedTime = (int) ((millisUntilFinished / 1000) % 60);
                int minutes = (int) ((millisUntilFinished / 1000) / 60);
                Log.e(TAG, elapsedTime + " | " + minutes);

                if (minutes == 2) {
                    minutes = 1;
                    elapsedTime = 60;
                }
            }

            //TODO start activity and pass extras to intent
            @Override
            public void onFinish() {
                startTimer(mCurrentLocation);
            }
        }.start();
    }

    private void sendSMS(String message) {
        ArrayList<Contact> contacts = ((BaseActivity) context).getContacts();
        for (Contact contact : contacts) {
            sendSMSmsg(contact.getNumber(), message);
        }
    }

    private void stopTimer() {
        timer.cancel();
    }

    /*location*/


    /**
     * Provides the entry point to Google Play services.
     */
    protected GoogleApiClient mGoogleApiClient;

    /**
     * Stores parameters for requests to the FusedLocationProviderApi.
     */
    protected LocationRequest mLocationRequest, quickLocationRequest;

    /**
     * Represents a geographical location.
     */
    protected Location mCurrentLocation, mLastLocation;

    protected Boolean mRequestingLocationUpdates;

    /**
     * Builds a GoogleApiClient. Uses the {@code #addApi} method to request the
     * LocationServices API.
     */
    protected synchronized void buildGoogleApiClient() {
        Log.i(TAG, "Building GoogleApiClient");

        mGoogleApiClient = new GoogleApiClient.Builder(context)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        createLocationRequest();
    }

    protected void createLocationRequest() {
        LocationRequest mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(110000);
        mLocationRequest.setFastestInterval(55000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    }

    protected void startLocationUpdates() {
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, mLocationRequest, this);
    }

    protected void doQuickLocationUpdate() {

        quickLocationRequest = new LocationRequest();
        quickLocationRequest.setInterval(1000);
        quickLocationRequest.setFastestInterval(500);
        quickLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        // The final argument to {@code requestLocationUpdates()} is a LocationListener
        // (http://developer.android.com/reference/com/google/android/gms/location/LocationListener.html).
        LocationServices.FusedLocationApi.requestLocationUpdates(
                mGoogleApiClient, quickLocationRequest, this);
    }


    protected void stopLocationUpdates() {
        //TODO add this in onbackpresses and onStop
        LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
    }

    @Override
    public void onConnected(Bundle connectionHint) {
        Log.i(TAG, "Connected to GoogleApiClient");

        mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {
            startTimer(mLastLocation);
        } else {
            doQuickLocationUpdate();
        }

        if (mCurrentLocation == null) {
            mCurrentLocation = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
            Log.d(TAG, "onConnected mCurrentLocation = " + mCurrentLocation.getLatitude());

        }

        if (mRequestingLocationUpdates) {
            startLocationUpdates();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        mCurrentLocation = location;
        if (quickLocationRequest != null) {
            quickLocationRequest = null;
        }
        if (timer == null) {
            startTimer(location);
        }
        Log.d(TAG, "onLocationChanged mCurrentLocation = " + mCurrentLocation.getLatitude());
    }

    @Override
    public void onConnectionSuspended(int cause) {
        // The connection to Google Play services was lost for some reason. We call connect() to
        // attempt to re-establish the connection.
        Log.i(TAG, "Connection suspended");
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnectionFailed(ConnectionResult result) {
        // Refer to the javadoc for ConnectionResult to see what error codes might be returned in
        // onConnectionFailed.
        Log.i(TAG, "Connection failed: ConnectionResult.getErrorCode() = " + result.getErrorCode());
    }


    public void sendSMSmsg(String phoneNumber, String message) {

        v.vibrate(50);
//        ArrayList<PendingIntent> sentPendingIntents = new ArrayList<PendingIntent>();
//        ArrayList<PendingIntent> deliveredPendingIntents = new ArrayList<PendingIntent>();
//        PendingIntent sentPI = PendingIntent.getBroadcast(context, 0,
//                new Intent(context, SmsSentReceiver.class), 0);
//        PendingIntent deliveredPI = PendingIntent.getBroadcast(context, 0,
//                new Intent(context, SmsDeliveredReceiver.class), 0);
//        try {
//            SmsManager sms = SmsManager.getDefault();
//            ArrayList<String> mSMSMessage = sms.divideMessage(message);
//            for (int i = 0; i < mSMSMessage.size(); i++) {
//                sentPendingIntents.add(i, sentPI);
//                deliveredPendingIntents.add(i, deliveredPI);
//            }
//            sms.sendMultipartTextMessage(phoneNumber, null, mSMSMessage,
//                    sentPendingIntents, deliveredPendingIntents);
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    public void showNotification() {
        NotificationCompat.Builder mBuilder;
        if (Build.VERSION.SDK_INT >= 16) {
            mBuilder = new NotificationCompat.Builder(context)
                    .setSmallIcon(R.mipmap.sosicon)
                    .setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION))
                    .setContentTitle(context.getString(R.string.app_name))
                    .setAutoCancel(true)
                    .setContentText(context.getString(R.string.notification_text));
            // Creates an explicit intent for an Activity in your app
            Intent resultIntent = new Intent();
            TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
            stackBuilder.addNextIntent(resultIntent);
            PendingIntent resultPendingIntent =
                    stackBuilder.getPendingIntent(
                            0,
                            PendingIntent.FLAG_UPDATE_CURRENT
                    );
            mBuilder.setContentIntent(resultPendingIntent);
            NotificationManager mNotificationManager =
                    (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
            mNotificationManager.notify(10142, mBuilder.build());
        }
    }

    public String getMapLink(Location location) {
        if (location != null) {
            Log.d(TAG, "http://maps.google.com/maps?z=12&t=m&q=loc:" + location.getLatitude() + "+" + location.getLongitude());
            return "http://maps.google.com/maps?z=12&t=m&q=loc:" + location.getLatitude() + "+" + location.getLongitude();
        } else {
            return null;
        }
    }

    //
}

以及清单中的声明:

<receiver
            android:name=".TriggerReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="PACKAGENAME.mybroadcast" />
            </intent-filter>
        </receiver>

那么这里可能出现什么问题以及为什么接收器无法启动?

由于

0 个答案:

没有答案