android.app.PendingIntent Java Examples

The following examples show how to use android.app.PendingIntent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: VideoCastNotificationService.java    From android with Apache License 2.0 6 votes vote down vote up
private void addPendingIntents(RemoteViews rv, boolean isPlaying, MediaInfo info) {
    Intent playbackIntent = new Intent(ACTION_TOGGLE_PLAYBACK);
    playbackIntent.setPackage(getPackageName());
    PendingIntent playbackPendingIntent = PendingIntent
            .getBroadcast(this, 0, playbackIntent, 0);

    Intent stopIntent = new Intent(ACTION_STOP);
    stopIntent.setPackage(getPackageName());
    PendingIntent stopPendingIntent = PendingIntent.getBroadcast(this, 0, stopIntent, 0);

    rv.setOnClickPendingIntent(R.id.playPauseView, playbackPendingIntent);
    rv.setOnClickPendingIntent(R.id.removeView, stopPendingIntent);

    if (isPlaying) {
        if (info.getStreamType() == MediaInfo.STREAM_TYPE_LIVE) {
            rv.setImageViewResource(R.id.playPauseView, R.drawable.ic_av_stop_sm_dark);
        } else {
            rv.setImageViewResource(R.id.playPauseView, R.drawable.ic_av_pause_sm_dark);
        }

    } else {
        rv.setImageViewResource(R.id.playPauseView, R.drawable.ic_av_play_sm_dark);
    }
}
 
Example #2
Source File: NotificationUtils.java    From GeometricWeather with GNU Lesser General Public License v3.0 6 votes vote down vote up
private static Notification buildAlertGroupSummaryNotification(Context context,
                                                               Location location,
                                                               Alert alert,
                                                               int notificationId) {
    return new NotificationCompat.Builder(context, GeometricWeather.NOTIFICATION_CHANNEL_ID_ALERT)
            .setSmallIcon(R.drawable.ic_alert)
            .setContentTitle(alert.getDescription())
            .setGroup(NOTIFICATION_GROUP_KEY)
            .setColor(
                    ContextCompat.getColor(
                            context,
                            TimeManager.getInstance(context).isDayTime()
                                    ? R.color.lightPrimary_5
                                    : R.color.darkPrimary_5
                    )
            ).setGroupSummary(true)
            .setOnlyAlertOnce(true)
            .setContentIntent(
                    PendingIntent.getActivity(
                            context,
                            notificationId,
                            IntentHelper.buildMainActivityShowAlertsIntent(location),
                            PendingIntent.FLAG_UPDATE_CURRENT
                    )
            ).build();
}
 
Example #3
Source File: NotificationState.java    From mollyim-android with GNU General Public License v3.0 6 votes vote down vote up
public PendingIntent getMarkAsReadIntent(Context context, int notificationId) {
  long[] threadArray = new long[threads.size()];
  int    index       = 0;

  for (long thread : threads) {
    Log.i(TAG, "Added thread: " + thread);
    threadArray[index++] = thread;
  }

  Intent intent = new Intent(MarkReadReceiver.CLEAR_ACTION);
  intent.setClass(context, MarkReadReceiver.class);
  intent.setData((Uri.parse("custom://"+System.currentTimeMillis())));
  intent.putExtra(MarkReadReceiver.THREAD_IDS_EXTRA, threadArray);
  intent.putExtra(MarkReadReceiver.NOTIFICATION_ID_EXTRA, notificationId);

  return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
}
 
