Вывод телефона и сервиса из спящего режима. Разработка под Android

Задача: обеспечить вывод телефона из спящего режима, воспроизвести звук и вибрацию при выводе уведомления.

Решение:

Создадим стартующий при загрузке сервис при помощи класса WakefulBroadcastReceiver.

Android Manifest:

— назначаем права на вывод из спящего режима, загрузку при перезагрузке, полный доступ в интернет и сеть

— обьявляем ресивер BootBroadcast как выполняемый при перезагрузке телефона



<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ru.sdfvsdf.noc.nocmessages">
<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" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />

<application
android:resource=»@xml/netsec»
android:allowBackup=»true»
android:icon=»@mipmap/ic_launcher»
android:label=»@string/app_name»
android:supportsRtl=»true»
android:theme=»@style/Theme.AppCompat.NoActionBar» >
<activity android:name=».Form1″>
<intent-filter>
<action android:name=»android.intent.action.MAIN» />

<category android:name=»android.intent.category.LAUNCHER» />
</intent-filter>
</activity>
<activity android:name=».Form2″ android:label=»MessList» >
</activity>

<receiver
android:name=».BootBroadcast»
android:enabled=»true»
android:exported=»true» >
<intent-filter>
<action android:name=»android.intent.action.BOOT_COMPLETED» />
</intent-filter>
</receiver>

<service
android:name=».MyService»
android:enabled=»true»
android:exported=»true» >
</service>

</application>

</manifest>

Код BootBroadcast.java:
Единственная функция — запускаем сервис MyService, активный в спящем режиме


package ru.dsfvsd.noc.nocmessages;

import android.content.Context;
import android.content.Intent;
import android.support.v4.content.WakefulBroadcastReceiver;
import android.util.Log;

/**
* Created by pavel on 08.06.17.
*/
public class BootBroadcast extends WakefulBroadcastReceiver {

public void AddToLog(String logtxt){
String TAG=»ServiseAutostart»;
Log.v(TAG, logtxt);
};

@Override
public void onReceive(Context context, Intent intent) {
Log.d(«неашипка», «—сервис стартовал после перезагрузки»);
//context.startService(new Intent(context, MyService.class));
Intent service = new Intent(context, MyService.class);
startWakefulService(context, service);

}
}

Код MyService.java:

— код который выполняется по таймеру и показывает сообщение пользователю, с выводом телефона из спящего режима


package ru.vdfvd.noc.nocmessages;

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.PowerManager;
import android.preference.PreferenceManager;
import android.util.Log;
import android.widget.ArrayAdapter;

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;

/**
* Created by pavel on 08.06.17.
*/
public class MyService extends Service {
Timer mTimer;
MyTimerTask mMyTimerTask;

public MyService() {
}
public class MyTimerTask extends TimerTask {

@Override
public void run() {
String elogin,epass;
SharedPreferences mSettings = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
elogin=mSettings.getString(«userlogin», «»);
epass=mSettings.getString(«userpass», «»);
Log.d(«неашипка», «—я сервис,чтото делаю по таймеру login:»+elogin);
//проверяем новые сообщения..
new GetAllNotReadMessages().execute(elogin,epass);

//new MyService.ParseTask().execute();
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
Log.d(«неашипка», «—сервис чтото поделал»);
throw new UnsupportedOperationException(«Not yet implemented»);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(«неашипка», «—я сервис,я стартовал»);
mTimer = new Timer();
mMyTimerTask = new MyTimerTask();
mTimer.schedule(mMyTimerTask, 10000, 10000);
SendNotif(«Сообщения NOC»,»Сервис в фоновом режиме»,1234);
return Service.START_STICKY;
}
@Override
public void onDestroy() {
Log.d(«неашипка», «—сервис уничтожен»);
super.onDestroy();
}
public void SendNotif(CharSequence title,CharSequence mess,int NOTIFY_ID) {
Context context = getApplicationContext(); //инициатор — текущая активность

Intent notificationIntent = new Intent(context, Form1.class);
notificationIntent.setFlags(notificationIntent.FLAG_ACTIVITY_CLEAR_TOP | notificationIntent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);

NotificationManager nm = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);

Resources res = context.getResources();
Notification.Builder builder = new Notification.Builder(context);

builder.setContentIntent(contentIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setLargeIcon(BitmapFactory.decodeResource(res, R.mipmap.ic_launcher))
.setTicker(mess)
.setWhen(System.currentTimeMillis())
.setAutoCancel(true)
.setContentTitle(title)
.setContentText(mess); // Текст уведомления

Notification n = builder.getNotification();
n.flags|= Notification.FLAG_NO_CLEAR;
nm.notify(NOTIFY_ID, n);

};

public void SendMessage(CharSequence title,CharSequence mess,int NOTIFY_ID) {
Context context = getApplicationContext(); //инициатор — текущая активность

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();
if (NOTIFY_ID==1){
n.defaults = Notification.DEFAULT_LIGHTS;
} else {
n.defaults = Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE;
// Intent intent = new Intent(context, Form2.class);
// startActivity(intent);
};
nm.notify(NOTIFY_ID, n);

 

PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), «TAG»);
wakeLock.acquire();

};
class GetAllNotReadMessages extends AsyncTask<String, Integer, String> {
@Override
protected String doInBackground(String… arg) {
String res;
BufferedReader reader = null;
String resultJson = «»;

res=null;
HttpURLConnection urlConnection = null;
Log.d(«неашипка», «—пробую получить все не прочитанные сообщения»);
try {
URL url = new URL(«http://noc.sdfvsdfvsdf.ru/getjsonmess.php?command=getnotreadmessages&username=»+arg[0]+»&pass=»+arg[1]);
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();
Log.d(«неашипка», «не читали: «+resultJson);
res=resultJson;
}
catch (Exception e) {
e.printStackTrace();
Log.d(«ашипка», «—не смогли получить сообщения»);
res=»-ERROR: Ошибка соединения!»;
SendMessage(«Ошибка NOC»,»Не смогли получить новые сообщения»,1);
}
return res;
};
@Override
protected void onPostExecute(String s) {
if (s.contains(«-ERROR»)!=true) {

JSONObject dataJsonObj = null;
try {
dataJsonObj = new JSONObject(s);
if(dataJsonObj.has(«msg») ) {
JSONArray mggs = dataJsonObj.getJSONArray(«msg»);
for (int i = 0; i < mggs.length(); i++) {
JSONObject mes = mggs.getJSONObject(i);
Log.d(«неашипка», «—отправили сообщение»);
SendMessage(mes.getString(«title»), mes.getString(«body»), mes.getInt(«id»));

};
};
} catch (JSONException e) {
Log.d(«ашипка», «—ошибка разбора json (или пусто)»);
e.printStackTrace();
};

} else {
SendMessage(«Ошибка NOC»,»Не смогли получить новые сообщения:»+s,1);
};
};

};
}

 

 

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Этот сайт использует Akismet для борьбы со спамом. Узнайте, как обрабатываются ваши данные комментариев.