我正在创建一个Android应用程序,其中每天都会在特定时间向用户发送通知。通知正在后台运行。我希望我的应用程序让用户使用名为btnStopService的按钮关闭通知。我怎样才能做到这一点?我尝试了,但通知无法关闭。
注意:假设我在特定时间调用startNotification方法。 忽略startNotification方法中的for循环。
这些是startNotification方法的代码:
public void startNotification() {
notifyManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
notifyBuilder = new NotificationCompat.Builder(getApplicationContext());
notifyBuilder.setContentTitle("Good morning");
notifyBuilder.setContentText("Morning");
notifyBuilder.setSmallIcon(R.drawable.bmi_cal);
notifyBuilder.setPriority(Notification.PRIORITY_MAX);
notifyBuilder.setLights(Color.BLUE, 500, 500);
try {
Uri notification = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), notification);
r.play();
} catch (Exception e) {
e.printStackTrace();
}
if (Build.VERSION.SDK_INT >= 21) notifyBuilder.setVibrate(new long[5000]);
new Thread(new Runnable() {
@Override
public void run() {
for(int i=0;i<1;i++)
{
notifyManager.notify(MY_NOTIFICATION_ID, notifyBuilder.build());
try {
Thread.sleep(1 * 1000);
} catch (InterruptedException e) {
}
}
// for (i = 0; i <= 20; i += 10) {
//notifyBuilder.setProgress(100, i, false);
// }
//notifyBuilder.setContentText("Bread is ready!");
//notifyBuilder.setProgress(0, 0, false);
notifyManager.notify(MY_NOTIFICATION_ID, notifyBuilder.build());
}
}
).start();
}
这些是启动服务的startCommand方法的代码:
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread triggerService=new Thread(new Runnable() {
long startingTime=System.currentTimeMillis();
long tics=0;
@Override
public void run() {
for(;;)
{
try
{
// ASSUME I trigger the notification at a specific time
startNotification();
/* tics= System.currentTimeMillis() - startingTime;
Intent myFilteredResponse=new Intent("liren.action.GOSERVICE3");
String msg= " value: " + tics;
myFilteredResponse.putExtra("serviceData", msg);
sendBroadcast(myFilteredResponse); */
Thread.sleep(3000);
}
catch (Exception e)
{
e.printStackTrace();
}
//notifyManager.notify(MY_NOTIFICATION_ID, notifyBuilder.build());
}
}
});
triggerService.start();
return super.onStartCommand(intent, flags, startId);
}
这些是btnStopService方法中的代码。
btnStopService方法在StopNotification java类中。
public class StopNotification extends AppCompatActivity {
ComponentName service;
Intent intentMyService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_stop_notification);
intentMyService = new Intent(this, myServiceRunner.class);
}
public void btnTurnOff(View v)
{
try {
stopService(new Intent(intentMyService));
Thread.sleep(1000);
Toast.makeText(getApplicationContext(), "Turn Off Notification", Toast.LENGTH_SHORT).show();
finish();
} catch (Exception e) {
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
请使用:
Intent intent = new Intent(this, YourService.class);
stopService(intent);