My question is simple, I have made a bit of a mess in my TaskAdapter and now I am facing a problem with an onCreate method because I dont have it in my TaskAdapter (obviously).
Now if You could give Me some ideas on how to implement my alarmManager and link the ALARM_SERVICE so the code would work.
Heres my BaseAdapter:
'public class TaskAdapter extends BaseAdapter {
//transfer context
Context context;
//transfer user to use for shared preferences
String userName;
//create a list of tasks.....
List<taskItem> myTasks;
Calendar calendar = Calendar.getInstance();
AlarmManager alarmManager;
PendingIntent pendingIntent;
//constructor, for creating the adapter we need from the user context and userName
public TaskAdapter(Context context, String userName) {
this.context = context;
this.userName = userName;
//go to user shared preferences and fill the list
getData();
notifyDataSetChanged();
}
//how many item to display
#Override
public int getCount() {
//return the myTasks size....
return myTasks.size();
}
//return a specific item by index
#Override
public Object getItem(int i) {
return myTasks.get(i);
}
//return index number
#Override
public long getItemId(int i) {
return 0;
}
//create our view
#Override
public View getView(final int index, final View view, ViewGroup viewGroup) {
//inflate the view inside view object -> viewInflated
final View viewInflated = LayoutInflater.from(context).inflate(R.layout.task_item, null, false);
//set our inflated view behavior
//set pointer for our inflated view
//set pointer for task name....
final TextView txtTaskName = (TextView) viewInflated.findViewById(R.id.taskName);
//set pointer for taskInfo
final TextView txtTaskInfo = (TextView) viewInflated.findViewById(R.id.taskInfo);
//set pointer for task status....
final Switch swTask = (Switch) viewInflated.findViewById(taskDone);
//set task name, by the index of my myTasks collection
txtTaskName.setText(myTasks.get(index).taskName);
//set task info, by index of myTasks collection
txtTaskInfo.setText(myTasks.get(index).taskInfo);
//set task status , switch is getting true/false
swTask.setChecked(myTasks.get(index).taskStatus);
//show date and time dialog
final ImageView dtPicker = (ImageView) viewInflated.findViewById(R.id.imgTime);
dtPicker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final AlertDialog.Builder ad = new AlertDialog.Builder(context);
final AlertDialog aDialog = ad.create();
final LinearLayout adLayout = new LinearLayout(context);
adLayout.setOrientation(LinearLayout.VERTICAL);
TextView txtTime = new TextView(context);
txtTime.setText("Choose time");
adLayout.addView(txtTime);
final TimePicker tp = new TimePicker(context);
adLayout.addView(tp);
final DatePicker dp = new DatePicker(context);
tp.setVisibility(View.GONE);
adLayout.addView(dp);
final Button btnNext = new Button(context);
btnNext.setText("Next>");
adLayout.addView(btnNext);
btnNext.setGravity(1);
Button btnCancel = new Button(context);
btnCancel.setText("Cancel");
adLayout.addView(btnCancel);
btnCancel.setGravity(1);
btnCancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
aDialog.cancel();
}
});
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final int hour = tp.getHour();
final int min = tp.getMinute();
final String myHour = String.valueOf(hour);
final String myMin = String.valueOf(min);
calendar.set(Calendar.MONTH, dp.getMonth());
calendar.set(Calendar.YEAR, dp.getYear());
calendar.set(Calendar.DAY_OF_MONTH, dp.getDayOfMonth());
dp.setVisibility(View.GONE);
tp.setVisibility(View.VISIBLE);
btnNext.setText("Finish");
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
calendar.set(Calendar.HOUR_OF_DAY, tp.getHour());
calendar.set(Calendar.MINUTE, tp.getMinute());
Intent my_intent = new Intent(context, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pendingIntent);
if(hour > 12){
String myHour = String.valueOf(hour - 12);
}
if(min < 10)
{
String myMin = "0"+String.valueOf(min);
}
Toast.makeText(context, "Set for- "+myHour+":"+myMin , Toast.LENGTH_LONG).show();
aDialog.cancel();
}
});
}
});
aDialog.setView(adLayout);
aDialog.show();
}
});
//create listener event, when switch is pressed
swTask.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//we using utlShared to update task status
//create instance of utlShared
utlShared myShared = new utlShared(context);
//calling method of task, and giving userName(shared preferences, taskName, taskStatus)
myShared.task(userName, txtTaskName.getText().toString(), txtTaskInfo.getText().toString(), swTask.isChecked());
//we sending a message to the user, and inform him/her about the change
Toast.makeText(context, swTask.isChecked() ? "Task done" : "Task undone", Toast.LENGTH_SHORT).show();
}
});
//return the view with the behavior.....
return viewInflated;
}
private void getData() {
//go to specific shared preferences by user name.....
SharedPreferences taskPref = context.getSharedPreferences(userName, context.MODE_PRIVATE);
//create instance of our myTasks list
myTasks = new ArrayList<>();
//get all tasks from shared preferances
//the shared preferences is by key and value, therefor we will use Map collection
//we know that the key is String, but we don't know what type of value we will get. <K,?>
Map<String, ?> tasks = taskPref.getAll();
// transfer the data from map collection to list collection , single item is like the defination of the tasks <String,?>
//Entry -> record , enterSet -> set of records
for (Map.Entry<String, ?> oneTask : tasks.entrySet()) {
//insert task to list by Key and Value, we check if value is equal to 1, becuase 1=true 0=false
String[] str = oneTask.getValue().toString().split(",");
myTasks.add(new taskItem(str[0], str[1], str[2].equals("1")));
}
}
}'
I cant find a way to start
"alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE)" because I dont really know how to start it in an other way if there is a way.
Any help would be much appreciated!
Here is my AlarmReceiver:
public class AlarmReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Log.e("Didnt start alarm", "Too bad...");
Intent service_intent = new Intent(context, RingtonePlayingService.class);
context.startService(service_intent);
}
}
And here is the RingtoneService:
public class RingtonePlayingService extends Service {
MediaPlayer someMedia;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.i("Local Services", "Received start id "+ startId+": "+intent);
someMedia = MediaPlayer.create(this, R.raw.skyrim);
someMedia.start();
return START_NOT_STICKY;
}
#Override
public void onDestroy()
{
Toast.makeText(this, "On destroy called!", Toast.LENGTH_SHORT).show();
}
}
Cheers.
It looks like your alarmManager field isn't being initialized.
Add this line to your TaskAdapter constructor:
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
Also, you can directly call your service, no need for the BroadcastReceiver in the middle:
Intent my_intent = new Intent(context, RingtonePlayingService.class);
pendingIntent = PendingIntent.getService(context, 0, my_intent, PendingIntent.FLAG_UPDATE_CURRENT);
UPDATE
A service should be declared with the service tag in the manifest.
See: https://developer.android.com/guide/topics/manifest/service-element.html
<service android:name=".RingtonePlayingService" android:enabled="true"/>
Related
I want notification on Button Click event in fragment.
I tried a a lot it is not giving me any error but its not showing me notification.
main.java
public class OneTimeTask extends Fragment implements View.OnClickListener {
public OneTimeTask() {
}
;
String addtask, adddetail, adddate;
static final int TIME_DIALOG_ID = 999;
View view;
EditText taskname, taskdetail, taskdate;
Button taskadd;
ProgressDialog mProgressDialog;
SessionManager session;
JSONObject jsonobject;
private DatePickerDialog fromDatePickerDialog;
private DatePickerDialog toDatePickerDialog;
private SimpleDateFormat dateFormatter;
String uid;
Intent intent;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.activity_daily__task, container, false);
getActivity().setTitle("Task");
taskname = (EditText) view.findViewById(R.id.taskname);
taskdetail = (EditText) view.findViewById(R.id.taskdetail);
taskdate = (EditText) view.findViewById(R.id.taskdate);
taskadd = (Button) view.findViewById(R.id.taskaddtask);
GetCurrentGPSLocation gps = new GetCurrentGPSLocation(getActivity());
if (gps.canGetLocation()) {
// \n is for new line
}else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
dateFormatter = new SimpleDateFormat("dd-MM-yyyy", Locale.ENGLISH);
session = new SessionManager(getActivity());
HashMap<String, String> user = session.getUserDetails();
uid = user.get(SessionManager.KEY_ID);
setDateTimeField();
return view;
}
private void setDateTimeField() {
taskadd.setOnClickListener(this);
Calendar newCalendar = Calendar.getInstance();
fromDatePickerDialog = new DatePickerDialog(getContext(), new DatePickerDialog.OnDateSetListener() {
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
Calendar newDate = Calendar.getInstance();
newDate.set(year, monthOfYear, dayOfMonth);
taskadd.setText(dateFormatter.format(newDate.getTime()));
}
},newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));
}
// #Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getActivity().getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void onClick(View view) {
if(view == taskadd) {
fromDatePickerDialog.show();
}
taskadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addtask=taskname.getText().toString();
adddetail=taskdetail.getText().toString();
adddate= taskdate.getText().toString();
InsertData();
Notification();
}
});
}
public void Notification() {
// Set Notification Title
String strtitle = getString(R.string.notificationtitle);
// Set Notification Text
String strtext = getString(R.string.notificationtext);
// Open NotificationView Class on Notification Click
/*
FragmentTransaction t = getActivity().getSupportFragmentManager().beginTransaction();
TabFragment mFrag = new TabFragment();
t.replace(com.Weal.sachin.omcom.R.id.framelayout, mFrag);
t.commit();
*/
Intent intent = new Intent(getActivity(), NotificationView.class);
// Send data to NotificationView Class
intent.putExtra("title", strtitle);
intent.putExtra("text", strtext);
// Open NotificationView.java Activity
PendingIntent pIntent = PendingIntent.getActivity(getContext(), 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
//Create Notification using NotificationCompat.Builder
NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext())
// Set Icon
.setSmallIcon(R.drawable.icon)
// Set Ticker Message
.setTicker(getString(R.string.notificationticker))
// Set Title
.setContentTitle(getString(R.string.notificationtitle))
// Set Text
.setContentText(getString(R.string.notificationtext))
// Add an Action Button below Notification
.addAction(R.drawable.ic_audiotrack, "Action Button", pIntent)
// Set PendingIntent into Notification
.setContentIntent(pIntent)
// Dismiss Notification
.setAutoCancel(true);
// Create Notification Manager
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getContext().getSystemService(NOTIFICATION_SERVICE);
// Build Notification with Notification Manager
notificationmanager.notify(0, builder.build());
}
Here my noficationview.class
package com.Weal.sachin.omcom;
/**
* Created by sachin on 1/23/2017.
*/
import android.app.Activity;
import android.app.NotificationManager;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TextView;
public class NotificationView extends Activity {
String title;
String text;
TextView txttitle;
TextView txttext;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.notificationview);
// Create Notification Manager
NotificationManager notificationmanager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
// Dismiss Notification
notificationmanager.cancel(0);
// Retrive the data from MainActivity.java
Intent i = getIntent();
title = i.getStringExtra("title");
text = i.getStringExtra("text");
// Locate the TextView
txttitle = (TextView) findViewById(R.id.title);
txttext = (TextView) findViewById(R.id.text);
// Set the data into TextView
txttitle.setText(title);
txttext.setText(text);
}
}
I tried this way and this code is not displaying the notification on Button Click...
May be that's because you are trying to add
taskadd.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
addtask=taskname.getText().toString();
adddetail=taskdetail.getText().toString();
adddate= taskdate.getText().toString();
InsertData();
Notification();
}
});
inside onClick() of your fragment. Since you are already inside onClick() you will not be requiring taskadd.setOnClickListener().
Instead replace your onClick() method with this.
if(view == taskadd) {
fromDatePickerDialog.show();
}
addtask=taskname.getText().toString();
adddetail=taskdetail.getText().toString();
adddate= taskdate.getText().toString();
InsertData();
Notification();
try this code to generate small and big notifications
full source code source
#Override
public void onClick(View v) {
Intent intent = new Intent(getApplicationContext(), PushNotificationDemo.class);
final PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, intent, 0);
NotificationManager notificationManager = (NotificationManager)
getSystemService(NOTIFICATION_SERVICE);
Notification n;
switch (v.getId()) {
case R.id.nd_smallnotification:
if (heading.getText().length() <= 0) {
heading.setError("Please provide push notification title");
} else {
heading.setError(null);
heading_text = heading.getText().toString();
n = new NotificationCompat.Builder(this)
.setContentTitle(heading_text)
.setContentText(message.getText().toString())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pending)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.addAction(android.R.drawable.ic_menu_manage, "Close", pending)
.build();
n.flags |= Notification.FLAG_AUTO_CANCEL | Intent.FLAG_ACTIVITY_SINGLE_TOP;
notificationManager.notify(0, n);
}
break;
case R.id.nd_bignotification:
if (heading.getText().length() <= 0) {
heading.setError("Please provide push notification title");
} else {
heading.setError(null);
heading_text = heading.getText().toString();
NotificationCompat.InboxStyle nc =
new NotificationCompat.InboxStyle();
nc.setBigContentTitle(heading_text);
String[] text = new String[5];
for (int i = 0; i < 5; i++) {
text[i] = i + ". say hello...";
nc.addLine(text[i]);
}
n = new NotificationCompat.Builder(this)
.setStyle(nc)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentIntent(pending)
.setDefaults(Notification.DEFAULT_SOUND)
.setAutoCancel(true)
.setWhen(System.currentTimeMillis())
.build();
n.flags |= Notification.FLAG_AUTO_CANCEL | Intent.FLAG_ACTIVITY_SINGLE_TOP;
notificationManager.notify(100, n);
}
break;
}
}
Init. your onClick inside onCreate():
taskname = (EditText) view.findViewById(R.id.taskname);
taskdetail = (EditText) view.findViewById(R.id.taskdetail);
taskdate = (EditText) view.findViewById(R.id.taskdate);
taskadd = (Button) view.findViewById(R.id.taskaddtask);
taskadd.setOnClickListener(getActivity); //<----here
Use properly onClick, don't init. the view twice:
public void onClick(View view) {
if(view == taskadd) {
fromDatePickerDialog.show(); //use this properly
addtask=taskname.getText().toString();
adddetail=taskdetail.getText().toString();
adddate= taskdate.getText().toString();
InsertData();
Notification();
}
}
Also to get the context of fragment. Remove getContext() from Notification:
Remove this:
getContext();
With this:
getActivity();
I am currently creating an android app that scans a network and outputs results in a ListView but I am trying to make it to where I tap on the network and it saves the data in a database then sends you to a page to show you what you selected but when I click an item it substrings the values correctly and displays work fine on the main activity but when I try to use the variables on my display page activity there values are set null.
Here is the main activity in the click listener:
networklist.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
String grabItemInfo = wifis[position];
Network_Info info1 = new Network_Info();
info1.setMainBSSID( grabItemInfo.substring(grabItemInfo.indexOf('#') +1, grabItemInfo.lastIndexOf('#')));
info1.setMainSSID( grabItemInfo.substring(0,(grabItemInfo.indexOf('#'))));
info1.setMainCAP( grabItemInfo.substring(grabItemInfo.lastIndexOf('#')+1, grabItemInfo.length()));
Toast toastTest = Toast.makeText(getApplicationContext(), info1.getMainSSID(), Toast.LENGTH_SHORT);
Toast toastTest2 = Toast.makeText(getApplicationContext(), info1.getMainBSSID(), Toast.LENGTH_SHORT);
Toast toastTest3 = Toast.makeText(getApplicationContext(), info1.getMainCAP(), Toast.LENGTH_SHORT);
toastTest.show();
toastTest2.show();
toastTest3.show();
ContentValues dbv = new ContentValues();
dbv.put("SSID", info1.getMainSSID());
dbv.put("BSSID", info1.getMainBSSID());
dbv.put("CAPABILITIES", info1.getMainCAP());
netDataBase.insert("netDataTable", "NULL", dbv);
Intent intent = new Intent(getApplicationContext(), Attack_Page.class);
startActivity(intent);
}
});
Here is my display page:
public class Attack_Page extends Network_List {
protected void onCreate(Bundle SavedIS){
super.onCreate(SavedIS);
setContentView(R.layout.attack_page);
TextView SSIDview = (TextView) findViewById(R.id.SSIDView);
TextView BSSIDview = (TextView) findViewById(R.id.BSSIDView);
TextView CAPview = (TextView) findViewById(R.id.CAPView);
Button backButton = (Button) findViewById(R.id.backbutton);
Intent intent = getIntent();
//String MainSSIDP = intent.getStringExtra(getMainSSID());
Network_Info info1 = new Network_Info();
Toast testToast = Toast.makeText(getApplicationContext(), info1.getMainSSID(), Toast.LENGTH_SHORT);
testToast.show();
//Cursor IDselect = netDataBase.rawQuery("SELECT SSID FROM netDataTable WHERE SSID = "+getMainSSID()+"", wifis);
//SSIDview.setText(IDselect.toString());
backButton.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
Intent bintent = new Intent(getApplicationContext(), Network_List.class);
startActivity(bintent);
}
});
}
}
Here is my setters and getters class:
public class Network_Info {
private String mainCAP;
private String mainSSID;
private String mainBSSID;
public void setMainSSID(String newMainSSID){
mainSSID = newMainSSID;
}
public void setMainBSSID(String newMainBSSID){
mainBSSID = newMainBSSID;
}
public void setMainCAP(String newMainCAP){
mainCAP = newMainCAP;
}
public String getMainSSID(){
return mainSSID;
}
public String getMainBSSID(){
return mainBSSID;
}
public String getMainCAP(){
return mainCAP;
}
}
Figured out you have to pass the variable with the intent:
Intent intent = new Intent(getApplicationContext(), Attack_Page.class);
intent.putExtra("EXTRA_SSID", info1.getMainSSID());
intent.putExtra("EXTRA_BSSID", info1.getMainBSSID());
intent.putExtra("EXTRA_CAP", info1.getMainCAP());
startActivity(intent);
Then use the key that you set in putExtra()
String MainSSIDP = intent.getStringExtra("EXTRA_SSID");
Thanks for the help though!
I have a news article app that has a gridview of all articles then you can select the full article. I want the user to receive a notification when a new news article has been posted. It just has to be really simple, the app logo and some text 'new article posted!' and then when they click on the notification the app is opened. Here is my code below, i'm not sure what you need to see though so let me know if you need anything else.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private List<NewsRecord> newsListData = new ArrayList<NewsRecord>();
private GridView newsListView;
private NewsListAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView newsListView = (GridView) findViewById(R.id.newsFeedList);
adapter = new NewsListAdapter(this, R.layout.adapter_news_list, newsListData, this);
newsListView.setAdapter(adapter);
newsListView.setOnItemClickListener(itemClicked);
nextStart = 0;
updateListData(nextStart, 20);
}
public int nextStart = 0;
public void updateListData(int StartPoint, int count){
String url = "http://www.efstratiou.info/projects/newsfeed/getList.php?start=" + StartPoint + "&count=" + count;
EDANewsApp app = EDANewsApp.getInstance();
JsonArrayRequest jsonRequest = new JsonArrayRequest(url, listener, errorListener);
app.requestQueue.add(jsonRequest);
nextStart +=count;
}
#Override
public boolean onCreateOptionsMenu (Menu menu){
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_menu, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item){
switch (item.getItemId()) {
case R.id.action_about:
Intent intent = new Intent(this, AboutActivity.class);
startActivity(intent);
return true;
case R.id.action_search:
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
AdapterView.OnItemClickListener itemClicked = new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent intent = new Intent(MainActivity.this, NewsItemActivity.class);
intent.putExtra("newsItemId", newsListData.get(position).recordId);
startActivity(intent);
}
};
//Listeners
Response.Listener<JSONArray> listener = new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
//we successfully received the JSONArray
//Here we will extract the data and use it in our app
//Clear the dataset before loading new data
// newsListData.clear();
//Go through all the JSON objects
for (int i = 0; i < response.length(); i++) {
try {
//Get one JSON object
JSONObject jsonObj = response.getJSONObject(i);
//Put JSON data in a Java object
NewsRecord record = new NewsRecord();
record.recordId = jsonObj.getInt("record_id");
record.title = jsonObj.getString("title");
record.date = jsonObj.getString("date");
record.shortInfo = jsonObj.getString("short_info");
record.imageUrl = jsonObj.getString("image_url");
newsListData.add(record);
} catch (JSONException e) {
e.printStackTrace();
}
}
adapter.notifyDataSetChanged();
}
};
Response.ErrorListener errorListener = new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
//There was an error in the communication
//We can notify the user about it
}
};
}
I am not 100% sure about when new article is posted.
If I am right, after adapter.notifyDataSetChanged() notify user with notificatoins by below code:
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Replace ResultActivity.class to your result notification class.
Intent resultIntent = new Intent(this, ResultActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(ResultActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// first element (0) allows you to update the notification later on.
mNotificationManager.notify(0, mBuilder.build());
Here the group chat activity is running currently. Group chat activity means chat window. in that chat window i retrieved the message from sqlite and showed by list view adpater. Here i am doing group chat for one event when new message is arrived for other event the notification issued. When i click the notification my group chat activity is not executed again even if i passed the intent from other class or activity.
This is my groupchatActivity code
#Override
protected void onStart() {
super.onStart();
if (activeEventMO != null) {
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 1);
editor.putLong("eventId", activeEventMO.getEventId());
editor.commit();
Log.i("App", "start");
AppActivityStatus.setActivityStarted();
AppActivityStatus.setActivityContext(context);
}
}
#Override
protected void onPause() {
super.onPause();
AppActivityStatus.setActivityStoped();
}
protected void onNewIntent(Intent intent){
super.onNewIntent(intent);
processExtraData();
}
private void processExtraData() {
activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
}
#Override
protected void onResume() {
super.onPause();
AppActivityStatus.setActivityStarted();
}
#Override
protected void onStop() {
super.onStop();
Log.i("App", "stop");
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putInt("APPSTATUS", 2);
editor.commit();
AppActivityStatus.setActivityStoped();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.image_upload, menu);
return true;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final List<ChatMO> chatMOs1 = new ArrayList<>();
setContentView(R.layout.chat_main);
EventMO eventMO = new EventMO();
context = getApplicationContext();
DatabaseHelper dbHelper = new DatabaseHelper(context);
listChatMessageObjectses = chatMOs1;
inputMsg = (EditText) findViewById(R.id.inputMsg);
listViewMessages = (ListView) findViewById(R.id.list_view_messages);
//this activeEventMO is a static object
processExtraData();
// activeEventMO = (EventMO) getIntent().getParcelableExtra("eventMo");
List<ChatMO> chatMOs = dbHelper.getGroupChatMessageForEvent(activeEventMO.getEventId());
//this for loop is for avoiding the notification coz notification also stores groupchat table in sqlite
for (ChatMO chatMO1 : chatMOs) {
chatMO1.getMessage();
chatMO1.getEvent_id();
chatMO1.getFromName();
int messageType = chatMO1.getMessage_type();
chatMO1.getDate();
chatMO1.isSelf();
if (messageType == 0) {
chatMOs1.add(chatMO1);
}
}
adapter = new MessagesListAdapter(context, chatMOs1);
//adapter functionality added for show the previous chat list of event/invite
listViewMessages.setAdapter(adapter);
sharedpreferences = getSharedPreferences(Constants.SHARED_PREFERENCE_NAME, context.MODE_PRIVATE);
// by default first primary user is current user in sql lite
// user table
userMO = dbHelper.getUserData(1);
/* if (!sharedpreferences.getString("MessageMO", "null").equals("null")) {
MessageMO messageMO1 = (MessageMO) gson.fromJson(sharedpreferences.getString("MessageMO", "null"), new TypeToken<MessageMO>() {
}.getType());
eventMO.setEventId(messageMO1.getEventId());
Log.e("shared","eventID"+messageMO1.getEventId());
Log.e("shared","eventID"+eventMO.getEventId());
eventMO.setText(messageMO1.getEventTitle());
Log.i("message values", messageMO1.toString());
ChatMO chatMO = new ChatMO();
//chatMessageObjects.setMessage(messageMO1.getMessage());
chatMO.setSelf(0);
chatMO.setFromName(messageMO1.getfromUserName());
listChatMessageObjectses.add(chatMO);
//listViewMessages.setAdapter(adapter);
adapter.notifyDataSetChanged();
}*/
new AsyncTask<Void, Void, String>() {
#Override
protected String doInBackground(Void... arg0) {
return userDelegate.getUsersForEvent(activeEventMO.getEventId());
}
#Override
protected void onPostExecute(String eventLists) {
eventUserMOs = gson.fromJson(eventLists, new TypeToken<ArrayList<UserMO>>() {
}.getType());
Toast.makeText(getApplicationContext(), "event users " + eventUserMOs.size(), Toast.LENGTH_LONG).show();
}
}.execute(null, null, null);
Button sendButton = (Button) findViewById(R.id.btnSend);
This gcmIntent here i am passing the intent from this gcmIntent
Intent groupChatActFrag = new Intent(getApplicationContext(), GroupChatActivity.class);
EventMO eventMO = new EventMO();
//here messageMO having the details of received message here i am setting eventId from messageMO to eventMO
// Inorder to passs gropchatActivity
eventMO.setEventId(messageMO.getEventId());
groupChatActFrag.putExtra("eventMo", eventMO);
groupChatActFrag.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString("MessageMO", gson.toJson(messageMO));
editor.commit();
PendingIntent contentIntent = PendingIntent.getActivity(this, 0, groupChatActFrag, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_dialog_info).setContentTitle(messageMO.getEventTitle())
.setStyle(new NotificationCompat.BigTextStyle().bigText(messageMO.getfromUserName())).setContentText(messageMO.getMessage()).setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
mBuilder.setContentIntent(contentIntent);
mBuilder.setAutoCancel(true);
mNotificationManager.notify((int) (long) messageMO.getEventId(), mBuilder.build());
You need to do couple of things to achieve the result.
Set launch mode of groupchatactivity to SingleTask
Override onNewIntent() method in groupchatactivity
Call setIntent(intent) for new received intent in onNewIntent()
Reflect as appropriate on above answer.
I'm working on a group project for a class I'm taking and we cannot seem to figure out why our Alarm Manager does not fire intents repeatedly. We've picked through the source code from top to bottom and cannot seem to isolate the source of this issue.
Can anyone recommend a fix? (or perhaps a starting point?)
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Rules.this, LMW.class);
PendingIntent pintent = PendingIntent.getService(Rules.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
7 * 1000, pintent);
// Start 2nd service using AlarmManager
Intent intent2 = new Intent(Rules.this, KillTimer.class);
PendingIntent pintent2 = PendingIntent.getActivity(Rules.this, 0, intent2,
0);
AlarmManager alarm2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
120 * 1000, pintent2); // here
Source:
public class AlarmManager extends ListActivity {
TextView empty;
TextView empty2;
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVITY_EDIT = 1;
public static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private List<ParseObject> todos;
private Dialog progressDialog;
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
// Override this method to do custom remote calls
public void setVisibility() {
empty.setVisibility(View.VISIBLE);
empty2.setVisibility(View.VISIBLE);
}
protected void doInBackground(Void... params) {
// Gets the current list of todos in sorted order
ParseQuery query = new ParseQuery("TestObject");
query.orderByDescending("_created_at");
try {
todos = query.find();
} catch (ParseException e) {
return;
}
runOnUiThread(new Runnable() {
public void run() {
}});
}
#Override
protected void onPreExecute() {
ToDoListActivity.this.progressDialog = ProgressDialog.show(ToDoListActivity.this, "",
"Loading...", true);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// Put the list of todos into the list view
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ToDoListActivity.this,
R.layout.todo_row);
for (ParseObject todo : todos) {
adapter.add((String) todo.get("DataI"));
adapter.add((String) todo.get("DataO"));
adapter.add((String) todo.get("DataRSSI"));
adapter.add((String) todo.get("DataSSID"));
adapter.add((String) todo.get("DataTIME"));
adapter.add((String) todo.get("DataRESTRICTED"));
}
setListAdapter(adapter);
ToDoListActivity.this.progressDialog.dismiss();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_new);
empty = (TextView) findViewById(android.R.id.empty);
empty.setVisibility(View.INVISIBLE);
new RemoteDataTask().execute();
registerForContextMenu(getListView());
}
private void createTodo() {
Intent i = new Intent(this, CreateTodo.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (intent == null) {
return;
}
final Bundle extras = intent.getExtras();
switch (requestCode) {
case ACTIVITY_CREATE:
new RemoteDataTask() {
protected void doInBackground(Void... params) {
String DataI = extras.getString("DataI");
String DataO = extras.getString("DataO");
String DataRSSI = extras.getString("DataRSSI");
String DataSSID = extras.getString("DataSSID");
String DataTIME = extras.getString("DataTIME");
String DataRESTRICTED = extras.getString("DataRESTRICTED");
ParseObject todo = new ParseObject("Todo");
todo.put("DataI", DataI);
todo.put("DataO", DataO);
todo.put("DataRSSI", DataRSSI);
todo.put("DataSSID", DataSSID);
todo.put("DataTIME", DataTIME);
todo.put("DataRESTRICTED", DataRESTRICTED);
try { todo.save(); } catch (ParseException e) {
}
super.doInBackground();
return;
}
}.execute();
break;
case ACTIVITY_EDIT:
// Edit the remote object
final ParseObject todo;
todo = todos.get(extras.getInt("position"));
todo.put("DataI", extras.getString("DataI"));
todo.put("DataO", extras.getString("DataO"));
todo.put("DataRSSI", extras.getString("DataRSSI"));
todo.put("DataSSID", extras.getString("DataSSID"));
todo.put("DataTIME", extras.getString("DataTIME"));
todo.put("DataRESTRICTED", extras.getString("DataRESTRICTED"));
new RemoteDataTask() {
protected void doInBackground(Void... params) {
try {
todo.save();
} catch (ParseException e) {
}
super.doInBackground();
return;
}
}.execute();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
return result;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
// Delete the remote object
final ParseObject todo = todos.get(info.position);
new RemoteDataTask() {
protected void doInBackground(Void... params) {
try {
todo.delete();
} catch (ParseException e) {
}
super.doInBackground();
return;
}
}.execute();
return true;
}
return super.onContextItemSelected(item);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case INSERT_ID:
createTodo();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, CreateTodo.class);
i.putExtra("DataI", todos.get(position).getString("DataI").toString());
i.putExtra("DataO", todos.get(position).getString("DataO").toString());
i.putExtra("DataRSSI", todos.get(position).getString("DataRSSI").toString());
i.putExtra("DataSSID", todos.get(position).getString("DataSSID").toString());
i.putExtra("DataTIME", todos.get(position).getString("DataTIME").toString());
i.putExtra("DataRESTRICTED", todos.get(position).getString("DataRESTRICTED").toString());
i.putExtra("position", position);
startActivityForResult(i, ACTIVITY_EDIT);
}
}
Service Class
public class LMW extends Service {
String Watchdog = "Watchdog";
String Dirty1 = "playboy";
String Dirty2 = "penthouse";
String Dirty3 = "pornhub";
String Dirty4 = "thepiratebay";
String Dirty5 = "vimeo";
String Dirty6 = "wired";
String Dirty7 = "limewire";
String Dirty8 = "whitehouse";
String Dirty9 = "hackaday";
String Dirty10 = "slashdot";
Long mStartRX = TrafficStats.getTotalRxBytes();
Long mStartTX = TrafficStats.getTotalTxBytes();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Watchdog Running!", Toast.LENGTH_SHORT).show();
Long.toString(mStartTX);
Long.toString(mStartRX);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataO", String.valueOf(mStartTX));
testObject.put("DataI", String.valueOf(mStartRX));
testObject.saveInBackground(); String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = getContentResolver().query(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
Log.i(Watchdog, url);
if (url.toLowerCase().contains(Dirty1) || url.toLowerCase().contains(Dirty2) || url.toLowerCase().contains(Dirty3) || url.toLowerCase().contains(Dirty4) || url.toLowerCase().contains(Dirty5) || url.toLowerCase().contains(Dirty6) || url.toLowerCase().contains(Dirty7) || url.toLowerCase().contains(Dirty8) || url.toLowerCase().contains(Dirty9) || url.toLowerCase().contains(Dirty10))
{
Intent intent2 = new Intent(LMW.this, Warning.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent2);
break;
} } while (cursor.moveToNext());
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}}
Activity Class:
public class Timer extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.killtimer);
Toast.makeText(getApplicationContext(), "KillWifi Running!", Toast.LENGTH_SHORT).show();
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
int networkId = wifiManager.getConnectionInfo().getNetworkId();
wifiManager.removeNetwork(networkId );
wifiManager.saveConfiguration();
}}
Go through the links, It helped me a lot.
http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html
http://android-er.blogspot.in/2010/10/schedule-repeating-alarm.html
I have had a similar problem and perhaps it applies to you (hard to tell since the code you supplied is pretty hard to navigate).
My issue was that applying multiple intents to the manager that evaluated as equal overrode the previous applications of that intent. See http://developer.android.com/reference/android/content/Intent.html#filterEquals(android.content.Intent) for what I mean by equivalence.
As an example, I had a schedule that used the URI domy://thing, with extras that varied over each intent (I need to fire the same action with different arguments each time). Extras don't count in equivalence, so my alarms were getting overwritten by each other.
To get around this, I stored a queue of my alarms in a separate file and when one fired, popped the next off the top and put that in the manager. Maybe that'll help you.
UPDATE:
No examples publicly visible, but try this (Trigger is a simple object containing a URI and a time it needs to be fired, scheduleDb is a class that extends SQLiteOpenHelper):
/**
* Pops the next trigger off the queue, adds it to the alarm manager, and
* stores it in the DB in case we need to cancel it later.
*/
private void scheduleNextTrigger() {
Log.d(TAG, "Popping next trigger off queue");
Optional<Trigger> nextTrigger = scheduleDb.getNextTrigger();
if (!nextTrigger.isPresent()) {
Log.d(TAG, "Trigger queue is empty");
return;
}
Trigger trigger = nextTrigger.get();
Log.d(TAG, "Scheduling new trigger " + trigger);
PendingIntent operation = createPendingIntent(trigger);
long timestamp = trigger.getTimestamp();
// Ensure the next item is in the future
if (timestamp > clock.currentTimeMillis()) {
Log.v(TAG, "Found valid trigger: " + trigger);
alarmManager.set(AlarmManager.RTC_WAKEUP, timestamp, operation);
}
scheduleDb.setScheduledTrigger(trigger);
}
private PendingIntent createPendingIntent(Trigger trigger) {
// AlarmManager allows only one instance of each URI, and seems to randomly
// delete bundled URI extras, so we'll encode the triggered URI and place it
// on a constant stem
Uri triggerUri = Uri.parse(TRIGGER_URI + "?" + Uri.encode(trigger.getUri()));
Intent triggerIntent = new Intent(Intent.ACTION_VIEW, triggerUri);
triggerIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Log.d(TAG, "Created trigger intent " + triggerIntent);
PendingIntent operation = PendingIntent.getService(this, 0, triggerIntent, 0);
return operation;
}
Hope that helps