[Q] How do you make a clock widget open Alarm Clock App? - Android Software Development

Okay, so i asked this question a while back and didnt get much help, but I am extremely lost. My partner who before actually programmed the app put in the necessary stuff, however i dont think it works in froyo+. I am extremely new to programming in general, and i cannot for the life of me figure this out. I have even tried other codes, but they dont work. Can someone please give me a detailed description on how to make a clock widget open the alarm clock app.
BTW this is the code that we are using at the moment:
package honeycomb.clocks;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.widget.RemoteViews;
public class BlueClock extends AppWidgetProvider
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action))
{
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.blueclock);
Intent ClocksIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER).setComponent(new ComponentName("com.android.alarmclock", "com.android.alarmclock.AlarmClock"));
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, ClocksIntent, 0);
views.setOnClickPendingIntent(R.id.Widget, pendingIntent);
AppWidgetManager.getInstance(context).updateAppWidget(intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS), views);
}
}
}
Click to expand...
Click to collapse

Hi,
I don't know if there's a better aproach, but this is the actual code I'm using to launch the alarm:
Code:
public static final Intent alarmIntent(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent alarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
// Verify clock implementation
String clockImpls[][] = {
{"HTC Alarm ClockDT", "com.htc.android.worldclock", "com.htc.android.worldclock.WorldClockTabControl" },
{"Standar Alarm ClockDT", "com.android.deskclock", "com.android.deskclock.AlarmClock"},
{"Froyo Nexus Alarm ClockDT", "com.google.android.deskclock", "com.android.deskclock.DeskClock"},
{"Moto Blur Alarm ClockDT", "com.motorola.blur.alarmclock", "com.motorola.blur.alarmclock.AlarmClock"},
{"Samsung Galaxy S", "com.sec.android.app.clockpackage","com.sec.android.app.clockpackage.ClockPackage"}
};
boolean foundClockImpl = false;
for(int i=0; i<clockImpls.length; i++) {
String packageName = clockImpls[i][1];
String className = clockImpls[i][2];
try {
ComponentName cn = new ComponentName(packageName, className);
packageManager.getActivityInfo(cn, PackageManager.GET_META_DATA);
alarmClockIntent.setComponent(cn);
foundClockImpl = true;
} catch (NameNotFoundException nf) {
}
}
if (foundClockImpl)
return alarmClockIntent;
else
return null;
}
Hope it helps!

pmduque said:
Hi,
I don't know if there's a better aproach, but this is the actual code I'm using to launch the alarm:
Code:
public static final Intent alarmIntent(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent alarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
// Verify clock implementation
String clockImpls[][] = {
{"HTC Alarm ClockDT", "com.htc.android.worldclock", "com.htc.android.worldclock.WorldClockTabControl" },
{"Standar Alarm ClockDT", "com.android.deskclock", "com.android.deskclock.AlarmClock"},
{"Froyo Nexus Alarm ClockDT", "com.google.android.deskclock", "com.android.deskclock.DeskClock"},
{"Moto Blur Alarm ClockDT", "com.motorola.blur.alarmclock", "com.motorola.blur.alarmclock.AlarmClock"},
{"Samsung Galaxy S", "com.sec.android.app.clockpackage","com.sec.android.app.clockpackage.ClockPackage"}
};
boolean foundClockImpl = false;
for(int i=0; i<clockImpls.length; i++) {
String packageName = clockImpls[i][1];
String className = clockImpls[i][2];
try {
ComponentName cn = new ComponentName(packageName, className);
packageManager.getActivityInfo(cn, PackageManager.GET_META_DATA);
alarmClockIntent.setComponent(cn);
foundClockImpl = true;
} catch (NameNotFoundException nf) {
}
}
if (foundClockImpl)
return alarmClockIntent;
else
return null;
}
Hope it helps!
Click to expand...
Click to collapse
Many thanks for this!!

sndytime said:
Many thanks for this!!
Click to expand...
Click to collapse
Unfortunately it didnt help me , Im not a programmer, and I dont know what Im supposed to do with this code and my partner is pissing me off

