package org.cocos2dx.javascript.Soul;
import android.content.Context;
import android.util.Log;
import androidx.work.Worker;
import androidx.work.WorkerParameters;
import org.cocos2dx.javascript.SoulSdk;
public class SoulWork extends Worker {
private static final String TAG = "SoulWork";
public SoulWork( Context appContext, WorkerParameters workerParams) {
super(appContext, workerParams);
}
@Override
public Result doWork() {
Log.d(TAG, "Performing long running task in scheduled job");
//接收外面传递进来的数据
String body = getInputData().getString("body");
if(title == null || body == null || title.isEmpty() || body.isEmpty()){
return Result.success();
}
sendNotification(body);
Log.d(TAG, type);
return Result.success();
}
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
private void sendNotification(String messageBody) {
Intent intent = new Intent(this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
PendingIntent.FLAG_IMMUTABLE);
String channelId = getString(R.string.default_notification_channel_id);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder =
new NotificationCompat.Builder(this, channelId)
.setSmallIcon(R.drawable.ic_stat_ic_notification)
.setContentTitle(getString(R.string.fcm_message))
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Since android Oreo notification channel is needed.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(channelId,
"Channel human readable title",
NotificationManager.IMPORTANCE_DEFAULT);
notificationManager.createNotificationChannel(channel);
}
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
}
1.延迟调用
/**
* 添加一个通知任务
* @param conent 通知内容
* @param seconds 通知下次时间
*/
public static void addWork(Data conent, int seconds,String tag){
WorkManager.getInstance( Cocos2dxHelper.getActivity()).cancelAllWorkByTag(tag);
OneTimeWorkRequest work = new OneTimeWorkRequest.Builder(SoulWork.class)
.setInitialDelay(seconds, TimeUnit.SECONDS)
.setInputData(conent)
.addTag(tag)
.build();
WorkManager.getInstance( Cocos2dxHelper.getActivity()).beginWith(work).enqueue();
}