Can't get onActivityResult to work.. - Java for Android App Development

Hi everybody. ^^
I'm in the process of making an app using Game Maker Studio, and I'm trying to code an Android extension for it in Java.
Basically what I want the extension to do is start a Gallery Image picker activity, where a user can select a picture from their phone, then the selected image would be inserted into the game.
I have it so that my extension can bring up the image picker activity, but that's as far as it gets before it clonks out. ><
Upon further testing, I was able to determine that where it gets stuck is right after the startActivityForResult command. The onActivityResult method is never initiated, so the extension isn't doing anything else from there. If someone could give me an idea why this isn't working, that would be awesome. Thanks! ^^
Here is the code for my extension. Also note that the (RunnerActivity.CurrentActivity) is basically referring to the activity where the game is displayed.
Code:
package ${YYAndroidPackageName};
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import ${YYAndroidPackageName}.R;
import ${YYAndroidPackageName}.RunnerActivity;
import com.yoyogames.runner.RunnerJNILib;
public class GalleryChooser extends Activity
{
String imagePath = "";
Intent i;
private static final int RESULT_LOAD_IMAGE=1;
public void ImageSelector() {
i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
(RunnerActivity.CurrentActivity).startActivityForResult(i, RESULT_LOAD_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if (requestCode == RESULT_LOAD_IMAGE && resultCode == (RunnerActivity.CurrentActivity).RESULT_OK && null != data) {
if (requestCode == RESULT_LOAD_IMAGE && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = (RunnerActivity.CurrentActivity).getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(columnIndex);
cursor.close();
}
else {imagePath = "Blank location returned :(";}
}
public String getImagePath() {
return imagePath;}
}

Lodmot said:
Hi everybody. ^^
I'm in the process of making an app using Game Maker Studio, and I'm trying to code an Android extension for it in Java.
Basically what I want the extension to do is start a Gallery Image picker activity, where a user can select a picture from their phone, then the selected image would be inserted into the game.
I have it so that my extension can bring up the image picker activity, but that's as far as it gets before it clonks out. ><
Upon further testing, I was able to determine that where it gets stuck is right after the startActivityForResult command. The onActivityResult method is never initiated, so the extension isn't doing anything else from there. If someone could give me an idea why this isn't working, that would be awesome. Thanks! ^^
Here is the code for my extension. Also note that the (RunnerActivity.CurrentActivity) is basically referring to the activity where the game is displayed.
Code:
package ${YYAndroidPackageName};
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import ${YYAndroidPackageName}.R;
import ${YYAndroidPackageName}.RunnerActivity;
import com.yoyogames.runner.RunnerJNILib;
public class GalleryChooser extends Activity
{
String imagePath = "";
Intent i;
private static final int RESULT_LOAD_IMAGE=1;
public void ImageSelector() {
i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
(RunnerActivity.CurrentActivity).startActivityForResult(i, RESULT_LOAD_IMAGE);
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// if (requestCode == RESULT_LOAD_IMAGE && resultCode == (RunnerActivity.CurrentActivity).RESULT_OK && null != data) {
if (requestCode == RESULT_LOAD_IMAGE && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = (RunnerActivity.CurrentActivity).getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(columnIndex);
cursor.close();
}
else {imagePath = "Blank location returned :(";}
}
public String getImagePath() {
return imagePath;}
}
Click to expand...
Click to collapse
In your onActivityResult(), in the line which you commented out to be replaced by the fewer conditions you should be checking the requestCode instead of the resultCode! Read the doc about activity results again, you pass the requestCode to startActivityForResult() and the resultCode is usually either RESULT_OK or RESULT_CANCELED! Best to check both codes like they do in the example I linked to above.

SimplicityApks said:
In your onActivityResult().........
Click to expand...
Click to collapse
Well the reason why that line is commented out is because I actually tried doing it like this:
Code:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
... but doing that gave me an error when I compiled it. It said "can't find symbol RESULT_OK" or something similar.
EDIT: NOW apparently it's compiling fine with the above! It must've had to do with the SDK Manager getting a new API level or something... However it's still not working the way I want it to...
The only way I was able to get that line to compile without errors was by doing it this way:
Code:
if (requestCode == RESULT_LOAD_IMAGE && resultCode == (RunnerActivity.CurrentActivity).RESULT_OK && null != data) {
However I have a feeling the RESULT_OK variable doesn't work that way, because it's not allowing that method to initiate when it's like that..
EDIT: I took the time to read a bit deeper into it, and it LOOKS like I might want to use setResult(). I'll try it when I get back to my computer.
EDIT 2: Nope, no workie. :/
EDIT 3: I'm able to compile the code exactly the way as it's described in the example you directed me to, but it's not performing the onActivityResult method still.. I tried using setResult(), that didn't work... A clever trick I'm trying is having a string variable set to different messages after each individual command is ran. Then I'm drawing that string variable in the game itself. Wherever the string variable stops changing will identify where the code error is, and it's definitely stopping right before the onActivityResult method begins. However, that could also happen if the game gets paused when it opens up Gallery (but even so, it should update once the game activity regains focus I would think)... Man... what a mystery! >.<
Just to keep my progress up to date, this is how my code looks now, and it compiles correctly:
Code:
package ${YYAndroidPackageName};
import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import ${YYAndroidPackageName}.R;
import ${YYAndroidPackageName}.RunnerActivity;
import com.yoyogames.runner.RunnerJNILib;
public class GalleryChooser extends Activity
{
String imagePath = "";
Intent i;
private static final int RESULT_LOAD_IMAGE=1;
public void ImageSelector() {
i = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
imagePath="activity started!";
(RunnerActivity.CurrentActivity).startActivityForResult(i, RESULT_LOAD_IMAGE);
imagePath="Activity Started 2!!! (we're still running in the background)";
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
imagePath="hello world...?";
//super.onActivityResult(requestCode, resultCode, data);
imagePath="checking request code...";
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && null != data) {
imagePath="RESULT_LOAD_IMAGE verified!";
Uri selectedImage = data.getData();
imagePath="Grabbing data...";
String[] filePathColumn = { MediaStore.Images.Media.DATA };
imagePath="Converting String....";
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
imagePath="Got Content Resolver!";
cursor.moveToFirst();
imagePath="Moved to First...";
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
imagePath = cursor.getString(columnIndex);
cursor.close();
}
else {imagePath = "Blank location returned :(";}
}
public String getImagePath() {
return imagePath;}
}

Related

[Q] Please help with tutorial code!

Good evening everyone! I am working on learning some java and I have made it to the notepad tutorial and when I go to run it on the emulator, I am getting a few errors, and I'm hoping someone here may be able to help.
Code:
package com.a8a.todolist;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.ArrayAdapter;
import android.view.View.OnClickListener;
public class ToDoList extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
//Inflat your view
setContentView(R.layout.main);
//Get references to UI widgets
ListView myListView = (ListView)findViewById(R.id.myListView);
final EditText myEditText = (EditText)findViewById(R.id.myEditText);
//Create the array list of to do items
final ArrayList<String> todoItems = new ArrayList<String>();
//Create the array adapter to bind the array to the listview
final ArrayAdapter<String> aa;
[B]aa = new ArayAdapter<String>(this, android.R.layout.simple_list_item_1,todoItems);[/B] [I]Multiple markers at this line - ArayAdapter cannot be resolved to a type - Line breakpoint:ToDoList [line: 27] - onCreate[/I]
(Bundle)
//Bind the arary adapter to the listview.
myListView.setAdapter(aa);
[B]myEditText.setOnKeyListener(new OnKeyListener() {[/B] [I]OnKeyListener cannot be resolved to a type[/I]
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getAction() == KeyEvent.ACTION_DOWN)
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER)
{
todoItems.add(0, myEditText.getText().toString());
aa.notifyDataSetChanged();
myEditText.setText("");
return true;
}
return false;
}
});
}
}
The bolded text is whats getting the error and the italics are the error itself. Any help would be appreciated, if you are able to explain why the change needs to be made as well that would be much appreciated, so I can learn from my mistakes.
Thanks in advance!
ArayAdapter was miss-spelled ArrayAdapter
I was also missing an import for OnKeyListener (import android.view.View.OnKeyListener). If you don't import a class and try to use it, Java doesn't know what it is, so it tells you it doesn't recognize the type.