Example #4
Source File: ActivityRecognizedService.java    From xDrip with GNU General Public License v3.0 6 votes vote down vote up
private static void disableMotionTrackingDueToErrors(Context context) {
    final long requested = getInternalPrefsLong(REQUESTED);
    final long received = getInternalPrefsLong(RECEIVED);
    Home.toaststaticnext("DISABLED MOTION TRACKING DUE TO FAILURES! See Error Log!");
    final String msg = "Had to disable motion tracking feature as it did not seem to be working and may be incompatible with your phone. Please report this to the developers using the send logs feature: " + requested + " vs " + received + " " + JoH.getDeviceDetails();
    UserError.Log.wtf(TAG, msg);
    UserError.Log.ueh(TAG, msg);
    Pref.setBoolean("motion_tracking_enabled", false);
    evaluateRequestReceivedCounters(true, context); // mark for disable
    setInternalPrefsLong(REQUESTED, 0);
    setInternalPrefsLong(RECEIVED, 0);
    final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);

    Intent intent = new Intent(xdrip.getAppContext(), ErrorsActivity.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(xdrip.getAppContext(), 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);
    builder.setContentText("Shut down motion detection! See Error Logs - Please report to developer" + JoH.dateTimeText(JoH.tsl()));
    builder.setContentIntent(pendingIntent);
    builder.setSmallIcon(R.drawable.ic_launcher);
    builder.setContentTitle("Problem with motion detection!");
    NotificationManagerCompat.from(context).notify(VEHICLE_NOTIFICATION_ERROR_ID, builder.build());
}
 
Example #5
Source File: SliceItem.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
private static Object readObj(String type, Parcel in) {
    switch (getBaseType(type)) {
        case FORMAT_SLICE:
            return Slice.CREATOR.createFromParcel(in);
        case FORMAT_TEXT:
            return TextUtils.CHAR_SEQUENCE_CREATOR.createFromParcel(in);
        case FORMAT_IMAGE:
            return Icon.CREATOR.createFromParcel(in);
        case FORMAT_ACTION:
            return new Pair<>(
                    PendingIntent.CREATOR.createFromParcel(in),
                    Slice.CREATOR.createFromParcel(in));
        case FORMAT_INT:
            return in.readInt();
        case FORMAT_TIMESTAMP:
            return in.readLong();
        case FORMAT_REMOTE_INPUT:
            return RemoteInput.CREATOR.createFromParcel(in);
        case FORMAT_BUNDLE:
            return Bundle.CREATOR.createFromParcel(in);
    }
    throw new RuntimeException("Unsupported type " + type);
}
 
Example #6
Source File: MessengerService.java    From codeexamples-android with Eclipse Public License 1.0 6 votes vote down vote up
/**
 * Show a notification while this service is running.
 */
private void showNotification() {
    // In this sample, we'll use the same text for the ticker and the expanded notification
    CharSequence text = getText(R.string.remote_service_started);

    // Set the icon, scrolling text and timestamp
    Notification notification = new Notification(R.drawable.stat_sample, text,
            System.currentTimeMillis());

    // The PendingIntent to launch our activity if the user selects this notification
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
            new Intent(this, Controller.class), 0);

    // Set the info for the views that show in the notification panel.
    notification.setLatestEventInfo(this, getText(R.string.remote_service_label),
                   text, contentIntent);

    // Send the notification.
    // We use a string id because it is a unique number.  We use it later to cancel.
    mNM.notify(R.string.remote_service_started, notification);
}
 
Example #7
Source File: NotificationPlatformBridge.java    From 365browser with Apache License 2.0 6 votes vote down vote up
/**
     * Returns the PendingIntent for completing |action| on the notification identified by the data
     * in the other parameters.
     *
     * All parameters set here should also be set in
     * {@link NotificationJobService#getJobExtrasFromIntent(Intent)}.
     *
     * @param context An appropriate context for the intent class and broadcast.
     * @param action The action this pending intent will represent.
     * @param notificationId The id of the notification.
     * @param origin The origin to whom the notification belongs.
     * @param profileId Id of the profile to which the notification belongs.
     * @param incognito Whether the profile was in incognito mode.
     * @param tag The tag of the notification. May be NULL.
     * @param webApkPackage The package of the WebAPK associated with the notification. Empty if
*        the notification is not associated with a WebAPK.
     * @param actionIndex The zero-based index of the action button, or -1 if not applicable.
     */
    private PendingIntent makePendingIntent(Context context, String action, String notificationId,
            String origin, String profileId, boolean incognito, @Nullable String tag,
            String webApkPackage, int actionIndex) {
        Uri intentData = makeIntentData(notificationId, origin, actionIndex);
        Intent intent = new Intent(action, intentData);
        intent.setClass(context, NotificationService.Receiver.class);
        intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_ID, notificationId);
        intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_ORIGIN, origin);
        intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_PROFILE_ID, profileId);
        intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_PROFILE_INCOGNITO, incognito);
        intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_TAG, tag);
        intent.putExtra(
                NotificationConstants.EXTRA_NOTIFICATION_INFO_WEBAPK_PACKAGE, webApkPackage);
        intent.putExtra(NotificationConstants.EXTRA_NOTIFICATION_INFO_ACTION_INDEX, actionIndex);

        return PendingIntent.getBroadcast(
                context, PENDING_INTENT_REQUEST_CODE, intent, PendingIntent.FLAG_UPDATE_CURRENT);
    }
 