in order to launch an external activity from an appwidget you need to set a very specific flag on the intent you broadcast. mine was for launching gmail.
Code:
Intent mailClient = new Intent(Intent.ACTION_VIEW);
mailClient.setClassName("com.google.android.gm", "com.google.android.gm.ConversationListActivity");
[B]mailClient.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);[/B]
PendingIntent onClickPending = PendingIntent.getBroadcast(context, 0, mailClient, 0);
RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.gitc_widget_html);
rv.setOnClickPendingIntent(R.id.full_widget, onClickPending);
//then update Your Appwidgets
//AppWidgetManager manager = AppWidgetManager.getInstance(context);
//manager.updateAppWidget(mAppWidgetId, rv);
and please realize that this was kinda a stub of what to do. i left alot out that was specific to my appwidget but that was needed for this to work. but the premise of creating an intent for what you want to launch then creating a pendingIntent and then attaching it to a view of your appwidget and then updating the remote view of you appwidget by using an AppwidgetManager holds true for any situation.
if you need me to elaborate then we can chat then.
-----
o and you aren't updating your appwidgets properly...
you need to get an array of all appwidgets you have and then call updateAppWidget on each like this (again, with my class names and such)
Code:
AppWidgetManager manager = AppWidgetManager.getInstance(context);
int[] ids = manager.getAppWidgetIds(new ComponentName(context, GITextCloud.class));
for (int id : ids) {
manager.updateAppWidget(id, rv);
//rv is the RemoteViews you created earlier up in the program...
//RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.gitc_widget_html);
}

pmduque said:
Hi,
I don't know if there's a better aproach, but this is the actual code I'm using to launch the alarm:
Code:
public static final Intent alarmIntent(Context context) {
PackageManager packageManager = context.getPackageManager();
Intent alarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
// Verify clock implementation
String clockImpls[][] = {
{"HTC Alarm ClockDT", "com.htc.android.worldclock", "com.htc.android.worldclock.WorldClockTabControl" },
{"Standar Alarm ClockDT", "com.android.deskclock", "com.android.deskclock.AlarmClock"},
{"Froyo Nexus Alarm ClockDT", "com.google.android.deskclock", "com.android.deskclock.DeskClock"},
{"Moto Blur Alarm ClockDT", "com.motorola.blur.alarmclock", "com.motorola.blur.alarmclock.AlarmClock"},
{"Samsung Galaxy S", "com.sec.android.app.clockpackage","com.sec.android.app.clockpackage.ClockPackage"}
};
boolean foundClockImpl = false;
for(int i=0; i<clockImpls.length; i++) {
String packageName = clockImpls[i][1];
String className = clockImpls[i][2];
try {
ComponentName cn = new ComponentName(packageName, className);
packageManager.getActivityInfo(cn, PackageManager.GET_META_DATA);
alarmClockIntent.setComponent(cn);
foundClockImpl = true;
} catch (NameNotFoundException nf) {
}
}
if (foundClockImpl)
return alarmClockIntent;
else
return null;
}
Hope it helps!
Click to expand...
Click to collapse
this isnt actually launching the clock application. you are just returning an intent that can be used to launch the clock application (still need to make a pendingIntent and attach it to a view). there is a difference and a new programmer could be very confused by this post.
other than that it looks like a nice way to find the class and package names for what clock is installed. =)