ProgressDialog don't appear

Hy please help me!!
My full code:
Code:
package com.android.skiptvad;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.graphics.LightingColorFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.android.skiptvad.*;
public class Login extends Activity {
private static final int DIALOG_LOADING = 0;
/** Called when the activity is first created. */
TextView tvuser;
String sessionid;
ProgressDialog pd = null;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
tvuser = (TextView) findViewById(R.id.tvuser);
TextView tvpw = (TextView) findViewById(R.id.tvpw);
final EditText etuser = (EditText) findViewById(R.id.etuser);
final EditText etpw = (EditText) findViewById(R.id.etpw);
Button btlogin = (Button)findViewById(R.id.btlogin);
btlogin.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if (etuser.getText() != null && etpw.getText()!= null)
{
pd = ProgressDialog.show(Login.this,"","Loading. Please wait...", true);
pd.show();
Thread t = new Thread() {
public void run(){
download(etuser.getText().toString(), md5(etpw.getText().toString()));
pd.dismiss();
}
};
t.run();
}
}
});
}
public void download (final String user, final String pw)
{
try{
HttpClient client = new DefaultHttpClient();
String postURL = "http://surfkid.redio.de/login";
HttpPost post = new HttpPost(postURL);
List<NameValuePair> params = new ArrayList<NameValuePair>();
params.add(new BasicNameValuePair("username", user));
params.add(new BasicNameValuePair("password", pw));
UrlEncodedFormEntity ent = new UrlEncodedFormEntity(params,HTTP.UTF_8);
post.setEntity(ent);
HttpResponse responsePOST = client.execute(post);
HttpEntity resEntity = responsePOST.getEntity();
final JSONObject jObject = new JSONObject(EntityUtils.toString(resEntity));
JSONObject menuObject = jObject.getJSONObject("responseData");
if (jObject.getInt("responseStatus")== 200 && jObject.get("responseDetails")!= null)
{
sessionid = menuObject.getString("session_id");
//dismissDialog(DIALOG_LOADING);
// pd.dismiss();
}
else
{
//dismissDialog(DIALOG_LOADING);
if (jObject.getInt("responseStatus")== 500)
{
throw new Exception("Server Error");
}
else if (jObject.getInt("responseStatus")== 400)
{
throw new Exception("Wrong User/Password");
}
else
{
throw new Exception();
}
}
//pd.dismiss();
} catch (Exception e) {
//dismissDialog(DIALOG_LOADING);
Toast toast ;
toast = Toast.makeText(getApplicationContext(), e.getMessage(), 500);
toast.show();
}
}
private String md5(String in) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("MD5");
digest.reset();
digest.update(in.getBytes());
byte[] a = digest.digest();
int len = a.length;
StringBuilder sb = new StringBuilder(len << 1);
for (int i = 0; i < len; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
return null;
}
@Override
protected Dialog onCreateDialog(int id) {
Dialog dialog = null;
switch (id) {
case DIALOG_LOADING:
dialog = new ProgressDialog(this);
((ProgressDialog) dialog).setMessage("Loading, please wait...");
break;
}
return dialog;
}
}
My Problem is that the ProgressDialog don't appear.
Please help!!