Example #8
Source File: LessonsWidgetProvider_4_1.java    From zhangshangwuda with Apache License 2.0 6 votes vote down vote up
public void setNextAlarm(Context context) {
	AlarmManager aManager = (AlarmManager) context
			.getSystemService(Service.ALARM_SERVICE);
	Calendar tcalendar = Calendar.getInstance();
	tcalendar.setTimeInMillis(System.currentTimeMillis());
	tcalendar.add(Calendar.DAY_OF_YEAR, +1);
	tcalendar.set(Calendar.HOUR_OF_DAY, 0);
	tcalendar.set(Calendar.MINUTE, 19);
	tcalendar.set(Calendar.SECOND, 19);
	Intent intent = new Intent(context, LessonsWidgetProvider_4_1.class);
	intent.setAction("zq.whu.zhangshangwuda.ui.lessons.widget_4_1.today");
	PendingIntent work = PendingIntent.getBroadcast(context, 0, intent,
			PendingIntent.FLAG_UPDATE_CURRENT);
	aManager.cancel(work);
	aManager.set(AlarmManager.RTC, tcalendar.getTimeInMillis(), work);
	Log.v("zq.whu.zhangshangwuda.ui.lessons.widget_4_1", "设置定时更新成功");
}
 
Example #9
Source File: LocationActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
private void listing15_8() {
  if (
    ActivityCompat
      .checkSelfPermission(this, ACCESS_FINE_LOCATION) == PERMISSION_GRANTED ||
      ActivityCompat
        .checkSelfPermission(this, ACCESS_COARSE_LOCATION) == PERMISSION_GRANTED) {

    // Listing 15-8: Requesting location updates using a Pending Intent
    FusedLocationProviderClient fusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    LocationRequest request = new LocationRequest()
                                .setInterval(60000 * 10) // Update every 10 minutes.
                                .setPriority(LocationRequest.PRIORITY_NO_POWER);

    final int locationUpdateRC = 0;
    int flags = PendingIntent.FLAG_UPDATE_CURRENT;

    Intent intent = new Intent(this, MyLocationUpdateReceiver.class);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(this, locationUpdateRC, intent, flags);

    fusedLocationClient.requestLocationUpdates(request, pendingIntent);
  }
}
 
Example #10
Source File: DesignerNewsStory.java    From android-proguards with Apache License 2.0 6 votes vote down vote up
public static CustomTabsIntent.Builder getCustomTabIntent(@NonNull Context context,
                                                          @NonNull Story story,
                                                          @Nullable CustomTabsSession session) {
    Intent upvoteStory = new Intent(context, UpvoteStoryService.class);
    upvoteStory.setAction(UpvoteStoryService.ACTION_UPVOTE);
    upvoteStory.putExtra(UpvoteStoryService.EXTRA_STORY_ID, story.id);
    PendingIntent pendingIntent = PendingIntent.getService(context, 0, upvoteStory, 0);
    return new CustomTabsIntent.Builder(session)
            .setToolbarColor(ContextCompat.getColor(context, R.color.designer_news))
            .setActionButton(ImageUtils.vectorToBitmap(context,
                            R.drawable.ic_upvote_filled_24dp_white),
                    context.getString(R.string.upvote_story),
                    pendingIntent,
                    false)
            .setShowTitle(true)
            .enableUrlBarHiding()
            .addDefaultShareMenuItem();
}
 