schwartzman93 said:
Unfortunately it didnt help me , Im not a programmer, and I dont know what Im supposed to do with this code and my partner is pissing me off
Click to expand...
Click to collapse
Code:
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.widget.RemoteViews;
public class Widget2 extends AppWidgetProvider
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
PendingIntent pendingIntent;
if (AppWidgetManager.ACTION_APPWIDGET_UPDATE.equals(action))
{
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget2);
pendingIntent = PendingIntent.getActivity(context, 0,getAlarmPackage(context), 0);
views.setOnClickPendingIntent(R.id.Widget2, pendingIntent);
AppWidgetManager
.getInstance(context)
.updateAppWidget(
intent.getIntArrayExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS),
views);
}
}
public Intent getAlarmPackage(Context context)
{
PackageManager packageManager = context.getPackageManager();
Intent AlarmClockIntent = new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER);
String clockImpls[][] = {
{ "Standard Alarm", "com.android.alarmclock",
"com.android.alarmclock.AlarmClock" },
{ "HTC Alarm ClockDT", "com.htc.android.worldclock",
"com.htc.android.worldclock.WorldClockTabControl" },
{ "Standard Alarm ClockDT", "com.android.deskclock",
"com.android.deskclock.AlarmClock" },
{ "Froyo Nexus Alarm ClockDT",
"com.google.android.deskclock",
"com.android.deskclock.DeskClock" },
{ "Moto Blur Alarm ClockDT",
"com.motorola.blur.alarmclock",
"com.motorola.blur.alarmclock.AlarmClock" },
{ "Samsung Galaxy S", "com.sec.android.app.clockpackage",
"com.sec.android.app.clockpackage.ClockPackage" } };
boolean foundClockImpl = false;
for (int i = 0; i < clockImpls.length; i++)
{
String packageName = clockImpls[i][1];
String className = clockImpls[i][2];
try
{
ComponentName cn = new ComponentName(packageName, className);
packageManager.getActivityInfo(cn,PackageManager.GET_META_DATA);
AlarmClockIntent.setComponent(cn);
foundClockImpl = true;
} catch (NameNotFoundException nf)
{
}
}
if (foundClockImpl)
{
return AlarmClockIntent;
}
else
{
return null;
}
}
}
Here is the Complete Source of my Appwidget Provider it generates a Clickevent on Appwidget to start the specific alarm app on the different phones.
Here is the Link to the simple Clock widget i have extended
Hope this helps!!

SUCCESS!!!!! Thank you guys so much, you have no idea how grateful I am for your help.

Related

ImageView from url in listview