Intent filter does not unregistered programatically

I have been trying to implement the broadcast receiver programatically , but my unregister method is not working or the app is working even if it in killed state .What i'm trying to accomplish is to display a test message ,when a sms receives ,,i have two buttons in app,register and unregister .If the user presses register ,no matter whether the app is running foreground or background the app should display the toast message,but if i press unregister the app should not invoke toast message .The code is
Code:
package gates.apps.automaticmessageresponder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
public class MainActivity extends Activity {
SmsReceiver broadcastReceiver=new SmsReceiver();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void register(View view){
this.registerReceiver(broadcastReceiver, new IntentFilter(
"android.provider.Telephony.SMS_RECEIVED"));
Log.e("register","pressed");
}
public void unRegister(View view){
this.unregisterReceiver(broadcastReceiver);
Log.e("unregister","pressed");
}
@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;
}
}
and another class is
Code:
package gates.apps.automaticmessageresponder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsManager;
import android.telephony.SmsMessage;
import android.util.Log;
import android.widget.Toast;
public class SmsReceiver extends BroadcastReceiver {
// Get the object of SmsManager
final SmsManager sms = SmsManager.getDefault();
@Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
// Retrieves a map of extended data from the intent.
final Bundle bundle = intent.getExtras();
try {
if (bundle != null) {
final Object[] pdusObj = (Object[]) bundle.get("pdus");
for (int i = 0; i < pdusObj.length; i++) {
SmsMessage currentMessage = SmsMessage.createFromPdu((byte[]) pdusObj[i]);
String phoneNumber = currentMessage.getDisplayOriginatingAddress();
String senderNum = phoneNumber;
String message = currentMessage.getDisplayMessageBody();
Log.i("SmsReceiver", "senderNum: "+ senderNum + "; message: " + message);
// Show alert
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, "senderNum: "+ senderNum + ", message: " + message, duration);
toast.show();
} // end for loop
} // bundle is null
} catch (Exception e) {
Log.e("SmsReceiver", "Exception smsReceiver" +e);
}
}
}
i have not modified the manifest ,except adding sms recieve permission
But the problem with above code is ,even i don't press register it's getting invoked and even if i press unregister button ,it's not stopping
Dude you haven't added a listener for on click(unless you have specified register in layout for button). Nor can I see the button defined. Plus your toast message falls in try catch block. So look for clues in that. I think it'll work once you correct the code. I'll help more if its possible.
Please give a thanks if you think this post helped you!
Sent from my Nexus 4 using XDA Premium 4 Mobile App .