Example #11
Source File: NotificationReceiver.java    From fanfouapp-opensource with Apache License 2.0 6 votes vote down vote up
private static void showMentionMoreNotification(final Context context,
        final int count) {
    if (AppContext.DEBUG) {
        Log.d(NotificationReceiver.TAG,
                "showMentionMoreNotification count=" + count);
    }
    final String title = "饭否消息";
    final String message = "收到" + count + "条提到你的消息";
    final Intent intent = new Intent(context, HomePage.class);
    intent.setAction("DUMY_ACTION " + System.currentTimeMillis());
    intent.putExtra(Constants.EXTRA_PAGE, 1);
    final PendingIntent contentIntent = PendingIntent.getActivity(context,
            0, intent, 0);
    NotificationReceiver.showNotification(
            NotificationReceiver.NOTIFICATION_ID_MENTION, context,
            contentIntent, title, message, R.drawable.ic_notify_mention);
}
 
Example #12
Source File: MainTest.java    From json2notification with Apache License 2.0 6 votes vote down vote up
@Test
public void testSerialize() {
    Intent intent = new Intent(Intent.ACTION_MAIN);
    intent.addCategory(Intent.CATEGORY_HOME);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

    Notification notification = new NotificationCompat.Builder(context)
        .setContentTitle("Hello World!")
        .setContentText("Hello World!")
        .setContentIntent(PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT))
        .build();

    String json = Json2Notification.from(context).with(notification).serialize();
    System.out.println(json);
    assertThat(json).isNotNull();
}
 
Example #13
Source File: DummyActivity.java    From Shelter with Do What The F*ck You Want To Public License 6 votes vote down vote up
private void actionInstallPackageQ(Uri uri) throws IOException {
    PackageInstaller pi = getPackageManager().getPackageInstaller();
    PackageInstaller.SessionParams params = new PackageInstaller.SessionParams(
            PackageInstaller.SessionParams.MODE_FULL_INSTALL);
    int sessionId = pi.createSession(params);

    // Show the progress dialog first
    pi.registerSessionCallback(new InstallationProgressListener(this, pi, sessionId));

    PackageInstaller.Session session = pi.openSession(sessionId);
    doInstallPackageQ(uri, session, () -> {
        // We have finished piping the streams, show the progress as 10%
        session.setStagingProgress(0.1f);

        // Commit the session
        Intent intent = new Intent(this, DummyActivity.class);
        intent.setAction(PACKAGEINSTALLER_CALLBACK);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
                intent, PendingIntent.FLAG_UPDATE_CURRENT);
        session.commit(pendingIntent.getIntentSender());
    });
}
 
Example #14
Source File: NotificationVirtualSensor.java    From gsn with GNU General Public License v3.0 6 votes vote down vote up
public void sendBasicNotification(String notif) {

		NotificationManager nm = (NotificationManager) StaticData.globalContext.getSystemService(Context.NOTIFICATION_SERVICE);
		int icon = R.drawable.alert_dark_frame;
		CharSequence contentTitle = "TinyGSN notification";
		CharSequence tickerText = notif;
		long when = System.currentTimeMillis();

		NotificationCompat.Builder mBuilder =
				new NotificationCompat.Builder(StaticData.globalContext)
						.setSmallIcon(icon)
						.setContentTitle(contentTitle)
						.setContentText(tickerText);

		Intent notificationIntent = new Intent(StaticData.globalContext, ActivityViewData.class);

		TaskStackBuilder stackBuilder = TaskStackBuilder.create(StaticData.globalContext);
		stackBuilder.addParentStack(ActivityViewData.class);
		stackBuilder.addNextIntent(notificationIntent);

		PendingIntent contentIntent = PendingIntent.getActivity(StaticData.globalContext, 0,
				                                                       notificationIntent, 0);
		mBuilder.setContentIntent(contentIntent);
		mBuilder.setAutoCancel(true);
		nm.notify(notify_id++, mBuilder.build());
	}
 
