So I have this code
public class notif extends Activity {
private static final int NOTIFY_ME_ID=1337;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final NotificationManager mgr=(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note=new Notification(R.drawable.icon,"New Problem ",System.currentTimeMillis());
note.flags|=Notification.FLAG_AUTO_CANCEL;
PendingIntent i=PendingIntent.getActivity(this, 0,new Intent(this,list.class), 0);
note.setLatestEventInfo(this,"Problem Occured","Click to see the problem",i);
mgr.notify(NOTIFY_ME_ID,note);
}
This code is about making notifications but i want it to just appear on my notification on top an not opening any page at first so it's like the notification can appear in the main menu without opening any page at first like.the sms notification that appear on top only without having to see the entire sms until we click the notification so can someone help me with this? :)
Create a class NotificationAlert and paste the code below there:
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
public class NotificationAlert extends Activity {
private static final int NOTIFY_ME_ID=1337;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notification_alert);
/*********** Create notification ***********/
final NotificationManager mgr=
(NotificationManager)this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note=new Notification(R.drawable.stat_notify_chat,
"Android Example Status message!",
System.currentTimeMillis());
// This pending intent will open after notification click
PendingIntent i=PendingIntent.getActivity(this, 0,
new Intent(this, NotifyMessage.class),
0);
note.setLatestEventInfo(this, "Android Example Notification Title",
"This is the android example notification message", i);
//After uncomment this line you will see number of notification arrived
//note.number=2;
mgr.notify(NOTIFY_ME_ID, note);
}
}
Create a class NotifyMessage and paste the code below there:
import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;
public class NotifyMessage extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TextView txt=new TextView(this);
txt.setText("Activity after click on notification");
setContentView(txt);
}
}
I think I know now that i have to use service and this is the code for making that service hope it helps other
public class servicenotif extends Service {
private static final String TAG = "servicenotif";
private static final int NOTIFY_ME_ID=1337;
private String url="Your URL";
SharedPreferences mPrefs;
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
//Untuk bikin alarm yang ngecek ke database setiap 30 detik
Log.d(TAG, "onCreate");
Intent i = new Intent(this, servicenotif.class);
PendingIntent pintent = PendingIntent.getService(this, 0, i,0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 30*1000, pintent);
}
#Override
public void onStart(Intent intent, int startId) {
//buat preference
new LoginAsyncTask().execute();
//Note: You can start a new thread and use it for long background processing from here.
}
class LoginAsyncTask extends AsyncTask<String, Integer, String> {
String response = "";
ProgressDialog dialog;
//step2
#Override
protected String doInBackground(String... params) {
// TODO Auto-generated method stub
try {
//publishProgress(190);
mPrefs = getSharedPreferences("Preference", Context.MODE_PRIVATE);
//ngambil data preference
String txtTransID=mPrefs.getString("tid", "");
if(txtTransID.equals("")){
txtTransID="0";
}
int t=Integer.valueOf(txtTransID);
//membuat notifikasi yang muncul apabila ada problem dan hanya muncul lagi apabila ada problem baru
JSONObject json = JSONfunctions.getJSONfromURL("Your URL");
JSONObject js = JSONfunctions.getJSONfromURL("Your URL");
JSONObject j = JSONfunctions.getJSONfromURL("Your URL");
try{
JSONArray makanan = json.getJSONArray("makanan");
for(int i=0;i<makanan.length();i++){
HashMap<String, String> map = new HashMap<String, String>();
JSONObject jsonobj = makanan.getJSONObject(i);
map.put("id",jsonobj.getString("Status"));
//mengecek status yang berubah dari nol menjadi 1
if(jsonobj.getString("Status").equals("1")){
JSONArray aku=js.getJSONArray("makanan");
for(int a=0;a<aku.length();a++)
{
HashMap<String, String> mp = new HashMap<String, String>();
JSONObject jsb = aku.getJSONObject(a);
mp.put("take", jsb.getString("Taken"));
//mengecek Taken yang belum diambil
if(jsb.getString("Taken").equals("null")){
JSONArray tid=j.getJSONArray("makanan");
for(int Ti=0;Ti<tid.length();Ti++){
HashMap<String,String> trans=new HashMap<String, String>();
JSONObject jo=tid.getJSONObject(Ti);
trans.put("trans", jo.getString("Trans_ID"));
int TID;
//mengecek Trans_ID yang ditambahkan apa ada yang baru atau tidak
if(jo.getString("Trans_ID").equals("")){
TID=0;
}
else{
TID=Integer.valueOf(jo.getString("Trans_ID"));
}
if(t<TID){
Editor editor = mPrefs.edit();
editor.putString("tid", jo.getString("Trans_ID"));
editor.commit();
map.put("nama", jsonobj.getString("Andon_Type"));
map.put("harga", jsonobj.getString("Line"));
String andon=jsonobj.getString("Andon_Type");
String line=jsonobj.getString("Line");
NotificationManager mgr=(NotificationManager)servicenotif.this.getSystemService(Context.NOTIFICATION_SERVICE);
Notification note=new Notification(R.drawable.icon,"New Problem ",System.currentTimeMillis());
note.flags|=Notification.FLAG_AUTO_CANCEL;
PendingIntent b=PendingIntent.getActivity(servicenotif.this, 0,new Intent(servicenotif.this,list2.class),PendingIntent.FLAG_ONE_SHOT);
note.setLatestEventInfo(servicenotif.this,"Problem Occured","Click to see the list of problem",b);
note.defaults=Notification.DEFAULT_ALL;
mgr.notify(NOTIFY_ME_ID,note);
}
//membuat notifikasi muncul lagi apabila data di reset
else if(t>TID){
Editor editor = mPrefs.edit();
editor.putString("tid", "");
editor.commit();
}
}
}
}
}
}
}
catch(JSONException e){
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
publishProgress(190);
return null;
}
//last step
#Override
protected void onPostExecute(String result) {
//dialog.cancel();
}
private void onCreate(Object object) {
// TODO Auto-generated method stub
}
#Override
protected void onProgressUpdate(Integer... values) {
// TODO Auto-generated method stub
// biasanya untuk progress download
int nilai = values[0];
// didapat dari publish progress
}
//step1
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
// buat bikin dialog loading
/*dialog = ProgressDialog.show(list.this, "Loading",
"Please wait..");*/
super.onPreExecute();
}
public void write(String fileName){
BufferedWriter bw=null;
try{
bw=new BufferedWriter(new OutputStreamWriter(openFileOutput(fileName,Context.MODE_PRIVATE)));
}
catch(Exception e){
}
}
}
private void getRequest(String Url2) {
// TODO Auto-generated method stub
HttpClient client = new DefaultHttpClient();
HttpGet request = new HttpGet(url);
try {
HttpResponse response = client.execute(request);
} catch (Exception ex) {
Toast.makeText(this, "Penghandelan Gagal !", Toast.LENGTH_SHORT)
.show();
}
}
private String request(HttpResponse response) {
// TODO Auto-generated method stub
String result = "";
try {
InputStream in = response.getEntity().getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(in));
StringBuilder str = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
str.append(line + "\n");
}
in.close();
result = str.toString();
} catch (Exception ex) {
result = "Error";
}
return result;
}
#Override
//untuk logout mematikan notifikasi dan alarm supaya tidak menjalankan service lagi
public void onDestroy() {
NotificationManager mgr=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
mgr.cancelAll();
Toast.makeText(this, "Log out successfull", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
PendingIntent i=PendingIntent.getService(this, 0,new Intent(this,servicenotif.class), 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
alarm.cancel(i);
}
Hope this will help
Related
Hi i am developing one android app where i upload multipal images to the server using Service that means i upload the images to server even my app is closed from background..
Also i displayed Nootification and displayed progress of image uploading in the notification .
The main problem is that i displayed alert dialog when all uploading is completed.But when i close the app then also that dialog is appeared on the screen.
i.e.
if i pause the app or hide the app then that alert dialog will display at home screen
i want to display alert dialog
here is my service
static public class UploadService extends Service {
private String LOG_TAG = "BoundService";
private IBinder mBinder = new MyBinder();
ArrayList<CustomGallery> listOfPhotos;
int i = 0;
long totalSize=0;
NotificationManager manager;
String response_str = null;
long totalprice = 0;
Notification.Builder builder;
SelectedAdapter_Test selectedAdapter;
NotificationCompat.Builder mBuilder;
String strsize, strtype, usermail, total, strmrp, strprice, strlab, strcity, abc, strdel_type, struname, imageName;
ArrayList<CustomGallery> dataT = new ArrayList<CustomGallery>();
#Nullable
#Override
public IBinder onBind(Intent intent) {
Log.v(LOG_TAG, "in onBind");
return mBinder;
}
#Override
public void onRebind(Intent intent) {
Log.v(LOG_TAG, "in onRebind");
super.onRebind(intent);
}
#Override
public boolean onUnbind(Intent intent) {
Log.v(LOG_TAG, "in onUnbind");
return true;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
selectedAdapter = new SelectedAdapter_Test(getApplicationContext(), dataT);
Toast.makeText(UploadService.this, "Service Started ", Toast.LENGTH_SHORT).show();
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
listOfPhotos = (ArrayList<CustomGallery>) intent.getSerializableExtra("listof");
strsize = intent.getStringExtra("strsize");
strtype = intent.getStringExtra("strtype");
usermail = intent.getStringExtra("user_mail");
strmrp = intent.getStringExtra("strmrp");
strprice = intent.getStringExtra("strprice");
strlab = intent.getStringExtra("strlab");
strcity = intent.getStringExtra("strcity");
struname = intent.getStringExtra("strusername");
strdel_type = intent.getStringExtra("strdel_type");
abc = intent.getStringExtra("foldername");
manager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle("Picture Upload")
.setContentText("Upload in progress")
.setSmallIcon(R.drawable.ic_launcher);
Intent resultIntent = new Intent(this, SelectPhotos.class);
PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
resultIntent.setAction("android.intent.action.MAIN");
resultIntent.addCategory("android.intent.category.LAUNCHER");
new UploadFileToServer().execute();
return Service.START_NOT_STICKY;
}
public class MyBinder extends Binder {
UploadService getService() {
return UploadService.this;
}
}
private class UploadFileToServer extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
// setting progress bar to zero
super.onPreExecute();
pb.setProgress(0);
}
#Override
protected void onProgressUpdate(Integer... progress) {
Log.v("Abhijit122", "" + String.valueOf(progress[0]) + "%");
pb.setProgress(progress[0]);
tp.setText(String.valueOf(progress[0]) + "%");
Log.e("ef", "df" + incr);
ti.setText((incr+1)+"/"+listOfPhotos.size());
}
#Override
protected String doInBackground(String... params) {
return uploadFile();
}
#SuppressWarnings("deprecation")
private String uploadFile() {
for (incr = 0; incr < listOfPhotos.size(); incr++) {
mBuilder.setProgress(listOfPhotos.size(), incr, false);
manager.notify(1, mBuilder.build());
try {
File f = new File(listOfPhotos.get(i).sdcardPath.toString());
int j = i + 1;
j++;
imageName = f.getName();
totalprice = totalprice + Long.parseLong(strprice);
total = String.valueOf(totalprice);
Log.e("Totalprice", " " + total);
String responseString = null;
final HttpClient httpclient = new DefaultHttpClient();
final HttpPost httppost = new HttpPost(URL); //TODO - to hit URL);
AndroidMultiPartEntity entity = new AndroidMultiPartEntity(
new AndroidMultiPartEntity.ProgressListener() {
#Override
public void transferred(long num) {
publishProgress((int) ((num / (float) totalSize) * 100));
}
});
File sourceFile = new File(listOfPhotos.get(i).sdcardPath);
// Adding file data to http body
entity.addPart("image", new FileBody(sourceFile));
entity.addPart("foldername", new StringBody(abc));
entity.addPart("size",
new StringBody(strsize));
entity.addPart("type",
new StringBody(strtype));
entity.addPart("username",
new StringBody(usermail));
entity.addPart("total",
new StringBody(total));
Log.e("Totalprice", "adf " + total);
entity.addPart("mrp",
new StringBody(strmrp));
entity.addPart("price",
new StringBody(strprice));
entity.addPart("lab",
new StringBody(strlab));
entity.addPart("city",
new StringBody(strcity));
entity.addPart("imagename",
new StringBody(imageName));
entity.addPart("deltype",
new StringBody(strdel_type));
entity.addPart("initflag",
new StringBody(""+initflag++));
entity.addPart("lab_username",
new StringBody(struname));
totalSize = entity.getContentLength();
httppost.setEntity(entity);
HttpResponse response = httpclient.execute(httppost);
HttpEntity r_entity = response.getEntity();
response_str = EntityUtils.toString(r_entity);
Log.d("Dhruva", "" + response_str);
if (r_entity != null) {
Log.v("Abhijit", "" + response_str);
}
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
return response_str;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
mBuilder.setContentText("Upload complete")
// Removes the progress bar
.setProgress(0, 0, false);
manager.notify(1, mBuilder.build());
AlertDialog alertDialog = new AlertDialog.Builder(getApplicationContext())
.setTitle("Success")
.setMessage("Successfully uploaded images...")
.setCancelable(false)
.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
}
}
}
i want to display alert dialog when all uploading is completed and when i click on ok button i want to start next activity.
This is my way to open next activity after successful uploading of images through service.also i implemented notification then which activity should i open when i click on notification
If there is another way please give me suggestion.
I have a drawerlayout and he call many fragments and they have asynctask within, also i have created a notification service, it's work very fine in api level < 11 but when the level is > 10 the asynctask of fragment only work when the service is not running, why?
My code of service is here
public class NotificationService extends Service {
MyTask myTask;
private final String url_notificaciones = "http://www.domain.com/domain/getNotificaciones.php";
private static final String TAG_TIPO_NOTIFICACION = "tipo_notificacion";
private static final String TAG_TITULO_NOTIFICACION= "titulo_notificacion";
private static final String TAG_DESCRIPCION_NOTIFICACION= "descripcion_notificacion";
private String jsonResult;
SessionManagement session;
boolean InitializeNotificationManager = true;
private HashMap<String, String> user;
private String id_datos_usuarios_session;
private JsonReadTask task;
private Handler handler = new Handler();
private TaskCanceler taskCanceler;
#Override
public void onCreate() {
super.onCreate();
try {
session = new SessionManagement(getApplication());
user = session.getUserDetails();
id_datos_usuarios_session = user.get(SessionManagement.KEY_ID_DATOS_USUARIOS).toString();
}catch (Exception e){
InitializeNotificationManager = false;
}
myTask = new MyTask();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
myTask.execute();
return START_NOT_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
myTask.cancel(true);
}
#Override
public IBinder onBind(Intent intent) {
throw new UnsupportedOperationException("Not yet implemented");
}
private class MyTask extends AsyncTask<String, String, String> {
private String date;
private boolean cent;
#Override
protected void onPreExecute() {
super.onPreExecute();
cent = true;
}
#Override
protected String doInBackground(String... params) {
while (cent) {
try {
if(isNetworkStatusAvialable (getApplication())) {
accessWebService();
}
// Stop 20s
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
return null;
}
#Override
protected void onProgressUpdate(String... values) {
//Toast.makeText(getApplicationContext(), "Hora actual: ", Toast.LENGTH_SHORT).show();
}
#Override
protected void onCancelled() {
super.onCancelled();
cent = false;
}
}
public void accessWebService(){
task = new JsonReadTask();
taskCanceler = new TaskCanceler(task);
handler.postDelayed(taskCanceler, 15*1000);
task.execute(new String[]{url_notificaciones});
}
private class JsonReadTask extends AsyncTask<String, Void, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(params[0]);
try {
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("get_app_id_datos_usuarios", id_datos_usuarios_session));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
jsonResult = inputStreamToString(
response.getEntity().getContent()).toString();
}
catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
private StringBuilder inputStreamToString(InputStream is) {
String rLine = "";
StringBuilder answer = new StringBuilder();
BufferedReader rd = new BufferedReader(new InputStreamReader(is));
try {
while ((rLine = rd.readLine()) != null) {
answer.append(rLine);
}
} catch (IOException e) {
// e.printStackTrace();
Toast.makeText(getApplicationContext(),
"Error..." + e.toString(), Toast.LENGTH_LONG).show();
}
return answer;
}
#Override
protected void onPostExecute(String result) {
ListDrwaer();
}
// build hash set for list view
public void ListDrwaer() {
try {
JSONObject jsonResponse = new JSONObject(jsonResult);
JSONArray jsonMainNode = jsonResponse.optJSONArray("notification");
JSONObject jsonChildNode = jsonMainNode.getJSONObject(0);
String tipo_notificacion = jsonChildNode.getString(TAG_TIPO_NOTIFICACION);
String titulo_notificacion = jsonChildNode.getString(TAG_TITULO_NOTIFICACION);
String descripcion_notificacion = jsonChildNode.getString(TAG_DESCRIPCION_NOTIFICACION);
if(tipo_notificacion.equals("1")) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("MenuNotificationFragment", "MyFriendsRequired");
PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
// Creamos la notificación. Las acciones son de "mentirijilla"
Notification noti = new NotificationCompat.Builder(getApplicationContext())
.setContentTitle(titulo_notificacion)
.setContentText(descripcion_notificacion).setSmallIcon(R.mipmap.icon_app)
.setContentIntent(pIntent)
.setLights(0xffff00, 4000, 100)
/*.addAction(R.drawable.ic_arrow, "Llamada", pIntent)
.addAction(R.drawable.ic_arrow, "Más", pIntent)
.addAction(R.drawable.ic_arrow, "Mucho Más", pIntent)*/.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Ocultamos la notificación si ha sido ya seleccionada
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
//Sound notification
try {
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), ringtoneUri);
ringtone.play();
} catch (Exception e) {
}
//Vibrate notification
try {
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 2000};
// The '0' here means to repeat indefinitely
// '0' is actually the index at which the pattern keeps repeating from (the start)
// To repeat the pattern from any other point, you could increase the index, e.g. '1'
v.vibrate(pattern, -1);
} catch (Exception e) {
}
}else if(tipo_notificacion.equals("2")){
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.putExtra("MenuNotificationFragment", "MyBussinesRequired");
PendingIntent pIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
// Creamos la notificación. Las acciones son de "mentirijilla"
Notification noti = new NotificationCompat.Builder(getApplicationContext())
.setContentTitle(titulo_notificacion)
.setContentText(descripcion_notificacion).setSmallIcon(R.mipmap.icon_app)
.setContentIntent(pIntent)
.setLights(0xffff00, 4000, 100)
/*.addAction(R.drawable.ic_arrow, "Llamada", pIntent)
.addAction(R.drawable.ic_arrow, "Más", pIntent)
.addAction(R.drawable.ic_arrow, "Mucho Más", pIntent)*/.build();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Ocultamos la notificación si ha sido ya seleccionada
noti.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(0, noti);
//Sound notification
try {
Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone ringtone = RingtoneManager.getRingtone(getApplicationContext(), ringtoneUri);
ringtone.play();
} catch (Exception e) {
}
//Vibrate notification
try {
// Get instance of Vibrator from current Context
Vibrator v = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
// Start without a delay
// Vibrate for 100 milliseconds
// Sleep for 1000 milliseconds
long[] pattern = {0, 100, 2000};
// The '0' here means to repeat indefinitely
// '0' is actually the index at which the pattern keeps repeating from (the start)
// To repeat the pattern from any other point, you could increase the index, e.g. '1'
v.vibrate(pattern, -1);
} catch (Exception e) {
}
}
} catch (JSONException e) {
}
}
}// end async task
//If the internet connection is ok
public static boolean isNetworkStatusAvialable (Context context) {
try {
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivityManager != null) {
NetworkInfo netInfos = connectivityManager.getActiveNetworkInfo();
if (netInfos != null)
if (netInfos.isConnected())
return true;
}
}catch (Exception e){
return false;
}
return false;
}
public class TaskCanceler implements Runnable{
private AsyncTask taskR;
public TaskCanceler(AsyncTask task) {
this.taskR = task;
}
#Override
public void run() {
if (task.getStatus() == AsyncTask.Status.RUNNING ) {
task.cancel(true);
}
}
}
}
Starting on Android 11 AsyncTask objects shares a single thread. So your service is blocking that thread, and the fragments can't run. The easiest solution is pretty obvious here, don't use AsyncTask for the service. It doesn't even make sense to use it there because AsyncTask is meant to deliver results back on the UI thread, something your service doesn't need to do. Here is a possible solution:
public class MyService extends Service implements Runnable {
private HandlerThread = ht;
private Handler handler;
#Override
public void onCreate() {
super.onCreate();
try {
session = new SessionManagement(getApplication());
user = session.getUserDetails();
id_datos_usuarios_session = user.get(SessionManagement.KEY_ID_DATOS_USUARIOS).toString();
}catch (Exception e){
InitializeNotificationManager = false;
}
ht = new HandlerThread("MyService");
ht.start();
handler = new Handler(ht.getLooper());
handler.post(this);
}
#Override
public void onDestroy() {
super.onDestroy();
handler.removeCallbacks(this);
ht.quit();
ht = null;
handler = null;
}
#Override
public void run(){
if(isNetworkStatusAvialable (getApplication())) {
accessWebService();
}
handler.postDelayed(20000, this);
}
}
I want My Application has to run in a background. The Application is majorly meant for sending push notification based on IBeacons i.e low-power Bluetooth technology given by Apple.
This is good My Application able to get the notification but it should be in open mode(App should be open). But I want My application has to run in the background like whenever a user enters into the IBeacon proximity range it internally has to get the notification.
MainClass:
public class MainActivity extends Activity {
private static final String ESTIMOTE_PROXIMITY_UUID = "B9407F30-F5F8-466E-AFF9-25556B57FE6D";
private static final Region ALL_ESTIMOTE_BEACONS = new Region("regionId",
ESTIMOTE_PROXIMITY_UUID, null, null);
protected static final String TAG = "EstimoteiBeacon";
BeaconManager beaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final TextView tx = (TextView) findViewById(R.id.textView1);
final List<Integer> test1 = new ArrayList<Integer>();
beaconManager = new BeaconManager(this);
beaconManager.connect(new BeaconManager.ServiceReadyCallback() {
#Override
public void onServiceReady() {
final ArrayList AList = new ArrayList();
try {
beaconManager.startRanging(ALL_ESTIMOTE_BEACONS);
beaconManager
.setRangingListener(new BeaconManager.RangingListener() {
#Override
public void onBeaconsDiscovered(Region arg0,
List<Beacon> beacons) {
for (Beacon beacon : beacons) {
int major = beacon.getMajor();
test1.add(major);
AList.add(major);
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
intent.putIntegerArrayListExtra("test", (ArrayList<Integer>) test1);
tx.setText(String.valueOf(major));
startActivity(intent);
}
}
});
} catch (RemoteException e) {
Log.e("error", "Cannot start ranging", e);
}
}
});
}
// ---stop ranging for beacons when activity is killed---
#Override
protected void onStop() {
super.onStop();
try {
beaconManager.stopRanging(ALL_ESTIMOTE_BEACONS);
} catch (RemoteException e) {
Log.e
(TAG, "Cannot stop", e);
}
}}
SecondClass
public class SecondActivity extends Activity {
String name,str;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.second);
//Bundle extras = getIntent().getExtras();
TextView tv1 = (TextView) findViewById(R.id.textView1);
TextView tv2 = (TextView) findViewById(R.id.textView2);
TextView tv3 = (TextView) findViewById(R.id.textView3);
Intent intent=getIntent();
ArrayList<Integer> test = intent.getIntegerArrayListExtra("test");
tv1.setText(test.get(0).toString());
tv2.setText(test.get(1).toString());
tv3.setText(test.get(2).toString());
String loginRequest = "http://172.17.13.10:8080/RESTfulDemoDerby/webresources/com.mss.mmxregistration/Message?maxvalue=32623";
Log.e("retalier url", loginRequest);
HttpGet request = new HttpGet(loginRequest);
Bluetooth loginTask = new Bluetooth(
SecondActivity.this, request);
loginTask.execute();
}
class Bluetooth extends Bluetoothtask {
public Bluetooth(Context context, HttpRequestBase request) {
super(context, request);
// TODO Auto-generated constructor stub
}
#Override
protected void onPostExecute(String result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (result != null) {
DocumentBuilderFactory factory = DocumentBuilderFactory
.newInstance();
DocumentBuilder builder;
InputSource is;
try {
factory.setNamespaceAware(true);
builder = factory.newDocumentBuilder();
is = new InputSource(new StringReader(result));
Document doc = builder.parse(is);
NodeList list = doc.getElementsByTagName("Payload");
result = list.item(0).getTextContent();
} catch (ParserConfigurationException e) {
} catch (SAXException e) {
} catch (IOException e) {
}
JSONObject jsonObj;
Gson gson = new Gson();
try {
jsonObj = new JSONObject(result);
Log.e("Result", result);
JSONObject jsonResponse;
try {
jsonResponse = new JSONObject(result);
JSONArray cast = jsonResponse.getJSONArray("result");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
name = actor.getString("message");
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Context context = getApplicationContext();
CharSequence text = "TURNING_ON BLUETOOTH";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, text, 15);
toast.show();
NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
#SuppressWarnings("deprecation")
Notification notification = new Notification(R.drawable.ic_launcher,
"New Message", System.currentTimeMillis());
Intent notificationIntent = new Intent(SecondActivity.this, SecondActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(SecondActivity.this, 0,
notificationIntent, 0);
notification.setLatestEventInfo(SecondActivity.this, "Title",
name, pendingIntent);
notificationManager.notify(9999, notification);
} catch (Exception e) {
}
}
}
}#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
We can use Broadcast receivers for background app running but for this how we will implement for this example.
Unfortunately you've built everything around Asynctasks and activities which will not suite your goal. You want to look up services.
Once you've moved your logic to a service, then you'll want to start/stop that service based on broadcast receivers or a persistent notification. Then your Activity can bind to your services to get more information from them if you want or you can use other forms of service->activity communication like broadcasts.
Note that this will likely be a battery drainer so you'll want to provide your users the ability to turn it off or at least opt in/out.
I have an asyncTask in my services . It calls for an asyncTask every 10 seconds . The problem is I got this error sometimes and app c
i'm calling for an asyncTask in my services , it runs every 10 second for checking some data. Some times I get this error :
Services_chat$1.run(Services_chat.java:50)
at java.util.Timer$TimerImpl.run(Timer.java:284)
Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:121)
at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:607)
at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:607)
at android.os.AsyncTask.<clinit>(AsyncTask.java:190)
... 2 more
java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
at android.os.Handler.<init>(Handler.java:121)
at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:607)
at android.os.AsyncTask$InternalHandler.<init>(AsyncTask.java:607)
at android.os.AsyncTask.<clinit>(AsyncTask.java:190)
at ir.radaar.goblin.Services_chat$1.run(Services_chat.java:50)
at java.util.Timer$TimerImpl.run(Timer.java:284)
this is my service code :
public class Services_chat extends Service {
Boolean runCode = false,finished=false;;
SharedPreferences settings;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
runCode = true;
settings = getSharedPreferences("settings", MODE_PRIVATE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
if (runCode) {
try {
new GetChat().execute();
} catch (Exception e) {
}
}
}
}, 0, 10000);// put here time 1000 milliseconds=1 second
return Service.START_STICKY;
}
public class GetChat extends AsyncTask<Void, Void, Void> {
private static final String TAG_CONTACTS = "contacts";
JSONArray contacts = null;
SharedPreferences settings;
DatabaseHandler db;
long when;
Random rd;
int randomid = 0, icon = 0;
String alarmText = "", titles = "";
String usernameFrom = "", msg = "";
#Override
protected void onPreExecute() {
super.onPreExecute();
try {
settings = getSharedPreferences("settings", MODE_PRIVATE);
db = new DatabaseHandler(Services_chat.this);
if (!db.isOpen())
db.open();
runCode=false;
} catch (Exception e) {
}
}
#Override
protected Void doInBackground(Void... params) {
Spots_tab1_json sh = new Spots_tab1_json();
String jsonStr = sh.makeServiceCall(
"http://url.com/getUnreadChat.php?userTo=" + settings.getString("username", ""),
Spots_tab1_json.GET);
if (jsonStr != null) {
try {
JSONObject jsonObj = new JSONObject(jsonStr);
contacts = jsonObj.getJSONArray(TAG_CONTACTS);
for (int i = 0; i < contacts.length(); i++) {
JSONObject c = contacts.getJSONObject(i);
msg = new String(c.getString("msg").getBytes("ISO-8859-1"), "UTF-8");
usernameFrom = new String(c.getString("from").getBytes("ISO-8859-1"), "UTF-8");
randomid = Integer.parseInt(new String(c.getString("id").getBytes("ISO-8859-1"), "UTF-8"));
db.insertUnreadChat(randomid);
db.insertChat(msg, "", usernameFrom, settings.getString("username", ""));
}
} catch (Exception e) {
}
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
runCode=true;
if (contacts != null) {
if (contacts.length() > 0) {
try {
if (contacts.length() > 0) {
// ///////////////hide notification manager/////////
NotificationManager notifies2 = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notifies2.cancelAll();
rd = new Random();
icon = R.drawable.ic_launcher;
NotificationManager notifies = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Intent notifyIntent = new Intent(Services_chat.this, Chat.class);
notifyIntent.putExtra("username", usernameFrom);
PendingIntent pendingintent = PendingIntent.getActivity(Services_chat.this, 0,
notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);
when = System.currentTimeMillis();
Notification notification = new Notification(icon, msg, when);
notification.setLatestEventInfo(Services_chat.this, Z_Farsi.Convert("گفنگوی جدید"),
msg, pendingintent);
notifies.notify(randomid, notification);
Uri not = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Ringtone r = RingtoneManager.getRingtone(getApplicationContext(), not);
r.play();
}
} catch (Exception e) {
}
}
}
}
}
}
What am I doing wrong ?
Thanks
Example: In my application I have client,distributors and server.client ask questions to server and server will reply for that question via Gcm push notification.I have implemented this by googling it and push notification tutorials.
And my issue is, if I send a question from client,it gets displayed in server by parsing the link but I'm not getting the push notification. any one help me with this.I don't know where I have done mistake. Any suggestion to implement this functionality via push notification. server side script is write in php
I have posted the server part code...here only i want the push notification
my GCM class
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.media.RingtoneManager;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import android.os.Bundle;
import android.support.v4.app.NotificationCompat;
import com.google.android.gcm.GCMBaseIntentService;
public class GCMIntentService extends GCMBaseIntentService
{
private static final String TAG = "GCM Tutorial::Service";
// Use your PROJECT ID from Google API into SENDER_ID
public static final String SENDER_ID = "projectid";
//SharedPreferences prefs;
//DbHelper db;
String xx = "";
public GCMIntentService() {
super(SENDER_ID);
}
#Override
protected void onRegistered(Context context, String registrationId) {
//prefs = this.getSharedPreferences("", Context.MODE_PRIVATE);
//SharedPreferences.Editor prefsEditor = prefs.edit();
//prefsEditor.putString("registrationid", registrationId);
//prefsEditor.commit();
Log.i(TAG, "onRegistered: registrationId=" + registrationId);
xx = registrationId;
Toast.makeText(getApplicationContext(), xx, Toast.LENGTH_LONG).show();
System.out.println("Register : "+registrationId);
}
#Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "onUnregistered: registrationId=" + registrationId);
}
#SuppressLint("NewApi")
#Override
protected void onMessage(Context context, Intent data) {
//db = new DbHelper(context);
//db.openToWrite();
String message;
// Message from PHP server
message = data.getStringExtra("message");
// Open a new activity called GCMMessageView
//db.insertmessage(message);
System.out.println("inside gcm class");
Intent intent = new Intent(this, MainActivity.class);
// Pass data to the new activity
intent.putExtra("message", message);
// Starts the activity on notification click
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Create the notification with a notification builder
Notification notification = new Notification.Builder(this)
.setSmallIcon(R.drawable.ic_launcher)
.setWhen(System.currentTimeMillis())
.setContentTitle("New message")
.setContentText(message).setContentIntent(pIntent)
.getNotification();
// Remove the notification on click
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.sound =
RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
notification.defaults |= Notification.DEFAULT_VIBRATE;
NotificationManager manager = (NotificationManager)context.getSystemService(NOTIFICATION_SERVICE);
manager.notify(R.string.app_name, notification);
{
// Wake Android Device when notification received
PowerManager pm = (PowerManager) context
.getSystemService(Context.POWER_SERVICE);
final PowerManager.WakeLock mWakelock = pm.newWakeLock(
PowerManager.FULL_WAKE_LOCK
| PowerManager.ACQUIRE_CAUSES_WAKEUP, "GCM_PUSH");
mWakelock.acquire();
// Timer before putting Android Device to sleep mode.
Timer timer = new Timer();
TimerTask task = new TimerTask() {
public void run() {
mWakelock.release();
}
};
timer.schedule(task, 5000);
}
}
#Override
protected void onError(Context arg0, String errorId) {
Log.e(TAG, "onError: errorId=" + errorId);
}
}
question class
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.Settings.Secure;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class prompt extends Activity
{
Button prompt_ok,prompt_cancel;
private static final String url="http://maps.googleapis.com/maps/api/geocode/json?address=";
private static final String url1="&sensor=false";
EditText zip,noofsup;
JSONArray results;
JSONObject geometry,location;
String latt,lngg,ques;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
Intent in=getIntent();
ques=in.getStringExtra("questionfornext");
setContentView(R.layout.prompt);
zip=(EditText)findViewById(R.id.zipcode);
noofsup=(EditText)findViewById(R.id.noofsupplier);
}
public void onClick(View view)
{
String zipcode=zip.getText().toString();
String finalurl=url+zipcode+url1;
new GetData().execute();
new GetRegister().execute();
new GetQuestion().execute();
Intent in=new Intent(getApplicationContext(),MainActivity.class);
startActivity(in);
setContentView(R.layout.activity_main);
}
public void onCancel(View v)
{
Intent in=new Intent(getApplicationContext(),MainActivity.class);
startActivity(in);
setContentView(R.layout.activity_main);
}
private class GetData extends AsyncTask<Void, Void, Void>
{
String status;
String zipcode=zip.getText().toString();
String finalurl=url+zipcode+url1;
#Override
protected void onPreExecute()
{
super.onPreExecute();
// Showing progress dialog
}
#Override
protected Void doInBackground(Void... arg0)
{
// Creating service handler class instance
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String jsonStr = sh.makeServiceCall(finalurl, ServiceHandler.GET);
Log.d("Response: ", "> " + jsonStr);
if (jsonStr != null)
{
try
{
JSONObject jsonObj = new JSONObject(jsonStr);
status=jsonObj.getString("status");
System.out.println("status"+status);
results=jsonObj.getJSONArray("results");
for(int j=0;j==0;j++)
{
JSONObject c=results.getJSONObject(0);
geometry=c.getJSONObject("geometry");
JSONObject ob=geometry.getJSONObject("location");
latt=ob.getString("lat");
lngg=ob.getString("lng");
// String latt=location.getString("lat");
//String lngg=location.getString("lng");
System.out.println("latt"+latt);
System.out.println("lng"+lngg);
}
}
catch (JSONException e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(status.equals("OK"))
{
new GetRegister().execute();
//Toast.makeText(getApplicationContext(), msg1, Toast.LENGTH_LONG).show();
}
else
{
Toast.makeText(getApplicationContext(), "Enter Valid ZIP", Toast.LENGTH_LONG).show();
}
}
}
private class GetRegister extends AsyncTask<Void, Void, Void>
{
//String android_id = Secure.getString(getContentResolver(),Secure.ANDROID_ID);
String weburl="register url ";//if we ask question it will automatically register
String weburl1="&latitude=";
String weburl2="&longtitude=";
String weburl3="&type=Android&author=Jers&Submit=submit";
String code,msg;
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
ServiceHandler sh=new ServiceHandler();
String finalweburl=weburl+MainActivity.androidId+weburl1+latt+weburl2+lngg+weburl3;
System.out.println("new final web url----////"+finalweburl);
String str=sh.makeServiceCall(finalweburl,ServiceHandler.GET);
if(str!=null)
{
try
{
JSONObject obj=new JSONObject(str);
code=obj.getString("code");
msg=obj.getString("msg");
System.out.println("jewellery id-----"+MainActivity.androidId);
System.out.println("code-----"+code);
}
catch(JSONException e)
{
e.printStackTrace();
}
}
else
{
Log.e("ServiceHandler", "Couldn't get any data from the url");
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
if(code.equals("1"))
{
new GetQuestion().execute();
Toast.makeText(getApplicationContext(), "Registered", Toast.LENGTH_SHORT).show();
}
else
{
// Toast.makeText(getApplicationContext(),"NOT a question", Toast.LENGTH_LONG).show();
}
}
}
private class GetQuestion extends AsyncTask<Void, Void, Void>
{
EditText question1=(EditText)findViewById(R.id.question);
String success,msg1;
#Override
protected void onPreExecute()
{
super.onPreExecute();
}
#Override
protected Void doInBackground(Void... arg0)
{
String noofsupplier=noofsup.getText().toString();
ServiceHandler sh=new ServiceHandler();
String android_id = Secure.getString(getContentResolver(),Secure.ANDROID_ID);
String url="request url for distributor ";
String url1="&question=";
String url2="&no_of_suppliers=";
String finalurlq1=url+android_id+url1+ques+url2+noofsupplier;
String finalurlq=new String(finalurlq1.replaceAll(" ","%20"));
System.out.println(finalurlq);
System.out.println("question---->"+ques);
String str1=sh.makeServiceCall(finalurlq,ServiceHandler.GET);
if(str1!=null)
{
try
{
JSONObject ob=new JSONObject(str1);
JSONObject ob1=ob.getJSONObject("response");
success=ob1.getString("success");
msg1=ob1.getString("msg");
System.out.println("success---->"+success);
System.out.println("msg----->"+msg1);
}
catch(JSONException e)
{
e.printStackTrace();
}
}
else
{
}
return null;
}
#Override
protected void onPostExecute(Void result)
{
super.onPostExecute(result);
// Dismiss the progress dialog
// if (pDialog.isShowing())
// pDialog.dismiss();
/* * Updating parsed JSON data into ListView**/
if(success.equals("1"))
{
Toast.makeText(getApplicationContext(), "Question is Registered", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "Question not registered", Toast.LENGTH_SHORT).show();
}
}
}
}