当有应用级通知时,我会向用户发送通知。在通知内部,我执行了一个操作,其中完成了调用意图。操作没有任何问题,但点击操作后,通知不会取消。我无法弄清楚为什么会这样。我已将autoCancel设置为true但仍然无法正常工作。发布到目前为止我尝试过的内容。
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;
}
我只是发布相关代码,这是创建通知所必需的。任何帮助表示赞赏。提前谢谢。
答案 0 :(得分:1)
当用户点击操作按钮时,通知不会被取消。
你必须从你的主要活动中手动取消它...
将以下代码放在MainActivity.java
:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_menu);
ButterKnife.bind(this);
NotificationManager notificatioMng =
(NotificationManager) getSystemService( Context.NOTIFICATION_SERVICE );
notificatioMng.cancelAll();
//The above lines will cancel the notification
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;
}