Example #15
Source File: GcmListenerSvc.java    From xDrip-plus with GNU General Public License v3.0 6 votes vote down vote up
private void sendNotification(String body, String title) {
    Intent intent = new Intent(this, Home.class);
    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

    Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Notification.Builder notificationBuilder = (Notification.Builder) new Notification.Builder(this)
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentTitle(title)
            .setContentText(body)
            .setAutoCancel(true)
            .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

    NotificationManager notificationManager =
            (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

    notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
 
Example #16
Source File: MyActivity.java    From Wrox-ProfessionalAndroid-4E with Apache License 2.0 6 votes vote down vote up
private void listing11_24(Context context, NotificationCompat.Builder builder) {
  Uri emailUri = Uri.parse("[email protected]");

  // Listing 11-24: Adding a Notification action
  Intent deleteAction = new Intent(context, DeleteBroadcastReceiver.class);

  deleteAction.setData(emailUri);
  PendingIntent deleteIntent = PendingIntent.getBroadcast(context, 0,
    deleteAction, PendingIntent.FLAG_UPDATE_CURRENT);

  builder.addAction(
    new NotificationCompat.Action.Builder(
      R.drawable.delete,
      context.getString(R.string.delete_action),
      deleteIntent).build());
}
 
Example #17
Source File: ApiTwentySixPlus.java    From linphone-android with GNU General Public License v3.0 6 votes vote down vote up
public static Notification createSimpleNotification(
        Context context, String title, String text, PendingIntent intent) {
    return new Notification.Builder(
                    context, context.getString(R.string.notification_channel_id))
            .setContentTitle(title)
            .setContentText(text)
            .setSmallIcon(R.drawable.linphone_logo)
            .setAutoCancel(true)
            .setContentIntent(intent)
            .setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
            .setCategory(Notification.CATEGORY_MESSAGE)
            .setVisibility(Notification.VISIBILITY_PRIVATE)
            .setPriority(Notification.PRIORITY_HIGH)
            .setWhen(System.currentTimeMillis())
            .setShowWhen(true)
            .setColorized(true)
            .setColor(context.getColor(R.color.notification_led_color))
            .build();
}
 
Example #18
Source File: NotificationChannel.java    From Shipr-Community-Android with GNU General Public License v3.0 5 votes vote down vote up
private void Notify() {
    Intent intent = new Intent(context, MainActivity.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    final PendingIntent pendingIntent = PendingIntent.getActivity(context, (int) Calendar.getInstance().getTimeInMillis(), intent, 0);

    NotificationCompat.InboxStyle inboxStyle = new NotificationCompat.InboxStyle();
    inboxStyle.setBigContentTitle(channel_Id + " channel");

    for (int i = (messages.size() > 5 ? messages.size() - 5 : 0); i < messages.size(); i++) {
        DeveloperMessage message = messages.get(i);
        String line = message.getName() + ":\t" + message.getText();
        inboxStyle.addLine(line);
    }

    int count = messages.size();
    String summary = count + (count > 1 ? " new messages" : " new message");
    inboxStyle.setSummaryText(summary);
    //Todo: change the small icon with an xml icon
    NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel_Id)
            .setSmallIcon(R.mipmap.ic_launcher) //Todo: change the small icon with an xml icon
            .setStyle(inboxStyle)
            .setContentIntent(pendingIntent)
            .setContentTitle(channel_Id + " channel")
            .setContentText(summary);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        android.app.NotificationChannel notificationChannel = new android.app.NotificationChannel(channel_Id, "Maker Toolbox", NotificationManager.IMPORTANCE_DEFAULT);
        notificationManager.createNotificationChannel(notificationChannel);
    }

    notificationManager.notify(id, builder.build());
}
 
Example #19
Source File: RingerModeTracker.java    From Easer with GNU General Public License v3.0 5 votes vote down vote up
RingerModeTracker(Context context, RingerModeConditionData data,
               @NonNull PendingIntent event_positive,
               @NonNull PendingIntent event_negative) {
    super(context, data, event_positive, event_negative);
    this.condition = data;
    this.am = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
}
 
Example #20
Source File: TasksUtils.java    From FreezeYou with Apache License 2.0 5 votes vote down vote up
private static void setTask(AlarmManager alarmManager, long triggerAtMillis, PendingIntent operation) {//RTC
    if (Build.VERSION.SDK_INT >= 23) {
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation);
    } else if (Build.VERSION.SDK_INT >= 19) {
        alarmManager.setExact(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation);
    } else {
        alarmManager.set(AlarmManager.RTC_WAKEUP, triggerAtMillis, operation);
    }
}
 