i created a java web service. it returns ArrayList type(text,image URL).
and my client side code i receive the by following code:
public class CustomeAdapter extends ArrayAdapter<RowItem> {
private List<RowItem> objects;
Context context;
private Bitmap bitmap;
Drawable d;
ViewHolder holder = null;
public CustomeAdapter(Context context, int listViewResourceId, List<RowItem> first) {
super(context, listViewResourceId, first);
this.context = context;
}
private class ViewHolder {
ImageView image;
TextView name,service,local;
}
@suppressLint("NewApi")
public View getView(int position, View convertView, ViewGroup parent){
//ViewHolder holder = null;
RowItem rowItem = getItem(position);
//final Bitmap bitmap = null;
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.image=(ImageView) convertView.findViewById(R.id.imageView1);
holder.name = (TextView) convertView.findViewById(R.id.item_textView1);
holder.service = (TextView) convertView.findViewById(R.id.item_textView2);
holder.local = (TextView) convertView.findViewById(R.id.item_textView3);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.name.setText("Name:"+rowItem.getCustomerName());
holder.service.setText("Service:"+rowItem.getServiceName());
holder.local.setText("Locality:"+rowItem.getLocalityName());
String src="http://192.168.1.16:8080/"+rowItem.getImage();
try {
URL url = new URL(src);
bitmap = BitmapFactory.decodeStream(url.openConnection().getInputStream());
holder.image.setImageBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
return convertView;
}
i am getting followimg error:
android.os.NetworkOnMainThreadException
can any one help me
I think there is a library that does this well, but can't remember it right now...
Check the library repo, and some of the apps that list libraries. Also, maybe Google will turn up something helpful.
Lazy list perhaps?
https://github.com/thest1/LazyList

Adding custom apps to an app switcher panel

I am currently working on an App Switcher with the ability to also add custom apps in the app switcher. So, I already got the recent apps loader built. This is the code for this part of the app:
Code:
public class Corners_RecentApps extends Activity {
private ArrayList<PanelItemDetail> rowItems = null;
private ListView listView;
private ArrayList<String> packageName = null;
private ArrayList<String> className = null;
[user=439709]@override[/user]
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
if(rightpanel){
overridePendingTransition(R.anim.left_slide_in_fast, 0);
setContentView(R.layout.right_side_panel);
}
else
{
overridePendingTransition(R.anim.right_slide_in_fast, 0);
setContentView(R.layout.activity_left_side_panel);
}
ImageView imgbtn = (ImageView) findViewById(R.id.transparentbackground);
ImageView panelbg = (ImageView) findViewById(R.id.panelbackground);
listView = (ListView)findViewById(R.id.panelcontents);
packageName = new ArrayList<String>();
className = new ArrayList<String>();
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RecentTaskInfo> tasks = am.getRecentTasks(30, 0);
rowItems = new ArrayList<PanelItemDetail>();
PackageManager pacMgr = getPackageManager();
for (ActivityManager.RecentTaskInfo recentTask : tasks) {
try {
rowItems.add(new PanelItemDetail(pacMgr.getApplicationIcon(recentTask.origActivity.getPackageName())));
packageName.add(recentTask.origActivity.getPackageName());
className.add(recentTask.origActivity.getClassName());
Log.d("#@#", "getPackageName = " + recentTask.origActivity.getPackageName());
Log.d("#@#", "getClassName = " + recentTask.origActivity.getClassName());
} catch (NameNotFoundException e) {
e.printStackTrace();
}
}
SharedPreferences myPreference = PreferenceManager.getDefaultSharedPreferences(this);
String itembg = myPreference.getString("itembg_list", "");
if(itembg.equals("defaults"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_default, rowItems);
listView.setAdapter(adapter);
}
else if(itembg.equals("dark"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_dark, rowItems);
listView.setAdapter(adapter);
}
else if(itembg.equals("light"))
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_light, rowItems);
listView.setAdapter(adapter);
}
else
{
PanelArrayAdapter adapter = new PanelArrayAdapter(this,R.layout.panelrow_none, rowItems);
listView.setAdapter(adapter);
}
listView.setOnItemClickListener(new OnItemClickListener() {
[user=439709]@override[/user]
public void onItemClick(AdapterView<?> parent, View view, int postion, long id) {
try{
boolean rightpanel = getSharedPreferences(getPackageName() + "_preferences", Context.MODE_PRIVATE).getBoolean("panelpos_right", true);
Intent taskintent = getPackageManager().getLaunchIntentForPackage(packageName.get(postion).toString());
startActivity(taskintent);
if(rightpanel){
overridePendingTransition(R.anim.right_slide_in, R.anim.zoom_out);
}
else
{
overridePendingTransition(R.anim.left_slide_in, R.anim.zoom_out);
}
finish();
}
catch (NullPointerException fail) {
Toast.makeText(getApplicationContext(), "!", Toast.LENGTH_SHORT).show();
}
}
});
SharedPreferences panelbgpref = PreferenceManager.getDefaultSharedPreferences(this);
String panelbgset = panelbgpref.getString("panelbg_list", "");
if(panelbgset.equals("light"))
{
panelbg.setImageResource(R.drawable.panelbg_light);
}
else
{
panelbg.setImageResource(R.drawable.panelbg);
}
imgbtn.setOnClickListener(new View.OnClickListener(){
[user=439709]@override[/user]
public void onClick(View v) {
if(v.getId() ==R.id.transparentbackground){
moveTaskToBack(true);
finish();
}
}
});
}
Now I want to let the users define in the app settings up to 3 own apps that should be shown on every moment.
How should I do that?
Thank you

Loading a new fragment from an OnClick set in asyncTask

