abc.json
[{"id":1,"title":"1. heading of Tips","description":"welcome to post 1"},{"id":2,"title":"2. heading of Tips","description":"welcome to post 2"},{"id":3,"title":"3. heading of Tips","description":"welcome to post 3"},{"id":4,"title":"4. heading of Tips","description":"welcome to post 4"}]
我是android新手。 我希望我的服务检查服务器上的JSON文件是否已更新。如果更新,它将复制数组的最后一个元素,并通过sendNotification()方法将它们作为通知传递。
MyService.java
public class MyService extends Service {
private static final String TAG = "MyService";
String heading="this is heading";
String post = "this is post";
public MyService() {
}
@Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onCreate() {
Toast.makeText(this, "The new Service was Created", Toast.LENGTH_SHORT).show();
// call the on Message received
onMessageReceived(heading,post);
}
public void onMessageReceived(String remoteMessage, String body) {
// TODO(developer): Handle FCM messages here.
// If the application is in the foreground handle both data and notification messages here.
// 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.
Log.d(TAG, "From: " + remoteMessage);
Log.d(TAG, "Notification Message Body: " + body);
sendNotification(remoteMessage,body);
}
// [END receive_message]
/**
* Create and show a simple notification containing the received FCM message.
*
* @param messageBody FCM message body received.
*/
private void sendNotification(String messageBody, String post) {
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_ONE_SHOT);
Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = (NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_icon)
.setContentTitle(post)
.setContentText(messageBody)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());
}
// send notification ends
@Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
}
}