Custom List View Open New Activities - Java for Android App Development

Hey everyone. Here is my code below. I have everything working. Got it to display the pictures and text in a list view. Only issue is that I want to be able to click on one of the list items and have it open an activity. When I added that part in, I get an error that states,
"Error44, 45) error: no suitable constructor found for Intent(<anonymous OnItemClickListener>,Class)
constructor Intent.Intent(String,Uri) is not applicable
(argument mismatch; <anonymous OnItemClickListener> cannot be converted to String)
constructor Intent.Intent(Context,Class<?>) is not applicable
(argument mismatch; <anonymous OnItemClickListener> cannot be converted to Context)"
Here is my code:
Code:
package com.example.matt.nootropicahandbook;
import android.net.Uri;
import android.app.Activity;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.content.Intent;
public class Biohack extends Activity
{
ListView list;
String[] itemname = {"Nootropics", "Supplements", "Metabolic Enhancement","Stacks", "Neuro Stimulation", "Diet", "Stay Away From",};
Integer[] imgid={R.drawable.piracetam1, R.drawable.piracetam2, R.drawable.piracetam3,
R.drawable.piracetam4, R.drawable.piracetam5, R.drawable.piracetam6, R.drawable.piracetam7,};
String[] classNames = {"Main", "Lifehack"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_biohack);
biohacksAdapter adapter=new biohacksAdapter(this, itemname, imgid, classNames);
list=(ListView)findViewById(R.id.list);
list.setAdapter(adapter);
list.setOnItemClickListener(new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// TODO Auto-generated method stub
String openClass = classNames[position];
try{
Class selected = Class.forName("com.example.matt.nootropicahandbook."+openClass);
Intent selectedIntent = new Intent(this, selected);
startActivity(selectedIntent);
}catch (ClassNotFoundException e)
{
e.printStackTrace();
}
}
});
}
}

The error is on the line:
Code:
Intent selectedIntent = new Intent(this, selected);
And here is my adapter class for refrence
Code:
package com.example.matt.nootropicahandbook;
import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
public class biohacksAdapter extends ArrayAdapter<String>{
private final Activity context;
private final String[] itemname;
private final Integer[] imgid;
private final String[] classNames;
public biohacksAdapter(Activity context,String[] itemname, Integer[] imgid, String[] classNames) {
super(context,R.layout.custom_row, itemname);
this.context = context;
this.itemname = itemname;
this.imgid = imgid;
this.classNames = classNames;
}
public View getView(int position, View view, ViewGroup parent)
{
LayoutInflater inflater = context.getLayoutInflater();
View rowView = inflater.inflate(R.layout.custom_row, null, true);
TextView txtTitle = (TextView) rowView.findViewById(R.id.item);
ImageView imageView = (ImageView) rowView.findViewById(R.id.icon);
TextView extratxt = (TextView) rowView.findViewById(R.id.textView1);
txtTitle.setText(itemname[position]);
imageView.setImageResource(imgid[position]);
extratxt.setText("Description "+itemname[position]);
return rowView;
}
}

replace
Intent selectedIntent = new Intent(this, selected);
to
Intent selectedIntent = new Intent(Biohack.this, selected);
because ...

Related

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!!

Webview Fragments and back button

I am having trouble using the back button to go back in webview. I have 5 different fragments in a tab + swipe layout. Each having a different webview. I have my MainActivity.Java as well as a java file for each fragment. Using the examples shown in stackoverflow regarding this (can't link. Sorry) I get a force close whenever I press back on the app. So I received some helped and did a non-conventional stab at it but I get a couple of errors so I'm hoping one of you guys can help me out. I am super new to app development and java in general so please bear with me.
Here is my MainActivity.java where the errors are:
Code:
package com.-------;
import java.util.Locale;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.KeyEvent;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.webkit.WebSettings;
import android.webkit.WebViewFragment;
public class MainActivity extends FragmentActivity {
SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;
[user=439709]@override[/user]
public void onBackPressed(){
mSectionsPagerAdapter.getLastFragment().tryGoBack(); [B]<-Error #1[/B]
}
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());
mViewPager = (ViewPager) findViewById(R.id.pager);
mViewPager.setAdapter(mSectionsPagerAdapter);
}
public class SectionsPagerAdapter extends FragmentPagerAdapter {
private WebViewFragment lastFragment;
public SectionsPagerAdapter(FragmentManager fm) {
super(fm);
}
public WebViewFragment getLastFragment() {
return lastFragment;
}
[user=439709]@override[/user]
public Fragment getItem(int position) {
WebViewFragment Fragment;
switch (position) {
case 0:
Fragment = new fragment1();
break;
case 1:
Fragment = new fragment2();
break;
case 2:
Fragment = new fragment3();
break;
case 3:
Fragment = new fragment4();
break;
case 4:
Fragment = new fragment5();
break;
default:
Fragment = null;
break;
}
lastFragment = Fragment;
return Fragment; [B]<-Error #2[/B]
}
[user=439709]@override[/user]
public int getCount() {
return 5;
}
[user=439709]@override[/user]
public CharSequence getPageTitle(int position) {
Locale l = Locale.getDefault();
switch (position) {
case 0:
return getString(R.string.tab1).toUpperCase(l);
case 1:
return getString(R.string.tab2).toUpperCase(l);
case 2:
return getString(R.string.tab3).toUpperCase(l);
case 3:
return getString(R.string.tab4).toUpperCase(l);
case 4:
return getString(R.string.tab5).toUpperCase(l);
}
return null;
}
}
}
Error #1 is in line 26 and says:
Code:
The method tryGoBack() is undefined for the type WebViewFragment
Error #2 is in line 80 and says
Code:
Type mismatch: cannot convert from WebViewFragment to Fragment
Here is one of my fragment java files as well:
fragment1.java
Code:
package com.-----;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.view.Window;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebViewFragment;
public class fragment1 extends WebViewFragment {
public abstract class WebViewFragment extends Fragment{
public abstract void tryGoBack();
}
WebView myWebView;
[user=439709]@override[/user]
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.fragment1, container, false);
myWebView = (WebView) root.findViewById(R.id.webview1);
myWebView.setWebViewClient(new WebViewClient());
myWebView.loadUrl("url");
return root;
}
}
Any help is greatly appreciated!
When dealing with two or different classes which all extend one of them, so in this case the WebViewFragment extending Fragment and your fragment1 inheriting from WebViewFragment, you can convert the object simply putting
Code:
(NewType)
in front of it. So for error 1, insert (Fragment1) and for error 2 insert (Fragment).
One advice I'd like to give you, Capitalize class names and don't capitalize object and variable names, so it should be Fragment1 (maybe a more clear name) and WebViewFragment fragment.

