如何通过 Android 通知停止前台服务?

huangapple go评论99阅读模式
英文:

How to stop a foreground service from the notification in android?

问题

以下是您要翻译的内容:

我在我的应用程序中使用了前台服务,我需要在通知本身上的一个按钮上停止这个服务,而无需打开该活动。
我的现有代码

这是我启动服务的活动。

serviceIntent = new Intent(getApplicationContext(), BackgroundService.class);
serviceIntent.putExtra("ip", ipAdd);
serviceIntent.putExtra("token", token);
serviceIntent.putExtra("port", portNo);
serviceIntent.putExtra("resource", resourceId);
serviceIntent.putExtra("userName", username);
startService(serviceIntent);
ClosingBackGroundService.getMainActivityContext(MainActivity.this);
button.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        stopService(serviceIntent);
    }
});

我正在使用一个类在通知上显示按钮,并尝试关闭活动。

public class ClosingBackGroundService extends BroadcastReceiver {

    static Context mainActContext;
    
    public static void getMainActivityContext(Context context) {
        mainActContext = context;
    }
    
    @Override
    public void onReceive(Context context, Intent intent) {
        mainActContext.stopService(MainActivity.serviceIntent);
        Log.i("Service", "closed");
    }
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    registerReceiver(broadcastReceiver, filter);
    Intent notificationIntent = new Intent(this, LoginActivity.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
    Intent closingIntent = new Intent(this, ClosingBackGroundService.class);
    PendingIntent actionIntent = PendingIntent.getBroadcast(this, 0, closingIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    Notification notification = new NotificationCompat.Builder(this, CHANNEL_ID)
            .setOngoing(true)
            .setSmallIcon(R.drawable.logo)
            .addAction(R.mipmap.ic_launcher, "Close Services", actionIntent)
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setContentText("Processes Running In BackGround").build();
    ipAdd = intent.getStringExtra("ip");
    port = intent.getStringExtra("port");
    token = intent.getStringExtra("token");
    resourceId = intent.getIntExtra("resource", 0);
    username = intent.getStringExtra("userName");
    runnableForGps.run();
    runnableForSendingGpsData.run();
    runnableForBluetooth.run();
    runnableForsendingBTData.run();
    startForeground(1, notification);

    return START_STICKY;
}

当我按下按钮时,通知消失,但进程仍在继续运行。

英文:

I am using a foreground service in my application I need to stop this service from a button that is present on the notification itself without opening the activity.
My current code

This is my activity from where I am starting the service.

serviceIntent = new Intent(getApplicationContext(),BackgroundService.class);
serviceIntent.putExtra("ip",ipAdd);
serviceIntent.putExtra("token",token);
serviceIntent.putExtra("port",portNo);
serviceIntent.putExtra("resource",resourceId);
serviceIntent.putExtra("userName",username);
startService(serviceIntent);
ClosingBackGroundService.getMainActivityContext(MainActivity.this);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
stopService(serviceIntent);
}
});

I am using a class to show the button on the notification and trying to close the activity

public class ClosingBackGroundService extends BroadcastReceiver {
static Context mainActContext;
public static void getMainActivityContext(Context context){
mainActContext = context;
}
@Override
public void onReceive(Context context, Intent intent) {
mainActContext.stopService(MainActivity.serviceIntent);
Log.i("Service","closed");
}
}
 @Override
public int onStartCommand(Intent intent, int flags, int startId) {
bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(broadcastReceiver, filter);
Intent notificationIntent = new Intent(this,LoginActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
Intent closingIntent = new Intent(this,ClosingBackGroundService.class);
PendingIntent actionIntent = PendingIntent.getBroadcast(this,0,closingIntent,PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new NotificationCompat.Builder(this,CHANNEL_ID)
.setOngoing(true)
.setSmallIcon(R.drawable.logo)
.addAction(R.mipmap.ic_launcher,"Close Services",actionIntent)
.setContentIntent(pendingIntent)
.setAutoCancel(true)
.setContentText("Processes Running In BackGround").build();
ipAdd = intent.getStringExtra("ip");
port = intent.getStringExtra("port");
token = intent.getStringExtra("token");
resourceId = intent.getIntExtra("resource",0);
username = intent.getStringExtra("userName");
runnableForGps.run();
runnableForSendingGpsData.run();
runnableForBluetooth.run();
runnableForsendingBTData.run();
startForeground(1,notification);
return START_STICKY;
}

When I press the button the notification disappears but the process keeps on working.

答案1

得分: 4

不需要创建 BroadCast 来停止 Service。尝试以下代码:

private static final String ACTION_STOP_LISTEN = "action_stop_listen";
Intent intent = new Intent(this, ClosingBackGroundService.class);
intent.setAction(ACTION_STOP_LISTEN);
PendingIntent actionIntent = PendingIntent.getService(this, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
addAction(R.mipmap.ic_launcher,"关闭服务",actionIntent);

onStartCommand 中检查你的 Intent 动作:

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (intent != null && ACTION_STOP_LISTEN.equals(intent.getAction())) {
        stopForeground(true);
        stopSelf();
        return START_NOT_STICKY;
    }
    // 你的代码
}
英文:

You don't need to create BroadCast to stop Service. Try this

private static final String ACTION_STOP_LISTEN = "action_stop_listen";
Intent intent = new Intent(this, ClosingBackGroundService.class);
intent.setAction(ACTION_STOP_LISTEN);
PendingIntent actionIntent = PendingIntent.getService(this, 123, intent, PendingIntent.FLAG_UPDATE_CURRENT);
addAction(R.mipmap.ic_launcher,"Close Services",actionIntent)

In onStartCommand check your Intent action

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (intent != null && ACTION_STOP_LISTEN.equals(intent.getAction())) {
stopForeground(true);
stopSelf();
return START_NOT_STICKY;
}
// your code
}

huangapple
  • 本文由 发表于 2020年5月29日 17:32:51
  • 转载请务必保留本文链接:https://go.coder-hub.com/62082842.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定