I have a fragment, which contains a button that when pressed loads a new fragment. The new fragment runs an async task to populate a listview with data.
I am running into trouble, trying to load a new fragment from the onClick. The problem is I can not get the getFragmentManager();
My async task looks like this:
Code:
public class GetStyleStatisticsJSON extends AsyncTask<String, Void, String> {
Context c;
private ProgressDialog Dialog;
android.support.v4.app.Fragment Fragment_one;
public GetStyleStatisticsJSON(Context context)
{
c = context;
Dialog = new ProgressDialog(c);
}
@Override
protected String doInBackground(String... arg0) {
// TODO Auto-generated method stub
return readJSONFeed(arg0[0]);
}
protected void onPreExecute() {
Dialog.setMessage("Analyzing Statistics");
Dialog.setTitle("Loading");
Dialog.setCancelable(false);
Dialog.show();
}
protected void onPostExecute(String result){
//decode json here
try{
JSONArray jsonArray = new JSONArray(result);
//acces listview
ListView lv = (ListView) ((Activity) c).findViewById(R.id.yourStyleStatistics);
//make array list for beer
final List<StyleInfo> tasteList = new ArrayList<StyleInfo>();
for(int i = 0; i < jsonArray.length(); i++) {
String style = jsonArray.getJSONObject(i).getString("style");
String rate = jsonArray.getJSONObject(i).getString("rate");
String beerID = jsonArray.getJSONObject(i).getString("id");
int count = i + 1;
style = count + ". " + style;
//create object
StyleInfo tempTaste = new StyleInfo(style, rate, beerID);
//add to arraylist
tasteList.add(tempTaste);
//add items to listview
StyleInfoAdapter adapter1 = new StyleInfoAdapter(c ,R.layout.brewer_stats_listview, tasteList);
lv.setAdapter(adapter1);
//set up clicks
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
StyleInfo o=(StyleInfo)arg0.getItemAtPosition(arg2);
String bID = o.id;
//todo: add onclick for fragment to load
FragmentManager man= (Activity)c.getFragmentManager();
FragmentTransaction tran = man.beginTransaction();
Fragment_one = new StylePage2();
final Bundle bundle = new Bundle();
bundle.putString("beerIDSent", bID);
Fragment_one.setArguments(bundle);
tran.replace(R.id.main, Fragment_one);//tran.
tran.addToBackStack(null);
tran.commit();
}
});
}
}
catch(Exception e){
}
Dialog.dismiss();
}
public String readJSONFeed(String URL) {
StringBuilder stringBuilder = new StringBuilder();
HttpClient httpClient = new DefaultHttpClient();
HttpGet httpGet = new HttpGet(URL);
try {
HttpResponse response = httpClient.execute(httpGet);
StatusLine statusLine = response.getStatusLine();
int statusCode = statusLine.getStatusCode();
if (statusCode == 200) {
HttpEntity entity = response.getEntity();
InputStream inputStream = entity.getContent();
BufferedReader reader = new BufferedReader(
new InputStreamReader(inputStream));
String line;
while ((line = reader.readLine()) != null) {
stringBuilder.append(line);
}
inputStream.close();
} else {
Log.d("JSON", "Failed to download file");
}
} catch (Exception e) {
Log.d("readJSONFeed", e.getLocalizedMessage());
}
return stringBuilder.toString();
}
}
can not resolve method FragmentManager() is the error I am receiving
Hi,
To be able to call getFragmentManager() or getSupportFragmentManager() you'll need to use FragmentActivity, so what I would do is:
1. Make sure the activity that calls the asycTask is a FragmentActivity.
2. Pass this actvity to the asycTask.
Something like: (asyncTask method)
setActivity(Activity activity)
{
fm = activity.getFragmentManager();
}
mrsegev said:
Hi,
To be able to call getFragmentManager() or getSupportFragmentManager() you'll need to use FragmentActivity, so what I would do is:
1. Make sure the activity that calls the asycTask is a FragmentActivity.
2. Pass this actvity to the asycTask.
Something like: (asyncTask method)
setActivity(Activity activity)
{
fm = activity.getFragmentManager();
}
Click to expand...
Click to collapse
thats the problem, I launch the asyncTask from a fragment....
Oh! So you'll access your activity like this:
getActivity().getFragmentManager();

How do I implement a onscroll Listener to my listview?