Example #21
Source File: TimeSynchronizationService.java    From SightRemote with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (serviceConnector.isConnectedToService()) {
        serviceConnector.connect();
        if (serviceConnector.getStatus() == Status.CONNECTED)
            onStatusChange(Status.CONNECTED, 0, 0);
    }
    Intent serviceIntent = new Intent(this, TimeSynchronizationService.class);
    pendingIntent = PendingIntent.getService(this, 0, serviceIntent, 0);
    alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + 60 * 60 * 1000, pendingIntent);
    return START_STICKY;
}
 
Example #22
Source File: AccountWidgetProvider.java    From CSipSimple with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Creates PendingIntent to notify the widget of a button click.
 *
 * @param context
 * @param accId
 * @return
 */
private static PendingIntent getLaunchPendingIntent(Context context, long accId, boolean activate ) {
    Intent launchIntent = new Intent(SipManager.INTENT_SIP_ACCOUNT_ACTIVATE);
    launchIntent.putExtra(SipProfile.FIELD_ID, accId);
    launchIntent.putExtra(SipProfile.FIELD_ACTIVE, activate);
    Log.d(THIS_FILE, "Create intent "+activate);
    PendingIntent pi = PendingIntent.getBroadcast(context, (int)accId,
            launchIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    return pi;
}
 
Example #23
Source File: OktaManagementActivity.java    From okta-sdk-appauth-android with Apache License 2.0 5 votes vote down vote up
private void sendPendingIntent(PendingIntent pendingIntent) {
    try {
        pendingIntent.send();
    } catch (PendingIntent.CanceledException e) {
        Log.e(TAG, "Unable to send intent", e);
    }
    finish();
}
 
Example #24
Source File: GCMRegistrar.java    From divide with Apache License 2.0 5 votes vote down vote up
static void internalRegister(Context context, String... senderIds) {
    String flatSenderIds = getFlatSenderIds(senderIds);
    Log.v(TAG, "Registering app "  + context.getPackageName() +
            " of senders " + flatSenderIds);
    Intent intent = new Intent(GCMConstants.INTENT_TO_GCM_REGISTRATION);
    intent.setPackage(GSF_PACKAGE);
    intent.putExtra(GCMConstants.EXTRA_APPLICATION_PENDING_INTENT,
            PendingIntent.getBroadcast(context, 0, new Intent(), 0));
    intent.putExtra(GCMConstants.EXTRA_SENDER, flatSenderIds);
    context.startService(intent);
}
 
Example #25
Source File: PeriodicReplicationService.java    From sync-android with Apache License 2.0 5 votes vote down vote up
/** Start periodic replications. */
public synchronized void startPeriodicReplication() {
    if (!isPeriodicReplicationEnabled()) {
        setPeriodicReplicationEnabled(true);
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent alarmIntent = new Intent(this, clazz);
        alarmIntent.setAction(PeriodicReplicationReceiver.ALARM_ACTION);
        // We need to use a BroadcastReceiver rather than sending the Intent directly to the
        // Service to ensure the device wakes up if it's asleep. Sending the Intent directly
        // to the Service would be unreliable.
        PendingIntent pendingAlarmIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);

        long initialTriggerTime;
        if (explicitlyStopped()) {
            // Replications were explicitly stopped, so we want the first replication to
            // happen immediately.
            initialTriggerTime = SystemClock.elapsedRealtime();
            setExplicitlyStopped(false);
        } else {
            // Replications were implicitly stopped (e.g. by rebooting the device), so we
            // want to resume the previous schedule.
            initialTriggerTime = getNextAlarmDueElapsedTime();
        }

        alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
            initialTriggerTime,
            getIntervalInSeconds() * MILLISECONDS_IN_SECOND,
            pendingAlarmIntent);
    } else {
        Log.i(TAG, "Attempted to start an already running alarm manager");
    }
}
 