(Q) Load Custom system font from Extend TextView class.

Hello everyone.
i am trying to load a custom font from /system/fonts i use a custom extend TextView class
however i cant seem to let it load the font :/ i know i can load it through the assets but thats not what i want. i want it to load a custom ttf font from /system/fonts/***
because i would/will be using this Custom TextView class inside the frameworks.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}
Here is my code.
if possible could someone help me ? i have tried some guides and couldnt seem to find a solution to this.
thanks
Best Regards Spacecaker.
SpaceCaker said:
Hello everyone.
i am trying to load a custom font from /system/fonts i use a custom extend TextView class
however i cant seem to let it load the font :/ i know i can load it through the assets but thats not what i want. i want it to load a custom ttf font from /system/fonts/***
because i would/will be using this Custom TextView class inside the frameworks.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}
Here is my code.
if possible could someone help me ? i have tried some guides and couldnt seem to find a solution to this.
thanks
Best Regards Spacecaker.
Click to expand...
Click to collapse
i have fixed it.
Code:
package com.touchwizres.lifecompaniontext;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.graphics.Typeface;
import android.util.AttributeSet;
import android.widget.TextView;
public class LifeCompanionTextView extends TextView {
TextView profilename;
String name;
public LifeCompanionTextView(final Context context, AttributeSet attrs) {
super(context, attrs);
profilename = (TextView) findViewById(R.id.life_companion_tag);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
name = sharedPreferences.getString("companionName","Life Companion");
profilename.setText(name);
Typeface tf = Typeface.createFromFile("/system/fonts/Cooljazz.ttf");
profilename.setTypeface(tf);
BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context c, Intent i) {
name = i.getStringExtra("NAME");
profilename.setText(name);
SharedPreferences sharedPreferences = context.getSharedPreferences("LifeCompanionFile",Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPreferences.edit(); //opens the editor
editor.putString("companionName", name); //true or false
editor.commit();
}
};
context.registerReceiver(mReceiver, new IntentFilter("lifecompanion.CHANGE_COMPANION"));
}
}

How do I change text in card views list?

I'm trying to update the text in my card view. I cannot figure out how to do it. I posted the code of my recyclerAdapter class below.
When a user clicks a card view it should update the text on the card view with a specified time.
Code:
package com.teamtreehouse.oslist;
import java.util.ArrayList;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.net.Uri;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.view.LayoutInflater;
import java.util.Calendar;
import android.content.Intent;
import java.text.SimpleDateFormat;
import java.util.Locale;
public class RecyclerAdapter extends RecyclerView.Adapter<FaucetHolder>
{
private ArrayList<Faucet> faucets;
private Context context;
private SharedPreferences sharedPref;
private String dateFormat = "h:mm a";
public RecyclerAdapter (ArrayList<Faucet> faucetsI,Context context) {
this.faucets = faucetsI;
this.context=context;
}
@Override
public FaucetHolder onCreateViewHolder(ViewGroup viewGroup, int i)
{
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.card_view,viewGroup,false);
FaucetHolder f = new FaucetHolder(v);
return f;
}
@Override
public void onBindViewHolder(FaucetHolder f, int k)
{
final Faucet faucet = faucets.get(k);
f.titleText.setText(faucet.getName());
f.titleText.setOnClickListener(new View.OnClickListener() {
public void onClick(View btn) {
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(faucet.getLink()));
setRenewal(faucet);
context.startActivity(intent);
}
});
}
@Override
public int getItemCount()
{
return faucets.size();
}
private void setRenewal(Faucet g) {
sharedPref = context.getSharedPreferences("myPref",0);
SharedPreferences.Editor edit = sharedPref.edit();
Calendar c = Calendar.getInstance();
long current = c.getTimeInMillis();
long future = current + g.getLength();
c.setTimeInMillis(future);
SimpleDateFormat df = new SimpleDateFormat(dateFormat,Locale.US);
String date = df.format(c.getTime());
edit.putString(g.getSPName(),date);
}
private void updateText(FaucetHolder f, Faucet g) {
sharedPref = context.getSharedPreferences("myPref",0);
String updatedTime = sharedPref.getString(g.getSPName(), null);
f.timeText.setText(updatedTime);
}
}
The full error text would be helpful. If you haven't done it before you can quickly check if something is wrong with your views in the adapter bei commenting them out.
Bump
Sent from my LG-F350K using Tapatalk

[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