我正在构建一个有趣的小项目,它包含一个小型应用程序,该应用程序可以将通知从设备发送到另一个设备。目前,我正在为我的女朋友构建此应用程序,以便她只需按一下按钮就可以直接向我的手机发送通知。该应用程序在某些方面可以完美运行。如果我在同一系统上使用同一部手机,则可以正常运行,但是如果出现版本差距,则它不会接收或发送通知,此刻,我正在使用运行9.0版android的模拟器进行测试和我自己的6.0手机,我可以向模拟器发送通知,但是模拟器无法向我发送通知。
我正在尝试使其在我的6.0版本和8.0版本上运行。目前,使其正常工作的唯一方法是让2个Android的版本为9(pie)。
这就是我用来发送通知的内容。
private void sendNotification()
{
AsyncTask.execute(new Runnable() {
@Override
public void run() {
int SDK_INT = android.os.Build.VERSION.SDK_INT;
if (SDK_INT > 8) {
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder()
.permitAll().build();
StrictMode.setThreadPolicy(policy);
String send_email;
if (MainActivity.LoggedIn_User_Email.equals("user1@gmail.com")) {
send_email = "user2@gmail.com";
} else {
send_email = "user1@gmail.com";
}
try {
String jsonResponse;
URL url = new URL("https://onesignal.com/api/v1/notifications");
HttpURLConnection con = (HttpURLConnection) url.openConnection();
con.setUseCaches(false);
con.setDoOutput(true);
con.setDoInput(true);
con.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
con.setRequestProperty("Authorization", "Basic MTY4MzQ4OTQtYTU1MC00Y2VkLTk5YjgtMjE3OTU2ODFmMzZm");
con.setRequestMethod("POST");
String strJsonBody = "{"
+ "\"app_id\": \"5efc856c-684c-4e67-8380-38d74811b638\","
+ "\"filters\": [{\"field\": \"tag\", \"key\": \"User_ID\", \"relation\": \"=\", \"value\": \"" + send_email + "\"}],"
+ "\"data\": {\"foo\": \"bar\"},"
+ "\"contents\": {\"en\": \"I need attention!! NOW!\"}"
+ "}";
System.out.println("strJsonBody:\n" + strJsonBody);
byte[] sendBytes = strJsonBody.getBytes("UTF-8");
con.setFixedLengthStreamingMode(sendBytes.length);
OutputStream outputStream = con.getOutputStream();
outputStream.write(sendBytes);
int httpResponse = con.getResponseCode();
System.out.println("httpResponse: " + httpResponse);
if (httpResponse >= HttpURLConnection.HTTP_OK
&& httpResponse < HttpURLConnection.HTTP_BAD_REQUEST) {
Scanner scanner = new Scanner(con.getInputStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
} else {
Scanner scanner = new Scanner(con.getErrorStream(), "UTF-8");
jsonResponse = scanner.useDelimiter("\\A").hasNext() ? scanner.next() : "";
scanner.close();
}
System.out.println("jsonResponse:\n" + jsonResponse);
} catch (Throwable t) {
t.printStackTrace();
}
}
}
});
}
这是我的依赖关系
dependencies
{
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.firebase:firebase-auth:16.1.0'
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.google.firebase:firebase-core:16.0.6'
implementation 'com.onesignal:OneSignal:3.10.6'
}