Я пытаюсь реализовать ML Kit: API-интерфейсы на естественном языке и ML Kit: Модель идентификации языка в моем приложении, я реализовал все настройки, и они работают нормально, но когда я пытаюсь реализовать их.
com.google.firebase:firebase-ml-natural-language:22.0.0
com.google.firebase:firebase-ml-natural-language-language-id-model:20.0.7
Класс FirebaseMessagingService выдает мне ошибку и вообще не может ее найти. Он говорит, что не может конвертироваться в объект Context. если удалить библиотеку, ошибка исчезла.
Logcat:
D: \ project \ uumoo_android \ app \ src \ main \ java \ net \ uumoo \ pocket \ android \ Services \MyFirebaseMessagingService.java:66: ошибка: несовместимые типы: MyFirebaseMessagingService не может быть преобразован в Context
private Context context = MyFirebaseMessagingService.this;
Это моя программа-приложение.
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
//noinspection GradleCompatible
implementation 'com.android.support:appcompat-v7:27.1.1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-v4:27.1.1'
implementation 'com.android.support:support-vector-drawable:27.1.1'
implementation 'com.google.android.gms:play-services-maps:15.0.1'
implementation 'com.google.firebase:firebase-messaging:17.3.0'
implementation 'com.firebase:firebase-jobdispatcher:0.8.5'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.android.support:design:27.1.1'
implementation 'de.hdodenhof:circleimageview:2.2.0'
implementation 'com.android.support:cardview-v7:27.1.1'
implementation 'com.wdullaer:materialdatetimepicker:3.6.2'
implementation 'com.dlazaro66.qrcodereaderview:qrcodereaderview:2.0.3'
implementation 'com.github.ittianyu:BottomNavigationViewEx:1.2.4'
//implementation 'com.squareup.retrofit2:retrofit:2.2.0'
//implementation 'com.google.code.gson:gson:2.8.2'
//implementation 'com.squareup.retrofit2:converter-gson:2.2.0'
implementation 'com.android.volley:volley:1.1.1'
implementation 'com.jakewharton:butterknife:8.8.1'
annotationProcessor 'com.jakewharton:butterknife-compiler:8.8.1'
implementation 'com.google.android.gms:play-services-location:15.0.1'
implementation 'com.github.bumptech.glide:glide:4.7.1'
annotationProcessor 'com.github.bumptech.glide:compiler:4.7.1'
implementation 'com.squareup.picasso:picasso:2.71828'
implementation 'com.github.tozny:java-aes-crypto:1.1.0'
implementation 'com.scottyab:aescrypt:0.0.1'
implementation 'com.kbeanie:multipicker:1.5@aar'
implementation "android.arch.persistence.room:runtime:1.1.1"
annotationProcessor "android.arch.persistence.room:compiler:1.1.1"
implementation 'com.androidadvance:topsnackbar:1.1.1'
implementation 'com.github.delight-im:Android-AdvancedWebView:v3.0.0'
implementation 'com.github.XuDaojie:QRCode-Android:v0.4.2'
implementation 'com.google.firebase:firebase-ml-vision:18.0.1'
implementation 'com.github.zomato:androidphotofilters:1.0.1'
implementation 'com.yakivmospan:scytale:1.0.1'
implementation 'com.xw.repo:bubbleseekbar:3.19'
implementation 'com.google.maps.android:android-maps-utils:0.5+'
// barcode reader library only use for UI
implementation 'info.androidhive:barcode-reader:1.1.5'
implementation "com.google.code.gson:gson:$rootProject.gsonVersion"
implementation 'com.google.android.gms:play-services-auth:16.0.1'
implementation 'com.google.android.gms:play-services-auth-api-phone:16.0.0'
//implementation 'com.google.firebase:firebase-core:17.2.1'
//dentify the language of text with ML Kit
implementation 'com.google.firebase:firebase-ml-natural-language:22.0.0'
implementation 'com.google.firebase:firebase-ml-natural-language-language-id-model:20.0.7'
}
apply plugin: 'com.google.gms.google-services'
это моя версия проекта
dependencies {
classpath 'com.android.tools.build:gradle:3.1.4'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
classpath 'com.google.gms:google-services:3.2.0'
// new
// classpath 'com.google.gms:google-services:4.3.2' // Google Services plugin
}
MyFireBaseClass
public class MyFirebaseMessagingService extends FirebaseMessagingService {
private static final String TAG = "MyFirebaseMsgService";
private Context context = MyFirebaseMessagingService.this;
private int notiCount = 0;
public static final String BROADCAST_ACTION = "net.uumoo.pocket.android.Services.Notification";
/**
* Called when message is received.
*
* @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
*/
// [START receive_message]
@Override
public void onMessageReceived(RemoteMessage remoteMessage) {
Log.e(TAG, "From: " + remoteMessage.getFrom());
if (remoteMessage.getData().size() > 0) {
Log.e(TAG, "Message data payload: " + remoteMessage.getData());
parseNotificationMap(remoteMessage.getData());
if (/* Check if data needs to be processed by long running job */ true) {
// For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
scheduleJob();
} else {
// Handle message within 10 seconds
handleNow();
}
}
// Check if message contains a notification payload.
if (remoteMessage.getNotification() != null) {
Log.e(TAG, "Message Notification Body: " + remoteMessage.getNotification());
sendNotification(
remoteMessage.getNotification().getTitle(),
remoteMessage.getNotification().getBody());
}
// Also if you intend on generating your own notifications as a result of a received FCM
// message, here is where that should be initiated. See sendNotification method below.
}
private void lighting() {
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
boolean isScreenOn = pm.isScreenOn();
Log.e("screen on", "" + isScreenOn);
if (isScreenOn == false) {
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP | PowerManager.ON_AFTER_RELEASE, "MyLock");
wl.acquire(10000);
PowerManager.WakeLock wl_cpu = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyCpuLock");
wl_cpu.acquire(10000);
}
}
// [END receive_message]
// [START on_new_token]
/**
* Called if InstanceID token is updated. This may occur if the security of
* <p>
* the previous token had been compromised. Note that this is called when the InstanceID token
* <p>
* is initially generated so this is where you would retrieve the token.
*/
@Override
public void onNewToken(String token) {
Log.e(TAG, "Refreshed token: " + token);
// If you want to send messages to this application instance or
// manage this apps subscriptions on the server side, send the
// Instance ID token to your app server.
sendRegistrationToServer(token);
}
// [END on_new_token]
/**
* Schedule a job using FirebaseJobDispatcher.
*/
private void scheduleJob() {
// [START dispatch_job]
FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(this));
Job myJob = dispatcher.newJobBuilder()
.setService(MyJobService.class)
.setTag("my-job-tag")
.build();
dispatcher.schedule(myJob);
// [END dispatch_job]
}
/**
* Handle time allotted to BroadcastReceivers.
*/
private void handleNow() {
Log.e(TAG, "Short lived task is done.");
}
/**
* Persist token to third-party servers.
* <p>
* <p>
* <p>
* Modify this method to associate the user's FCM InstanceID token with any server-side account
* <p>
* maintained by your application.
*
* @param token The new token.
*/
private void sendRegistrationToServer(String token) {
if (Constants.isNetworkAvailable(context)) {
if (SharedPreferenceManager.getInstance(context).checkAccessToken()) {
sendFCMTokenToServer(makeFCMTokenJSONObject(token));
}
else Log.e("NoAccess","No Access Token ");
}
}
private void sendFCMTokenToServer(JSONObject jsonObject) {
Log.e(TAG, "object " + jsonObject.toString());
String url = Constants.BASE_URL + "api/v2/fcm-token-update/";
RequestQueue requestQueue = Volley.newRequestQueue(context);
JsonObjectRequest jsonObjectRequest = new JsonObjectRequest(
Request.Method.POST, url, jsonObject, response -> {
Log.e(TAG, "onResponse " + response.toString());
try {
parseFCMTokenFromResponse(response);
} catch (JSONException e) {
e.printStackTrace();
}
}, error -> {
Constants.showTopSnackBar((AppCompatActivity) context, error.toString());
Log.e(TAG, "error " + error.toString());
});
requestQueue.add(jsonObjectRequest);
}
private void parseFCMTokenFromResponse(JSONObject response) throws JSONException {
if (response.has("success")) {
if (response.getString("success").equals("true")) {
//Toast.makeText(context, response.getString("msg"), Toast.LENGTH_LONG).show();
}
} else if (response.has("error")) {
Constants.showTopSnackBar((AppCompatActivity) context, response.getString("error"));
}
}
private JSONObject makeFCMTokenJSONObject(String fcmToken) {
User user = SharedPreferenceManager.getInstance(context).getUser();
JSONObject jsonObject = new JSONObject();
try {
jsonObject.put("mobileno", user.getPocket_mobileno());
jsonObject.put("user_type", Constants.POCKET_USER_TYPE);
jsonObject.put("deviceid", user.getPocket_deviceid());
jsonObject.put("simid_one", user.getPocket_simid());
jsonObject.put("simid_two", user.getPocket_simid_two());
jsonObject.put("fcm_token", fcmToken);
} catch (JSONException e) {
e.printStackTrace();
}
return jsonObject;
}
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
private void sendNotification(String title, String messageBody) {
lighting();
Intent intent = new Intent(this, LogActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
//Uri soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.christmas_bells);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CH_ID")
.setSmallIcon(R.drawable.icon)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
if (soundUri != null) {
// Changing Default mode of notification
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
// Creating an Audio Attribute
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
// Creating Channel
NotificationChannel notificationChannel = new NotificationChannel("CH_ID", "Testing_Audio", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(soundUri, audioAttributes);
mNotificationManager.createNotificationChannel(notificationChannel);
}
}
mNotificationManager.notify(0, notificationBuilder.build());
}
private void parseNotificationMap(Map<String, String> body) {
if (body.get("type").equals(Constants.NOTIFICATION_DATA_TYPE_TRANSACTION)) {
String msg_title = body.get("msg_title");
String amount = body.get("amount");
String sender = body.get("sender");
String receiver = body.get("receiver");
String transaction_type = body.get("transaction_type");
String msg = body.get("msg");
switch (transaction_type) {
case "payment":
SharedPreferenceManager.getInstance(context).setLogFragment("0");
break;
case "deposit":
SharedPreferenceManager.getInstance(context).setLogFragment("1");
break;
case "transfer":
SharedPreferenceManager.getInstance(context).setLogFragment("2");
break;
case "withdraw":
SharedPreferenceManager.getInstance(context).setLogFragment("3");
break;
}
LocalBroadcastManager broadcaster = LocalBroadcastManager.getInstance(getBaseContext());
if (SharedPreferenceManager.getInstance(context)
.getNotificationCount() != null) {
notiCount = Integer.parseInt(
SharedPreferenceManager.getInstance(context).getNotificationCount()
);
SharedPreferenceManager.getInstance(context).setNotificationCount(
String.valueOf(++notiCount)
);
} else {
SharedPreferenceManager.getInstance(context).setNotificationCount(
String.valueOf(++notiCount)
);
}
Intent intent = new Intent(BROADCAST_ACTION);
intent.putExtra("notiCount", notiCount);
broadcaster.sendBroadcast(intent);
sendNotification(msg_title, msg);
} else if (body.get("type").equals(Constants.NOTIFICATION_DATA_TYPE_SYSTEM)) {
AppDataBase.getAppDatabase(context).messageDao().insert(
new MessageEntity(
body.get("mobile_no"),
body.get("msg_title"),
body.get("msg"),
body.get("date"),
body.get("custom_date"),
body.get("time"),
body.get(""),
0
)
);
sendNotificationSystem(body.get("msg_title"), body.get("msg"));
} else if (body.get("type").equals(Constants.NOTIFICATION_DATA_TYPE_GEOFENCE)) {
} else if (body.get("type").equals(Constants.NOTIFICATION_DATA_TYPE_KEYS)) {
Log.e(TAG, "NOTIFICATION_DATA_TYPE_KEYS");
AppDataBase appDataBase = AppDataBase.getAppDatabase(context);
if (appDataBase.keyDao().getNumberOfRows() == 0) {
appDataBase.keyDao().insert(new KeyEntity(Constants.LOG_IN, Constants.encryptKeystore(context, Constants.LOG_IN, body.get(Constants.LOG_IN))));
appDataBase.keyDao().insert(new KeyEntity(Constants.APP_PASS, Constants.encryptKeystore(context, Constants.APP_PASS, body.get(Constants.APP_PASS))));
appDataBase.keyDao().insert(new KeyEntity(Constants.TRN_PASS, Constants.encryptKeystore(context, Constants.TRN_PASS, body.get(Constants.TRN_PASS))));
appDataBase.keyDao().insert(new KeyEntity(Constants.FORGOT_PIN, Constants.encryptKeystore(context, Constants.FORGOT_PIN, body.get(Constants.FORGOT_PIN))));
appDataBase.keyDao().insert(new KeyEntity(Constants.FORGOT_PASS, Constants.encryptKeystore(context, Constants.FORGOT_PASS, body.get(Constants.FORGOT_PASS))));
appDataBase.keyDao().insert(new KeyEntity(Constants.WITHDRAW, Constants.encryptKeystore(context, Constants.WITHDRAW, body.get(Constants.WITHDRAW))));
appDataBase.keyDao().insert(new KeyEntity(Constants.DEPOSIT, Constants.encryptKeystore(context, Constants.DEPOSIT, body.get(Constants.DEPOSIT))));
appDataBase.keyDao().insert(new KeyEntity(Constants.TRANSFER, Constants.encryptKeystore(context, Constants.TRANSFER, body.get(Constants.TRANSFER))));
} else {
appDataBase.keyDao().updateKeyTable(Constants.LOG_IN, Constants.encryptKeystore(context, Constants.LOG_IN, body.get(Constants.LOG_IN)));
appDataBase.keyDao().updateKeyTable(Constants.APP_PASS, Constants.encryptKeystore(context, Constants.APP_PASS, body.get(Constants.APP_PASS)));
appDataBase.keyDao().updateKeyTable(Constants.TRN_PASS, Constants.encryptKeystore(context, Constants.TRN_PASS, body.get(Constants.TRN_PASS)));
appDataBase.keyDao().updateKeyTable(Constants.FORGOT_PIN, Constants.encryptKeystore(context, Constants.FORGOT_PIN, body.get(Constants.FORGOT_PIN)));
appDataBase.keyDao().updateKeyTable(Constants.FORGOT_PASS, Constants.encryptKeystore(context, Constants.FORGOT_PASS, body.get(Constants.FORGOT_PASS)));
appDataBase.keyDao().updateKeyTable(Constants.WITHDRAW, Constants.encryptKeystore(context, Constants.WITHDRAW, body.get(Constants.WITHDRAW)));
appDataBase.keyDao().updateKeyTable(Constants.DEPOSIT, Constants.encryptKeystore(context, Constants.DEPOSIT, body.get(Constants.DEPOSIT)));
appDataBase.keyDao().updateKeyTable(Constants.TRANSFER, Constants.encryptKeystore(context, Constants.TRANSFER, body.get(Constants.TRANSFER)));
}
}
}
private void sendNotificationSystem(String title, String messageBody) {
lighting();
Intent intent = new Intent(this, NotificationsActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
//Uri soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.christmas_bells);
Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, "CH_ID")
.setSmallIcon(R.drawable.icon)
.setContentTitle(title)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(soundUri)
.setContentIntent(pendingIntent);
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
if (soundUri != null) {
// Changing Default mode of notification
notificationBuilder.setDefaults(Notification.DEFAULT_VIBRATE);
// Creating an Audio Attribute
AudioAttributes audioAttributes = new AudioAttributes.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
.setUsage(AudioAttributes.USAGE_ALARM)
.build();
// Creating Channel
NotificationChannel notificationChannel = new NotificationChannel("CH_ID", "Testing_Audio", NotificationManager.IMPORTANCE_HIGH);
notificationChannel.setSound(soundUri, audioAttributes);
mNotificationManager.createNotificationChannel(notificationChannel);
}
}
mNotificationManager.notify(0, notificationBuilder.build());
}
}