如何在Android 12+中使用前台服务



如何在Android 12中使用前台服务而不会出现Api 23+的错误。

这个例子帮助

MainActivity:

import androidx.appcompat.app.AppCompatActivity;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;


public class MainActivity extends AppCompatActivity {
public static final String MESSAGE_STATUS = "message_status";
TextView tvStatus;
Button btnSend;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
tvStatus = findViewById(R.id.tvStatus);
btnSend = findViewById(R.id.btnSend);
//        final WorkManager mWorkManager = WorkManager.getInstance();
//        final OneTimeWorkRequest mRequest = new OneTimeWorkRequest.Builder(NotificationWorker.class).build();



btnSend.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//                mWorkManager.enqueue(mRequest);

//Start our own service
if ( isServiceRunning( MyService.class) ) {
Toast.makeText(MainActivity.this, "وضعیت روشن است امکان سرویس جدید نیست"  , Toast.LENGTH_SHORT).show();
}else{
Intent intent = new Intent(MainActivity.this, MyService.class);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
startForegroundService(intent);
}
Toast.makeText(MainActivity.this, "Running .... "  , Toast.LENGTH_SHORT).show();
}
}
});

}

// http://www.androidtutorialshub.com/andorid-how-to-check-service-is-running-or-not/
private boolean isServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}

}//class

创建服务:

MyService.java

import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.util.Log;
import androidx.core.app.NotificationCompat;
public class MyService extends Service {
String channelId = "task_channel";
String channelName = "task_name";
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new
NotificationChannel(channelId, channelName,
NotificationManager.IMPORTANCE_DEFAULT);
}
showNotification("WorkManager", "Message has been Sent");
new Thread(new Runnable() {
@Override
public void run() {
try {
int cou=0;
while (true) {
Log.i("mohsennnn : ", "me --> " +  cou);
cou++;
Thread.sleep(500);
}
} catch (Exception e) {
Log.i("mohsennn Service", e.toString());
}
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
private void showNotification(String task, String desc) {
NotificationManager manager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new
NotificationChannel(channelId, channelName, NotificationManager.IMPORTANCE_DEFAULT);
manager.createNotificationChannel(channel);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), channelId)
.setContentTitle(task)
.setContentText(desc)
.setSmallIcon(R.mipmap.ic_launcher);
//        manager.notify(1, builder.build());
startForeground(1 , builder.build());
}//showNotification
}

清单:

<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Foreground_service_with_notification">
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"></service>
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

activity_layout.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:id="@+id/tvStatus"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="8dp"
android:gravity="center"
android:text="Hello World!"
android:textSize="18sp"
app:layout_constraintBottom_toTopOf="@+id/btnSend"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintVertical_chainStyle="packed" />
<Button
android:id="@+id/btnSend"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginStart="8dp"
android:layout_marginTop="16dp"
android:layout_marginEnd="8dp"
android:layout_marginBottom="8dp"
android:background="#000"
android:paddingLeft="8dp"
android:paddingRight="8dp"
android:text="Send Notification"
android:textAllCaps="false"
android:textColor="#fff"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintHorizontal_bias="0.5"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toBottomOf="@+id/tvStatus" />
</androidx.constraintlayout.widget.ConstraintLayout>

最新更新