I have a large data to load from JSON.
I have implemented a custom list view by following a tutorial, now since the data is huge I want it load as the user scrolls.
This is my LoadRestaurant class code which is inside the main activity.
Code:
class LoadRestaurants extends AsyncTask<String, String, String> {
//Show Progress Dialog
@Override
protected void onPreExecute() {
super.onPreExecute();
pDialog = new ProgressDialog(SearchAll.this);
pDialog.setMessage("Loading All Restaurants...");
pDialog.setIndeterminate(false);
pDialog.setCancelable(false);
pDialog.show();
}
protected String doInBackground(String... arg) {
//building parameters
List<NameValuePair> params = new ArrayList<NameValuePair>();
//Getting JSON from URL
String json = jsonParser.makeHttpRequest(URL_RESTAURANT_LIST, "GET", params);
//Log Cat Response Check
Log.d("Areas JSON: ", "> " + json);
try {
restaurants = new JSONArray(json);
if (restaurants != null) {
//loop through all restaurants
for (int i = 0; i < restaurants.length(); i++) {
JSONObject c = restaurants.getJSONObject(i);
//Storing each json object in the variable.
String id = c.getString(TAG_ID);
String name = c.getString(TAG_NAME);
String location = c.getString(TAG_LOCATION);
String rating = c.getString(TAG_RATING);
//Creating New Hashmap
HashMap<String, String> map = new HashMap<String, String>();
//adding each child node to Hashmap key
map.put(TAG_ID, id);
map.put(TAG_NAME, name);
map.put(TAG_LOCATION, location);
map.put(TAG_RATING, rating);
//adding HashList to ArrayList
restaurant_list.add(map);
}
}
} catch (JSONException e) {
e.printStackTrace();
}
return null;
}
protected void onPostExecute(String file_url) {
//dismiss the dialog
pDialog.dismiss();
//Updating UI from the Background Thread
runOnUiThread(new Runnable() {
@Override
public void run() {
ListAdapter adapter = new SimpleAdapter(
SearchAll.this, restaurant_list,
R.layout.listview_restaurants, new String[]{
TAG_ID, TAG_NAME, TAG_LOCATION, TAG_RATING}, new int[]{
R.id.login_id, R.id.restaurant_name, R.id.address, R.id.rating});
setListAdapter(adapter);
ListView lv = getListView();
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
// Bundle bundle = new Bundle();
Intent intent = new Intent(SearchAll.this, RestaurantProfile.class);
String loginId = ((TextView) view.findViewById(R.id.login_id)).getText().toString();
intent.putExtra("login_id", loginId);
startActivity(intent);
}
});
}
});
}
}
}
I want to load around 20 restaurants and then it auto loads another 20 as soon as user reaches the end of first 20.
There are lots of tutorials online but its confusing to implement.
Please help me out!
The custom ListView, support for automatic loading you can try https://github.com/chrisbanes/Android-PullToRefresh

[Q] Create notification when bluetooth data is received in the background