Data That is Fetched From The Web Server Are Appending

I have this search function for my app that fetches data from web server using json, everything works completely except that everytime I search something, the data keeps on appending on my listview. For example if I search for a data with an id number 7 then press search button, the data is fetched and placed on the listview which what I want, but then if I search again the id number 7, there are now 2 instances of data with an id number of 7 in the listview. What I want is to refresh the listview for every search so that the only data that will appear on the listview is the current searched data.
MainActivity.java
Code:
package learn2crack.listview;
import java.util.ArrayList;
import java.util.HashMap;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.EditText;
import learn2crack.listview.library.JSONParser;
public class MainActivity extends Activity {
ListView list;
TextView title;
Button Btngetdata;
ArrayList<HashMap<String, String>> oslist = new ArrayList<HashMap<String, String>>();
//JSON Node Names
private static final String TAG_NEWS = "news";
private static final String TAG_TITLE = "title";
JSONArray android = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
oslist = new ArrayList<HashMap<String, String>>();
Btngetdata = (Button)findViewById(R.id.getdata);
Btngetdata.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
new JSONParse().execute();
}
});
}
private class JSONParse extends AsyncTask<String, String, JSONObject> {
private ProgressDialog pDialog;
@Override
protected void onPreExecute() {
super.onPreExecute();
title = (TextView)findViewById(R.id.title);
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Getting Data ...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(true);
pDialog.show();
}
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
String url = "http://localhost/abc-news/news.php?json-request-news=";
EditText id = (EditText)findViewById(R.id.search_text);
url = url + id.getText().toString();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
pDialog.dismiss();
try {
// Getting JSON Array from URL
android = json.getJSONArray(TAG_NEWS);
for(int i = 0; i < android.length(); i++){
JSONObject c = android.getJSONObject(i);
// Storing JSON item in a Variable
String title = c.getString(TAG_TITLE);
// Adding value HashMap key => value
HashMap<String, String> map = new HashMap<String, String>();
map.put(TAG_TITLE, title);
oslist.add(map);
list=(ListView)findViewById(R.id.list);
ListAdapter adapter = new SimpleAdapter(MainActivity.this, oslist,
R.layout.list_v,
new String[] { TAG_TITLE }, new int[] {
R.id.title });
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at "+oslist.get(+position).get("name"), Toast.LENGTH_SHORT).show();
}
});
}
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}
I attached an image below to support this problem I'm encountering.
Code:
oslist.add(map);
you're adding to the list that drives the adapter, add does what it implies ... maybe you should go though some basics, copy and pasting code sometimes wastes more time that you think it would save in the long run.
Hope that helps
Can you explain it more clearly here?
clonedaccnt said:
Can you explain it more clearly here?
Click to expand...
Click to collapse
erm, add = add ? sorry to come across like this but not sure what you are expecting... a,b,c .add(d) == a,b,c,d
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
clonedaccnt said:
What do I need to do to my code so that the newly searched data will not append on the previous data that is fetched?
Click to expand...
Click to collapse
I thought that was clear, don't "add" to what you have? Are you aware of what an array is ? or a list? and an adapter? cause I think I would start there, you just keep adding to the list that powers the adapter. If you dont want to add to it just don't, either clear it or replace it.
so just to be clear, a list or map has the method .clear() <--- that clears it of all data
I've already solve the problem earlier, I was going to post that I've already solve it but found out that you've already replied on the thread, sorry. About the problem, yes I too used the .clear() of the ArrayList to clear the array before adding a new one, it's my first time to create an activity that pass the data on the same activity, I'm used to passing the data from one activity to another so I don't have a chance to encounter this kind of problem.
Anyways thanks for helping I will not have accomplished this without your help.