Example #26
Source File: BaseService.java    From libcommon with Apache License 2.0 5 votes vote down vote up
/**
 * 通知領域に指定したメッセージを表示する。フォアグラウンドサービスとして動作させる。
 * @param smallIconId
 * @param title
 * @param content
 * @param intent
 */
protected void showNotification(@DrawableRes final int smallIconId,
	@NonNull final CharSequence title, @NonNull final CharSequence content,
	final PendingIntent intent) {

	showNotification(NOTIFICATION_ID,
		getString(R.string.service_name),
		null, null,
		smallIconId, R.drawable.ic_notification,
		title, content,
		true, intent);
}
 
Example #27
Source File: DoNothingService.java    From xDrip with GNU General Public License v3.0 5 votes vote down vote up
private void setFailOverTimer() {
    if (Home.get_follower()) {
        final long retry_in = (5 * 60 * 1000);
        UserError.Log.d(TAG, "setFailoverTimer: Restarting in: " + (retry_in / (60 * 1000)) + " minutes");
        nextWakeUpTime = JoH.tsl() + retry_in;
        //final PendingIntent wakeIntent = PendingIntent.getService(this, 0, new Intent(this, this.getClass()), 0);
        final PendingIntent wakeIntent = WakeLockTrampoline.getPendingIntent(this.getClass());
        JoH.wakeUpIntent(this, retry_in, wakeIntent);

    } else {
        stopSelf();
    }
}
 
Example #28
Source File: TasksUtils.java    From FreezeYou with Apache License 2.0 5 votes vote down vote up
private static void setRealTimeTask(AlarmManager alarmManager, long triggerAtMillis, PendingIntent operation) {
    if (Build.VERSION.SDK_INT >= 23) {
        alarmManager.setExactAndAllowWhileIdle(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, operation);
    } else if (Build.VERSION.SDK_INT >= 19) {
        alarmManager.setExact(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, operation);
    } else {
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, triggerAtMillis, operation);
    }
}
 
Example #29
Source File: LeftRightWidget.java    From homescreenarcade with GNU General Public License v3.0 5 votes vote down vote up
protected void updateAppWidget(Context context, AppWidgetManager appWidgetManager,
                            int appWidgetId) {
    RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.left_right_widget);
    views.setOnClickPendingIntent(R.id.left_btn,
            PendingIntent.getBroadcast(context, 0, new Intent(ArcadeCommon.ACTION_LEFT), 0));
    views.setOnClickPendingIntent(R.id.right_btn,
            PendingIntent.getBroadcast(context, 0, new Intent(ArcadeCommon.ACTION_RIGHT), 0));
            
    appWidgetManager.updateAppWidget(appWidgetId, views);
}
 
Example #30
Source File: NotificationHelper.java    From FastAccess with GNU General Public License v3.0 5 votes vote down vote up
public static void notifyShort(@NonNull Context context, @NonNull String title, @NonNull String msg, @DrawableRes int iconId, int nId,
                               @Nullable PendingIntent pendingIntent) {
    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new NotificationCompat.Builder(context)
            .setAutoCancel(true)
            .setDefaults(Notification.DEFAULT_ALL)
            .setContentTitle(title)
            .setContentText(msg)
            .setSmallIcon(iconId)
            .setContentIntent(pendingIntent)
            .build();
    notificationManager.notify(nId, notification);
}