I am currently working on an arduino project that connects to my phone using a bluetooth module.
On the arduino I have various diagnostic sensors hooked up to it. When the sensors "sense an error," I would like to receive a notification on my phone.
I'm guessing this would require me to program an app that runs as a background service listening for data coming across the bluetooth connection. Then when it receives the data it would need to create a notification and play the system notification sound.
Is it even possible to listen to the data coming from the bluetooth module while being run in the background?
How hard would this be for me, a beginner, to program? I have programmed in several other languages (html, visual basic, and python), so I understand basic coding concepts.
I would like to thank everyone for all the help. The amount of replies just shows how useful this forum is to beginning devs.
Anyways, after three days of straight research, I pumped out a working app. Now I would like for someone to review my code and see if anything can be revised or done better, as I really don't know what I'm doing.
The main activity:
Code:
package com.example.bluetooth;
//Import needed files
import java.util.ArrayList;
import java.util.Set;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
//Main activity class
public class MainActivity extends ActionBarActivity {
//Creates object variables
private Button list, disconnect;
private ListView lv;
private BluetoothAdapter BA;
private Set<BluetoothDevice> pairedDevices;
private Toast toast;
@Override
//on create
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//creates variables containing id's
list = (Button) findViewById(R.id.button1);
disconnect = (Button) findViewById(R.id.button2);
lv = (ListView) findViewById(R.id.listView1);
//When you click the list item
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Object obj = lv.getAdapter().getItem(position);
String str = obj.toString();
int strStartIndex = str.indexOf("\n");
str = str.substring(strStartIndex + 1);
//check to see if bluetooth is enabled before
//starting the service
if (BA.isEnabled()) {
toast = Toast.makeText(getApplicationContext(),
"Connecting to: " + str, Toast.LENGTH_SHORT);
toast.show();
//connects to item you tapped, creating a service
Intent btConnectIntent = new Intent(MainActivity.this, ForegroundService.class);
btConnectIntent.setAction("btConnect");
btConnectIntent.putExtra("mac", str);
startService(btConnectIntent);
}
//Bluetooth isn't enabled
else{
toast = Toast.makeText(getApplicationContext(),
"Bluetooth must be enabled!", Toast.LENGTH_SHORT);
toast.show();
}
}
});
}
//When you click the list button
public void list(View view) {
//Get bluetooth adapter and set it to BA
BA = BluetoothAdapter.getDefaultAdapter();
//Make sure device has bluetooth
if (BA != null) {
//See if bluetooth is enabled and if it is, get the list of paired devices
if (BA.isEnabled()) {
bluetoothList();
}
//If bluetooth isn't enabled, enable it
else {
//Start new intent to see if they turn on bluetooth
Intent turnOn = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(turnOn, 0);
toast = Toast.makeText(getApplicationContext(),
"Bluetooth must be on!", Toast.LENGTH_SHORT);
toast.show();
}
}
//Device doesn't have a bluetooth adapter
else {
toast = Toast.makeText(getApplicationContext(),
"Your device doesn't support bluetooth!", Toast.LENGTH_SHORT);
toast.show();
}
}
//Waiting to see if they turn on bluetooth
//If they do, show list
public void onActivityResult(int requestCode, int resultCode, Intent turnOn) {
//if it turned on successfully, get the list of paired bluetooth devices
if (resultCode == RESULT_OK) {
bluetoothList();
}
}
//When they click disconnect button, stop the service
public void disconnect(View view) {
Intent stopIntent = new Intent(MainActivity.this, ForegroundService.class);
stopIntent.setAction("stopForeground");
startService(stopIntent);
}
//Method that gets the list of paired devices
private void bluetoothList() {
pairedDevices = BA.getBondedDevices();
ArrayList list = new ArrayList();
for (BluetoothDevice bt : pairedDevices)
list.add(bt.getName() + "\n" + bt.getAddress());
//create array adapter
final ArrayAdapter adapter = new ArrayAdapter
(this, android.R.layout.simple_list_item_1, list);
//connect our list view to the adapter
lv.setAdapter(adapter);
toast = Toast.makeText(getApplicationContext(),
"Showing paired devices", Toast.LENGTH_SHORT);
toast.show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
}
And the foreground service:
Code:
package com.example.bluetooth;
//Import needed files
import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
//Service class
public class ForegroundService extends Service {
int FOREGROUND_ID = 1997;
private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private BluetoothAdapter BA;
private BluetoothSocket BS;
private StringBuilder sb = new StringBuilder();
private Toast toast;
private String mac;
private Handler h;
//When the service is created
//Doesn't run again unless service is totally killed
public void onCreate() {
//Set service as foreground service
startForeground(FOREGROUND_ID, buildForegroundNotification());
toast = Toast.makeText(getApplicationContext(), "Service started", Toast.LENGTH_SHORT);
toast.show();
//Get bluetooth adapter and set it to BA
BA = BluetoothAdapter.getDefaultAdapter();
//Create a handler to listen for data
//New threads send data to this handler
//If it receives data, show it in a toast
h = new Handler() {
public void handleMessage(Message msg) {
Bundle bundle = msg.getData();
toast = Toast.makeText(getApplicationContext(), bundle.getString("str"), Toast.LENGTH_SHORT);
toast.show();
}
;
};
}
//Called every time an activity runs startService
public int onStartCommand(Intent intent, int flags, int startId) {
//When an activity starts the service, it sends an action
//Check if action = btConnect
if (intent.getAction().equals("btConnect")) {
//Make sure there's not already an open socket
if (BS == null) {
//Creates a bundle to get data
Bundle extras = intent.getExtras();
//Extracts data from bundle, in this case the mac address
mac = extras.getString("mac");
//Creates another handler to listen for data
final Handler mHandler = new Handler();
//A runnable called when can't connect
final Runnable hUnsuccessful = new Runnable() {
public void run() {
toast = Toast.makeText(getApplicationContext(),
"Unsuccessful", Toast.LENGTH_SHORT);
toast.show();
toast = Toast.makeText(getApplicationContext(), "Service stopped", Toast.LENGTH_SHORT);
toast.show();
//Kill the service
stopForeground(true);
stopSelf();
}
};
//A runnable called when successfully connected
final Runnable hSuccessful = new Runnable() {
public void run() {
//Run method using socket BS
//Method listens for data coming across socket
ConnectedThread(BS);
toast = Toast.makeText(getApplicationContext(),
"Successful", Toast.LENGTH_SHORT);
toast.show();
}
};
//Creates a new thread since BS.connect
//will block the main thread otherwise
Thread thread = new Thread() {
public void run() {
//Creates BluetoothDevice from the mac address
//mac address was passed to service in onStartCommand
BluetoothDevice device = BA.getRemoteDevice(mac);
// Get a BluetoothSocket to connect with the given BluetoothDevice
try {
// MY_UUID is the app's UUID string, also used by the server code
BS = device.createRfcommSocketToServiceRecord(MY_UUID);
}
//If it can't create a socket
catch (IOException e) {
//Send unsuccessful to the handler
mHandler.post(hUnsuccessful);
return;
}
// Cancel discovery because it will slow down the connection
BA.cancelDiscovery();
//Try to connect
try {
BS.connect();
}
// Unable to connect, send a toast and close the socket
catch (IOException connectException) {
//Try to close socket
try {
if (BS != null) {
BS.close();
BS = null;
}
//Send unsuccessful to the handler
mHandler.post(hUnsuccessful);
return;
}
//Can't close socket, do nothing
catch (IOException closeException) {
}
}
//If it made it to here, it was successful
//Send successful to the handler
mHandler.post(hSuccessful);
}
};
//Start the thread
thread.start();
}
//if BS != null
//Currently connected to a socket
else {
toast = Toast.makeText(getApplicationContext(), "You must disconnect first", Toast.LENGTH_SHORT);
toast.show();
}
}
//When an activity starts the service, it sends an action
//Check if action = stopForeground
if (intent.getAction().equals("stopForeground")) {
toast = Toast.makeText(getApplicationContext(), "Service stopped", Toast.LENGTH_SHORT);
toast.show();
//Try to close socket if one is open
try {
if (BS != null) {
BS.close();
BS = null;
toast = Toast.makeText(getApplicationContext(),
"Bluetooth device disconnected", Toast.LENGTH_SHORT);
toast.show();
}
}
//If it can't close it, do nothing
catch (IOException e) {
}
//Kill the service
stopForeground(true);
stopSelf();
}
//Service should stay alive, unless we kill it
return START_STICKY;
}
//Method to create foreground notification
private Notification buildForegroundNotification() {
NotificationCompat.Builder notification = new NotificationCompat.Builder(this);
notification.setOngoing(true);
notification.setContentTitle("Bluetooth Service")
.setContentText("Service to listen for bluetooth data")
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setPriority(Notification.PRIORITY_MIN);
return (notification.build());
}
//Method to create a notification
private void notification(String title, String text) {
int mId = 0;
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(android.R.drawable.sym_def_app_icon)
.setContentTitle(title)
.setContentText(text)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000})
.setPriority(NotificationCompat.PRIORITY_MAX);
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
mBuilder.setSound(alarmSound);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(mId, mBuilder.build());
}
//Looping method to listen for data over bluetooth socket
private void ConnectedThread(BluetoothSocket socket) {
final InputStream mmInStream;
InputStream tmpIn = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
//Create new thread as it will otherwise block main thread
Thread thread = new Thread() {
public void run() {
byte[] buffer = new byte[256]; //buffer store for the stream
int bytes; //bytes returned from read()
//Keep listening to the InputStream until an exception occurs
while (true) {
try {
Message msg = new Message();
Bundle bundle = new Bundle();
// Read from the InputStream
bytes = mmInStream.read(buffer); // Get number of bytes and message in "buffer"
String strIncom = new String(buffer, 0, bytes);
sb.append(strIncom);
int endOfLineIndex = sb.indexOf("\r\n");
if (endOfLineIndex > 0) {
String sbprint = sb.substring(0, endOfLineIndex);
sb.delete(0, sb.length());
bundle.putString("str", sbprint);
msg.setData(bundle);
h.sendMessage(msg);
notification("Sensor Data:", sbprint);
}
}
//If InputStream gets interrupted
catch (IOException e) {
Message msg = new Message();
Bundle bundle = new Bundle();
bundle.putString("str", "Lost connection");
msg.setData(bundle);
h.sendMessage(msg);
notification("Error", "Lost connection");
Intent stopIntent = new Intent(getApplicationContext(), ForegroundService.class);
stopIntent.setAction("stopForeground");
startService(stopIntent);
break;
}
}
}
};
//Start the thread
thread.start();
}
//Required
public IBinder onBind(Intent intent) {
return null;
}
}

Categories

Resources