[App]Notification notified on Emulator but not visible on Phone

Hi Everyone! I was working on an app, which needed to give a remainder on a certain time, by triggering a notification. The app seemed to work fine on the emulator. But, the notification never shows up on a real phone.
The service which sends the broadcast.
Code:
package com.example.tanmay.yourdiary;
import android.annotation.TargetApi;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import java.text.SimpleDateFormat;
import java.util.Calendar;
/**
* Created by Tanmay on 22-01-2016.
*/
public class MyService extends IntentService {
public MyService() {
super("com.example.tanmay.yourdiary");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
final Context context = this;
final Intent i = new Intent("com.example.tanmay.yourdiary.MyReceiver");
i.setAction("com.example.tanmay.yourdiary.MyReceiver");
new Thread(new Runnable(){
public void run(){
while(true){
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String g="";
g=sdf.format(c.getTime());
Log.i("dd",g);
if(g.equals("05:23")){
Log.i("d3d",g);
LocalBroadcastManager.getInstance(context).sendBroadcast(i);
try {
Thread.sleep(24*60*60*1000);
stopSelf();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
return START_STICKY;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
protected void onHandleIntent(Intent intent) {
}
}
The receiver
Code:
package com.example.tanmay.yourdiary;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
public class MyReceiver extends BroadcastReceiver {
public MyReceiver() {
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onReceive(Context context, Intent intent) {
// TODO: This method is called when the BroadcastReceiver is receiving
// an Intent broadcast.
Log.i("dfdfg", "bc rec");
NotificationCompat.Builder builder = new NotificationCompat.Builder(context).setSmallIcon(R.drawable.ic_launcher).setContentTitle("Reminder").setContentText("Time to write your thoughts!");
TaskStackBuilder taskstackbuilder = TaskStackBuilder.create(context);
taskstackbuilder.addParentStack(MainActivity.class);
Intent i = new Intent(context,Writing.class);
taskstackbuilder.addNextIntent(i);
PendingIntent ip = taskstackbuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(ip);
NotificationManager manager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(1,builder.build());
}
}
Try this code to see if it works on your phone or not
Code:
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.ic_launcher).setContentTitle("Title").setContentText("Description text");
Intent resultIntent = new Intent(mContext, MainActivity.class);
resultIntent.putExtra(AN_ADITIONAL_EXTRA, "User clicked on the notification");
// Because clicking the notification opens a new ("special") activity, there's no need to create an artificial back stack.
PendingIntent resultPendingIntent = PendingIntent.getActivity(mContext, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(resultPendingIntent);
mBuilder.setAutoCancel(true);
// Sets an ID for the notification
int mNotificationId = 10; // give it an ID you recognize within your application
// Gets an instance of the NotificationManager service
NotificationManager mNotifyMgr = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// Builds the notification and issues it.
mNotifyMgr.notify(mNotificationId, mBuilder.build());
And in your MainActivity.class under onNewIntent / onCreate
if(getIntent.getExtras() != null){
if(intent.hasExtra(AN_ADITIONAL_EXTRA)){
// User clicked on the notification, do something
}
}

Categories

Resources