1
當有應用程序級通知時,我會向用戶發送通知。在通知內部,我執行一個操作,其中調用意圖完成。該行爲沒有任何問題,但點擊行動後,通知不會取消。我無法弄清楚爲什麼會發生這種情況。我已將autoCancel設置爲true,但仍然無效。張貼到目前爲止我嘗試過的。通知不取消操作點擊android
MapsFragment.java
public PendingIntent createGeofencePendingIntent(int myRange) {
Log.d(TAG, "createGeofencePendingIntent");
if(myRange == 3) {
final Intent intent3 = new Intent(getContext(), GeofenceTransitionService.class);
intent3.putExtra("region", inString[2]);
return geoFencePendingIntent3 = PendingIntent.getService(
getContext(), 1, intent3, PendingIntent.FLAG_UPDATE_CURRENT);
}
if(myRange == 1) {
final Intent intent1 = new Intent(getContext(), GeofenceTransitionService.class);
intent1.putExtra("region", inString[0]);
return geoFencePendingIntent1 = PendingIntent.getService(
getContext(), 2, intent1, PendingIntent.FLAG_UPDATE_CURRENT);
}
if(myRange == 2) {
final Intent intent2 = new Intent(getContext(), GeofenceTransitionService.class);
intent2.putExtra("region", inString[1]);
return geoFencePendingIntent2 = PendingIntent.getService(
getContext(), 3, intent2, PendingIntent.FLAG_UPDATE_CURRENT);
}
return null;
}
GeofenceTransistionService.java
public class GeofenceTransitionService extends IntentService {
private static final String TAG = GeofenceTransitionService.class.getSimpleName();
int counter = 0;
String geoFencingRegion;
public GeofenceTransitionService() {
super(TAG);
}
String str;
boolean appNotifications;
DatabaseReference gPhone;
String guardianPhoneNumber;
String status;
String numberPlus;
@Override
protected void onHandleIntent(Intent intent) {
GeofencingEvent geofencingEvent = GeofencingEvent.fromIntent(intent);
SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
String userId = sharedPreferences.getString(Preferences.USERID, "");
appNotifications = sharedPreferences.getBoolean(getString(R.string.title_app_notifications_key), false);
if(userId != null){
gPhone = FirebaseDatabase.getInstance().getReference().child("guardians").child("guardianEmails");
}
// Handling
str = intent.getStringExtra("region");
if (geofencingEvent.hasError()) {
String errorMsg = getErrorString(geofencingEvent.getErrorCode());
Log.e(TAG, errorMsg);
return;
}
if(str.matches("a")) {
counter = 1;
geoFencingRegion = " zone 1";
}
else if(str.matches("b")) {
counter = 2;
geoFencingRegion = " zone 2";
}
else if (str.matches("c")) {
counter = 3;
geoFencingRegion = " zone 3";
}
int geoFenceTransition = geofencingEvent.getGeofenceTransition();
// Check if the transition type is of interest
if (geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER ||
geoFenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
// Get the geofence that were triggered
List<Geofence> triggeringGeofences = geofencingEvent.getTriggeringGeofences();
String geofenceTransitionDetails = getGeofenceTrasitionDetails(geoFenceTransition, triggeringGeofences);
// Send notification details as a String
if(appNotifications) {
sendNotification(geofenceTransitionDetails);
}
}
}
private String getGeofenceTrasitionDetails(int geoFenceTransition, List<Geofence> triggeringGeofences) {
// get the ID of each geofence triggered
ArrayList<String> triggeringGeofencesList = new ArrayList<>();
for (Geofence geofence : triggeringGeofences) {
triggeringGeofencesList.add(geofence.getRequestId());
}
if (geoFenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER) {
status = "Entering " + geoFencingRegion;
}
else if (geoFenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT) {
status = "Exiting " + geoFencingRegion;
}
try {
gPhone.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
LocationModel myModel = dataSnapshot.getValue(LocationModel.class);
if(myModel !=null){
guardianPhoneNumber = myModel.getGuardianNumber();
guardianPhoneNumber = guardianPhoneNumber.replaceAll("[^0-9]","");
numberPlus = "+1" + guardianPhoneNumber;
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage(numberPlus, null, "The standard user is " + status, null, null);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
// Toast.makeText(getApplicationContext(), "SMS Sent!",
// Toast.LENGTH_LONG).show();
} catch (Exception e) {
Toast.makeText(getApplicationContext(),
"SMS faild, please try again later!",
Toast.LENGTH_LONG).show();
e.printStackTrace();
}
return status + TextUtils.join(", ", triggeringGeofencesList);
}
private void sendNotification(String msg) {
Log.i(TAG, "sendNotification: " + msg);
// Intent to start the main Activity
Intent notificationIntent = MainMenuActivity.makeNotificationIntent(getApplicationContext(), msg);
notificationIntent.putExtra("Maps", "geofenceCall");
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainMenuActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent notificationPendingIntent = stackBuilder.getPendingIntent(counter, PendingIntent.FLAG_UPDATE_CURRENT);
// Creating and sending Notification
NotificationManager notificatioMng =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificatioMng.notify(
counter,
createNotification(msg, notificationPendingIntent));
}
// Create notification
private Notification createNotification(String msg, PendingIntent notificationPendingIntent) {
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this);
notificationBuilder
.setSmallIcon(R.drawable.ic_contact_phone_black_24dp)
.setColor(Color.WHITE)
.setAutoCancel(true)
.setContentTitle("Geofence Alert!")
.setContentText(msg + "Do you want to call the patient you are tracking?")
.addAction(R.drawable.ic_call_black_24dp,"Call",notificationPendingIntent)
.setContentIntent(notificationPendingIntent)
.setDefaults(Notification.DEFAULT_LIGHTS | Notification.DEFAULT_VIBRATE | Notification.DEFAULT_SOUND);
return notificationBuilder.build();
}
private static String getErrorString(int errorCode) {
switch (errorCode) {
case GeofenceStatusCodes.GEOFENCE_NOT_AVAILABLE:
return "GeoFence not available";
case GeofenceStatusCodes.GEOFENCE_TOO_MANY_GEOFENCES:
return "Too many GeoFences";
case GeofenceStatusCodes.GEOFENCE_TOO_MANY_PENDING_INTENTS:
return "Too many pending intents";
default:
return "Unknown error.";
}
}
}
MainActivity.java
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
ButterKnife.bind(this);
String type = getIntent().getStringExtra("Maps");
if (type != null) {
switch (type) {
case "mapsFragment":
Fragment mapsFragment = new MapsFragment();
FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
fragmentTransaction.replace(R.id.container_gaFragments, mapsFragment).commit();
break;
case "gasstation":
Uri gmmIntentUri = Uri.parse("geo:0,0?q=gas station");
Intent mapIntent = new Intent(Intent.ACTION_VIEW, gmmIntentUri);
mapIntent.setPackage("com.google.android.apps.maps");
startActivity(mapIntent);
break;
case "geofenceCall":
databaseReferenceGuardian.addListenerForSingleValueEvent(new ValueEventListener() {
@Override
public void onDataChange(DataSnapshot dataSnapshot) {
LocationModel locationModel = dataSnapshot.getValue(LocationModel.class);
if(locationModel !=null){
guardianNumber = locationModel.getGuardianNumber();
guardianNumber = guardianNumber.replaceAll("[^0-9]","");
numberPlus = "+1" + guardianNumber;
String uri = "tel:" + numberPlus;
//Build the intent that will make the phone call
Intent callIntent = new Intent(Intent.ACTION_CALL, Uri.parse(uri));
callIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (ActivityCompat.checkSelfPermission(MainMenuActivity.this, Manifest.permission.CALL_PHONE) != PackageManager.PERMISSION_GRANTED) {
// TODO: Consider calling
// ActivityCompat#requestPermissions
// here to request the missing permissions, and then overriding
// public void onRequestPermissionsResult(int requestCode, String[] permissions,
// int[] grantResults)
// to handle the case where the user grants the permission. See the documentation
// for ActivityCompat#requestPermissions for more details.
return;
}
getApplicationContext().startActivity(callIntent);
}
}
@Override
public void onCancelled(DatabaseError databaseError) {
}
});
}
}
public static Intent makeNotificationIntent(Context context, String msg) {
Intent intent = new Intent(context, MainMenuActivity.class);
intent.putExtra(NOTIFICATION_MSG, msg);
return intent;
}
我只是發佈了創建通知所必需的相關代碼。任何幫助表示讚賞。提前致謝。
非常感謝好友!像魅力一樣工作 –
我的愉快,兄弟:) –