Задача: выводить пользователю адресные сообщения, в трэй экрана телефона.
- В основном проекте, создадим сервис из шаблона New->Service. На выходе получим:
package ru.slonet.account.personalaccount; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class MyService extends Service { public MyService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } }
2. В основной активности, добавим на событие OnCreate, старт сервиса при запуске приложения:
getApplicationContext().startService(new Intent(getApplicationContext(), MyService.class));
3. Добавим в манифест разрешения и сервис:
<service android:name=".MyService" android:enabled="true" android:exported="true" > </service>
<uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
4. Для того что бы сервис стартовал при перезагрузке телефона автоматически, добавим в манифест слушателя события «перезагрузка»:
<receiver android:name=".BootBroadcast" android:enabled="true" android:exported="true" > <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>
И создадим класс BootBroadcast который будет выполняться после отлова события «Загрузка завершена»:
package ru.slonet.account.personalaccount; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class BootBroadcast extends BroadcastReceiver { public void AddToLog(String logtxt){ String TAG="ServiseAutostart"; Log.v(TAG, logtxt); }; @Override public void onReceive(Context context, Intent intent) { AddToLog("--сервис стартовал после перезагрузки " + intent.getStringExtra("ru.slonet.action.cooki")); context.startService(new Intent(context, MyService.class)); } }
5. В сервисе создадим периодическое задание по таймеру: читать JSON данные с ресурса интернете. И если что-то есть новенькое — то выводить в таскбар:
package ru.slonet.account.personalaccount; import android.app.AlarmManager; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.content.res.Resources; import android.graphics.BitmapFactory; import android.os.AsyncTask; import android.os.IBinder; import android.os.SystemClock; import android.preference.PreferenceManager; import android.util.Log; import android.widget.Toast; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.Timer; import java.util.TimerTask; import java.util.concurrent.TimeUnit; public class MyService extends Service { String uid; Timer mTimer; MyTimerTask mMyTimerTask; String message; public void AddToLog(String logtxt){ String TAG="ServiceLog"; Log.v(TAG, logtxt); }; public void SendMessage(CharSequence title,CharSequence mess) { Context context = getApplicationContext(); //инициатор - текущая активность int NOTIFY_ID = 1001; Intent notificationIntent = new Intent(context, Form1.class); PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT); NotificationManager nm = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); Resources res = context.getResources(); Notification.Builder builder = new Notification.Builder(context); builder.setContentIntent(contentIntent) .setSmallIcon(android.R.drawable.stat_sys_warning) .setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher)) .setTicker(mess) .setWhen(System.currentTimeMillis()) .setAutoCancel(true) .setContentTitle(title) .setContentText(mess); // Текст уведомления Notification n = builder.getNotification(); n.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE; nm.notify(NOTIFY_ID, n); }; void ParseTask() { HttpURLConnection urlConnection = null; BufferedReader reader = null; String resultJson = ""; Context gcontext; String LOG_TAG = "log_timer"; AddToLog("--парсим json"); // получаем данные с внешнего ресурса try { uid=uid.replace("; ","&"); URL url = new URL("http://ewdwe.wedwe-edwe.ru/getjsoin.php?"+uid); Log.d(LOG_TAG, "url: " + url); urlConnection = (HttpURLConnection) url.openConnection(); urlConnection.setRequestMethod("GET"); urlConnection.connect(); InputStream inputStream = urlConnection.getInputStream(); StringBuffer buffer = new StringBuffer(); reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) { buffer.append(line); } resultJson = buffer.toString(); } catch (Exception e) { e.printStackTrace(); Log.d(LOG_TAG, "--не смогли прочитать JSON"); } String strJson; strJson=resultJson; // выводим целиком полученную json-строку Log.d(LOG_TAG, strJson); JSONObject dataJsonObj = null; String secondName = ""; try { dataJsonObj = new JSONObject(strJson); JSONArray messages = dataJsonObj.getJSONArray("messages"); // 1. достаем инфо о втором друге - индекс 1 JSONObject frec = messages.getJSONObject(0); String titl = frec.getString("title"); //смотрим, а может тожэесамое сообщение? String mm; mm=frec.getString("message"); AddToLog("--сравниваю:"+message+" и "+mm); if (message.equals(mm)){} else { message = frec.getString("message"); Log.d(LOG_TAG, "title: " + titl); Log.d(LOG_TAG, "message: " + message); // ну и раз уж такое щасье, то выводим сообщение юзеру.. AddToLog("--Отправялем сообщение:"+message); SendMessage(titl, message); }; } catch (JSONException e) { e.printStackTrace(); } } public MyService() { } @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. throw new UnsupportedOperationException("Not yet implemented"); } public class MyTimerTask extends TimerTask { @Override public void run() { AddToLog("--выполнили по таймеру..."); ParseTask(); //new MyService.ParseTask().execute(); } } @Override public int onStartCommand(Intent intent, int flags, int startId) { AddToLog("--это я, твой сервис, я стартовал! "); SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); uid = sharedPreferences.getString("cooki", ""); AddToLog("--сервис: load uid2:" + uid); if (mTimer != null) { mTimer.cancel(); mTimer = null; } message=""; mTimer = new Timer(); mMyTimerTask = new MyTimerTask(); mTimer.schedule(mMyTimerTask, 1000, 5000); return Service.START_STICKY; } @Override public void onDestroy() { super.onDestroy(); AddToLog("--остановили сервис"); } }