I'm working on a group project for a class I'm taking and we cannot seem to figure out why our Alarm Manager does not fire intents repeatedly. We've picked through the source code from top to bottom and cannot seem to isolate the source of this issue.
Can anyone recommend a fix? (or perhaps a starting point?)
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Rules.this, LMW.class);
PendingIntent pintent = PendingIntent.getService(Rules.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
7 * 1000, pintent);
// Start 2nd service using AlarmManager
Intent intent2 = new Intent(Rules.this, KillTimer.class);
PendingIntent pintent2 = PendingIntent.getActivity(Rules.this, 0, intent2,
0);
AlarmManager alarm2 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
120 * 1000, pintent2); // here
Source:
public class AlarmManager extends ListActivity {
TextView empty;
TextView empty2;
private static final int ACTIVITY_CREATE = 0;
private static final int ACTIVITY_EDIT = 1;
public static final int INSERT_ID = Menu.FIRST;
private static final int DELETE_ID = Menu.FIRST + 1;
private List<ParseObject> todos;
private Dialog progressDialog;
private class RemoteDataTask extends AsyncTask<Void, Void, Void> {
// Override this method to do custom remote calls
public void setVisibility() {
empty.setVisibility(View.VISIBLE);
empty2.setVisibility(View.VISIBLE);
}
protected void doInBackground(Void... params) {
// Gets the current list of todos in sorted order
ParseQuery query = new ParseQuery("TestObject");
query.orderByDescending("_created_at");
try {
todos = query.find();
} catch (ParseException e) {
return;
}
runOnUiThread(new Runnable() {
public void run() {
}});
}
#Override
protected void onPreExecute() {
ToDoListActivity.this.progressDialog = ProgressDialog.show(ToDoListActivity.this, "",
"Loading...", true);
super.onPreExecute();
}
#Override
protected void onProgressUpdate(Void... values) {
super.onProgressUpdate(values);
}
#Override
protected void onPostExecute(Void result) {
// Put the list of todos into the list view
ArrayAdapter<String> adapter = new ArrayAdapter<String>(ToDoListActivity.this,
R.layout.todo_row);
for (ParseObject todo : todos) {
adapter.add((String) todo.get("DataI"));
adapter.add((String) todo.get("DataO"));
adapter.add((String) todo.get("DataRSSI"));
adapter.add((String) todo.get("DataSSID"));
adapter.add((String) todo.get("DataTIME"));
adapter.add((String) todo.get("DataRESTRICTED"));
}
setListAdapter(adapter);
ToDoListActivity.this.progressDialog.dismiss();
}
}
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_new);
empty = (TextView) findViewById(android.R.id.empty);
empty.setVisibility(View.INVISIBLE);
new RemoteDataTask().execute();
registerForContextMenu(getListView());
}
private void createTodo() {
Intent i = new Intent(this, CreateTodo.class);
startActivityForResult(i, ACTIVITY_CREATE);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (intent == null) {
return;
}
final Bundle extras = intent.getExtras();
switch (requestCode) {
case ACTIVITY_CREATE:
new RemoteDataTask() {
protected void doInBackground(Void... params) {
String DataI = extras.getString("DataI");
String DataO = extras.getString("DataO");
String DataRSSI = extras.getString("DataRSSI");
String DataSSID = extras.getString("DataSSID");
String DataTIME = extras.getString("DataTIME");
String DataRESTRICTED = extras.getString("DataRESTRICTED");
ParseObject todo = new ParseObject("Todo");
todo.put("DataI", DataI);
todo.put("DataO", DataO);
todo.put("DataRSSI", DataRSSI);
todo.put("DataSSID", DataSSID);
todo.put("DataTIME", DataTIME);
todo.put("DataRESTRICTED", DataRESTRICTED);
try { todo.save(); } catch (ParseException e) {
}
super.doInBackground();
return;
}
}.execute();
break;
case ACTIVITY_EDIT:
// Edit the remote object
final ParseObject todo;
todo = todos.get(extras.getInt("position"));
todo.put("DataI", extras.getString("DataI"));
todo.put("DataO", extras.getString("DataO"));
todo.put("DataRSSI", extras.getString("DataRSSI"));
todo.put("DataSSID", extras.getString("DataSSID"));
todo.put("DataTIME", extras.getString("DataTIME"));
todo.put("DataRESTRICTED", extras.getString("DataRESTRICTED"));
new RemoteDataTask() {
protected void doInBackground(Void... params) {
try {
todo.save();
} catch (ParseException e) {
}
super.doInBackground();
return;
}
}.execute();
break;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
boolean result = super.onCreateOptionsMenu(menu);
menu.add(0, INSERT_ID, 0, R.string.menu_insert);
return result;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
menu.add(0, DELETE_ID, 0, R.string.menu_delete);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case DELETE_ID:
AdapterContextMenuInfo info = (AdapterContextMenuInfo) item.getMenuInfo();
// Delete the remote object
final ParseObject todo = todos.get(info.position);
new RemoteDataTask() {
protected void doInBackground(Void... params) {
try {
todo.delete();
} catch (ParseException e) {
}
super.doInBackground();
return;
}
}.execute();
return true;
}
return super.onContextItemSelected(item);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case INSERT_ID:
createTodo();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
Intent i = new Intent(this, CreateTodo.class);
i.putExtra("DataI", todos.get(position).getString("DataI").toString());
i.putExtra("DataO", todos.get(position).getString("DataO").toString());
i.putExtra("DataRSSI", todos.get(position).getString("DataRSSI").toString());
i.putExtra("DataSSID", todos.get(position).getString("DataSSID").toString());
i.putExtra("DataTIME", todos.get(position).getString("DataTIME").toString());
i.putExtra("DataRESTRICTED", todos.get(position).getString("DataRESTRICTED").toString());
i.putExtra("position", position);
startActivityForResult(i, ACTIVITY_EDIT);
}
}
Service Class
public class LMW extends Service {
String Watchdog = "Watchdog";
String Dirty1 = "playboy";
String Dirty2 = "penthouse";
String Dirty3 = "pornhub";
String Dirty4 = "thepiratebay";
String Dirty5 = "vimeo";
String Dirty6 = "wired";
String Dirty7 = "limewire";
String Dirty8 = "whitehouse";
String Dirty9 = "hackaday";
String Dirty10 = "slashdot";
Long mStartRX = TrafficStats.getTotalRxBytes();
Long mStartTX = TrafficStats.getTotalTxBytes();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Watchdog Running!", Toast.LENGTH_SHORT).show();
Long.toString(mStartTX);
Long.toString(mStartRX);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataO", String.valueOf(mStartTX));
testObject.put("DataI", String.valueOf(mStartRX));
testObject.saveInBackground(); String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = getContentResolver().query(android.provider.Browser.BOOKMARKS_URI,
projection, null, null, null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor.getColumnIndex(Browser.BookmarkColumns.URL));
Log.i(Watchdog, url);
if (url.toLowerCase().contains(Dirty1) || url.toLowerCase().contains(Dirty2) || url.toLowerCase().contains(Dirty3) || url.toLowerCase().contains(Dirty4) || url.toLowerCase().contains(Dirty5) || url.toLowerCase().contains(Dirty6) || url.toLowerCase().contains(Dirty7) || url.toLowerCase().contains(Dirty8) || url.toLowerCase().contains(Dirty9) || url.toLowerCase().contains(Dirty10))
{
Intent intent2 = new Intent(LMW.this, Warning.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent2);
break;
} } while (cursor.moveToNext());
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}}
Activity Class:
public class Timer extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.killtimer);
Toast.makeText(getApplicationContext(), "KillWifi Running!", Toast.LENGTH_SHORT).show();
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
int networkId = wifiManager.getConnectionInfo().getNetworkId();
wifiManager.removeNetwork(networkId );
wifiManager.saveConfiguration();
}}
Go through the links, It helped me a lot.
http://android-er.blogspot.in/2010/10/simple-example-of-alarm-service-using.html
http://android-er.blogspot.in/2010/10/schedule-repeating-alarm.html
I have had a similar problem and perhaps it applies to you (hard to tell since the code you supplied is pretty hard to navigate).
My issue was that applying multiple intents to the manager that evaluated as equal overrode the previous applications of that intent. See http://developer.android.com/reference/android/content/Intent.html#filterEquals(android.content.Intent) for what I mean by equivalence.
As an example, I had a schedule that used the URI domy://thing, with extras that varied over each intent (I need to fire the same action with different arguments each time). Extras don't count in equivalence, so my alarms were getting overwritten by each other.
To get around this, I stored a queue of my alarms in a separate file and when one fired, popped the next off the top and put that in the manager. Maybe that'll help you.
UPDATE:
No examples publicly visible, but try this (Trigger is a simple object containing a URI and a time it needs to be fired, scheduleDb is a class that extends SQLiteOpenHelper):
/**
* Pops the next trigger off the queue, adds it to the alarm manager, and
* stores it in the DB in case we need to cancel it later.
*/
private void scheduleNextTrigger() {
Log.d(TAG, "Popping next trigger off queue");
Optional<Trigger> nextTrigger = scheduleDb.getNextTrigger();
if (!nextTrigger.isPresent()) {
Log.d(TAG, "Trigger queue is empty");
return;
}
Trigger trigger = nextTrigger.get();
Log.d(TAG, "Scheduling new trigger " + trigger);
PendingIntent operation = createPendingIntent(trigger);
long timestamp = trigger.getTimestamp();
// Ensure the next item is in the future
if (timestamp > clock.currentTimeMillis()) {
Log.v(TAG, "Found valid trigger: " + trigger);
alarmManager.set(AlarmManager.RTC_WAKEUP, timestamp, operation);
}
scheduleDb.setScheduledTrigger(trigger);
}
private PendingIntent createPendingIntent(Trigger trigger) {
// AlarmManager allows only one instance of each URI, and seems to randomly
// delete bundled URI extras, so we'll encode the triggered URI and place it
// on a constant stem
Uri triggerUri = Uri.parse(TRIGGER_URI + "?" + Uri.encode(trigger.getUri()));
Intent triggerIntent = new Intent(Intent.ACTION_VIEW, triggerUri);
triggerIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
Log.d(TAG, "Created trigger intent " + triggerIntent);
PendingIntent operation = PendingIntent.getService(this, 0, triggerIntent, 0);
return operation;
}
Hope that helps
Related
I have splash screen which has count down time. I am assigning time value manually in my example time = 10000.
1)How can I assign value which I am getting from the service to the time variable.
2) How can I compare both the time and then assign the service time to the splash screen activity.
Activity
TextView text1, text2, text3;
// int time= 3600000*8;
int time = 10000;
public int Main_time ;
private UsbService usbService;
private EditText editText;
private MyHandler mHandler;
StringBuilder stringBuilder = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
mHandler = new MyHandler(splash_screen.this);
splashScreenUseAsyncTask();
int mUIFlag = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
getWindow().getDecorView().setSystemUiVisibility(mUIFlag);
text1 = (TextView) findViewById(R.id.tv_hour);
text2 = (TextView) findViewById(R.id.tv_minute);
text3 = (TextView) findViewById(R.id.tv_second);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
//usbService.sendATGetESN();
//usbService.sendATGetSTART();
//usbService.sendATGetPC();
//usbService.sendATGetSTOP();
usbService.sendATGetACC();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
try {
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
} catch (IllegalArgumentException ex) {
}
super.onPause();
}
#Override
public void onDestroy() {
try{
if(mUsbReceiver!=null)
unregisterReceiver(mUsbReceiver);
}catch(Exception e){}
super.onDestroy();
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
Intent serviceIntent = new Intent(this, splash_screen.class);
this.startService(serviceIntent);
startService(serviceIntent);
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, splash_screen.class);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
public class MyHandler extends Handler {
private final WeakReference<splash_screen> mActivity;
public MyHandler(splash_screen activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
StringBuilder main= mActivity.get().stringBuilder.append(data);
Main_time = Integer.parseInt(main.toString());
Log.d("REPLY", "Processing Accumulator List Command22"+Main_time);
break;
}
}
}
private void splashScreenUseAsyncTask() {
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
//for 5 Hours
CountDownTimer countDownTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long l) {
//long Days = l / (24 * 60 * 60 * 1000);
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
// tv_days.setText(String.format("%02d", Days));
text1.setText(String.format("%02d", Hours));
text2.setText(String.format("%02d", Minutes));
text3.setText(String.format("%02d", Seconds));
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
anim.setDuration(500);
anim.setRepeatCount(anim.INFINITE);
anim.setRepeatMode(Animation.REVERSE);
splashImageView.startAnimation(anim);
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
//imageAplha = 0;
//splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if (!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
private class RetrieveDateTask extends AsyncTask<String, String, String> {
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
currTread.sleep(time);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
}
}
Service
long sec = Integer.parseInt(value9);
long result = TimeUnit.SECONDS.toMillis(sec);
Log.d("REPLY","Milli"+ result);
String s = String.valueOf(result);
if (mHandler != null) {
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, s).sendToTarget();
}
new MyTask().execute();
private class MyTask extends AsyncTask<Void,Void,Long>{
#Override
protected Long doInBackground(Void... voids) {
//after downloading or after getting time from service that time for example 3000 we received
return 3000l;
}
#Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreen.this,MainActivity.class));
}
},timeinMs);
}
}
public class splash_screen extends AppCompatActivity {
TextView text1, text2, text3,display;
// int time= 3600000*8;
public String data;
private UsbService usbService;
private EditText editText;
private MyHandler mHandler;
public StringBuilder stringBuilder = new StringBuilder();
long time = 60000;
private long result ;
private long result2 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
mHandler = new MyHandler(splash_screen.this);
int mUIFlag = View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
getWindow().getDecorView().setSystemUiVisibility(mUIFlag);
text1 = (TextView) findViewById(R.id.tv_hour);
text2 = (TextView) findViewById(R.id.tv_minute);
text3 = (TextView) findViewById(R.id.tv_second);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
usbService.sendATGetACC();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
try {
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
} catch (IllegalArgumentException ex) {
}
super.onPause();
}
#Override
public void onDestroy() {
try{
if(mUsbReceiver!=null)
unregisterReceiver(mUsbReceiver);
}catch(Exception e){}
super.onDestroy();
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
Intent serviceIntent = new Intent(this, splash_screen.class);
this.startService(serviceIntent);
startService(serviceIntent);
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, splash_screen.class);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
public class MyHandler extends Handler {
private final WeakReference<splash_screen> mActivity;
public MyHandler(splash_screen activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
mActivity.get().time(data);
break;
}
}
}
public void time(String data) {
long sec = Integer.parseInt(data);
result = TimeUnit.SECONDS.toMillis(sec);
Log.d("REPLY", "Result value"+result);
result2 = time - result;
Log.d("REPLY", "Result2 value"+result2);
Log.d("REPLY", "Time value"+time);
if(result>=time) {
//usbService.sendATGetSTOP();
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
}
else{
if (result >= time) {
// usbService.sendATGetSTOP();
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
} else {
// Log.d("REPLY", "result2 value " + result2);
splashScreenUseAsyncTask();
} }
}
private void splashScreenUseAsyncTask() {
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
//for 5 Hours
CountDownTimer countDownTimer = new CountDownTimer(result2, 1000) {
#SuppressLint("DefaultLocale")
#Override
public void onTick(long l) {
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
// tv_days.setText(String.format("%02d", Days));
text1.setText(String.format("%02d", Hours));
text2.setText(String.format("%02d", Minutes));
text3.setText(String.format("%02d", Seconds));
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
anim.setDuration(500);
anim.setRepeatCount(anim.INFINITE);
anim.setRepeatMode(Animation.REVERSE);
splashImageView.startAnimation(anim);
}
#Override
public void onFinish() {
if (!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
#SuppressLint("StaticFieldLeak")
private class RetrieveDateTask extends AsyncTask<String, String, String> {
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
currTread.sleep(result2);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
//usbService.sendATGetSTOP();
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
usbService.sendATGetACC();
}
}
}
I have already been fetched data from instagram api. But i cannot reach that data to use it on my service. I have tried all methods that i know.
**Here is my main object: ** If my followers count is increases or decreases, notify, And check that for every 5 min.(I am still working on it. There are lots of misses yet.)
**Here is my main question: ** Do i really have to create a new parser to fetch data that i already have or what should i build?
If you have any sample or Articles for this case, that would be useful.
I heard about Csv file. Is that can be useful to import ?
PS: I learned java and android studio yet. I am pretty newbie.
public class MyService extends Service {
private InstagramApp mApp;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
#Nullable
#Override
public IBinder onBind(Intent intent) { return null; }
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
Timer myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String xx=userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
getnotification(xx);
}
}, 0, 5000);
return START_STICKY;
}
#Override
public void onDestroy() {
Toast.makeText(this,"Service Stopped", Toast.LENGTH_LONG).show();
}
public void getnotification(String xx){
//String foo=(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
// int fo= Integer.parseInt(foo);
// Toast.makeText(this, xx, Toast.LENGTH_LONG).show();
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent = new Intent(this, MainActivity.class);
PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
//PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_full_open_on_phone)
.setContentTitle("Notifications "+xx)
.setContentText("Followed by="+ userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY))
.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
/* Uri uri = Uri.parse("http://instagram.com/");
Intent likeIng = new Intent(Intent.ACTION_VIEW, uri);
likeIng.setPackage("com.instagram.android");
try {
startActivity(likeIng);
} catch (ActivityNotFoundException e) {
startActivity(new Intent(Intent.ACTION_VIEW,
Uri.parse("http://instagram.com/xxx")));
}*/
}
Here is my MainActivity
public class MainActivity extends AppCompatActivity implements OnClickListener {
private InstagramApp mApp;
private Button btnConnect;
private Button btnMe, btnOS,btnCS;
private HashMap<String, String> userInfoHashmap = new HashMap<String, String>();
ViewGroup myLayout;
private FirebaseAnalytics mFirebaseAnalytics;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(activity_main);
mFirebaseAnalytics = FirebaseAnalytics.getInstance(this);
myLayout = (ViewGroup)findViewById(R.id.myLayout);
mApp = new InstagramApp(this, ApplicationData.CLIENT_ID,
ApplicationData.CLIENT_SECRET, ApplicationData.CALLBACK_URL);
mApp.setListener(new OAuthAuthenticationListener() {
#Override
public void onSuccess() {
mApp.fetchUserName(handler);
}
#Override
public void onFail(String error) {
Toast.makeText(MainActivity.this, error, Toast.LENGTH_SHORT)
.show();
}
}
);
setWidgetReference();
bindEventHandlers();
if (mApp.hasAccessToken()) {
btnConnect.setText("Disconnect");
mApp.fetchUserName(handler);
}
}
private void setWidgetReference() {
btnConnect = (Button) findViewById(R.id.btnConnect);
btnMe = (Button) findViewById(R.id.btnMy);
btnOS = (Button) findViewById(R.id.btnOS);
btnCS = (Button) findViewById(R.id.btnCS);
}
private void bindEventHandlers() {
btnConnect.setOnClickListener(this);
btnMe.setOnClickListener(this);
btnOS.setOnClickListener(this);
btnCS.setOnClickListener(this);
}
String log="log";
#Override
public void onClick(View v) {
if (v == btnConnect) {
connectOrDisconnectUser();
} else {
String url = "";
if (v == btnMe) {
Log.v(log,"info show");
displayInfoDialogView();
//TODO Usersa string koy. Yeni hesap için.
// url = "https://api.instagram.com/v1/users/self"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/?access_token=" + mApp.getTOken(); imageView.setTag(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE));String imageName = (String) imageView.getTag();String axe=(String) userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE);image.setImageResource(axe);
}
else if (v == btnOS) {
Log.v(log,"Service started");
startService(new Intent(getBaseContext(),MyService.class));
// url = "https://api.instagram.com/v1/users/self/media/recent"+ userInfoHashmap.get(InstagramApp.TAG_ID)+ "/followed-by?access_token="+ mApp.getTOken();
}
//startActivity(new Intent(MainActivity.this, Relationship.class).putExtra("userInfo", url));
else if(v==btnCS){
Log.v(log,"Service closed");
stopService(new Intent(getBaseContext(),MyService.class));
}
}
}
public void goBack(View v){
setContentView(R.layout.activity_main);
}
private void connectOrDisconnectUser() {
if (mApp.hasAccessToken()) {
final AlertDialog.Builder builder = new AlertDialog.Builder(
MainActivity.this);
builder.setMessage("Disconnect from Instagram?")
.setCancelable(false)
.setPositiveButton("Yes",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
mApp.resetAccessToken();
btnConnect.setText("Connect");
}
})
.setNegativeButton("No",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
final AlertDialog alert = builder.create();
alert.show();
} else {
mApp.authorize();
}
}
private Handler handler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
if (msg.what == InstagramApp.WHAT_FINALIZE) {
userInfoHashmap = mApp.getUserInfo();
btnConnect.setText("Disconnect");
} else if (msg.what == InstagramApp.WHAT_ERROR) {
Toast.makeText(MainActivity.this, "Check your network.",
Toast.LENGTH_SHORT).show();
}
return false;
}
});
#Override
protected void onStart() {
super.onStart();
Toast.makeText(this, "Welcome to onStart", Toast.LENGTH_SHORT).show();
}
#Override
protected void onResume() {
super.onResume();
Toast.makeText(this, "Welcome to onResume", Toast.LENGTH_SHORT).show();
}
#Override
protected void onPause() {
super.onPause();
Toast.makeText(this, "It is onPause", Toast.LENGTH_SHORT).show();
}
#Override
protected void onStop() {
super.onStop();
Toast.makeText(this, "Stopped", Toast.LENGTH_SHORT).show();
}
#Override
protected void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Bye Bye :((", Toast.LENGTH_SHORT).show();
}
private void displayInfoDialogView() {
AlertDialog.Builder alertDialog = new AlertDialog.Builder(MainActivity.this);
alertDialog.setTitle(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.activity_follower_list, null);
alertDialog.setView(view);
TextView tvName = (TextView) view.findViewById(R.id.textView3);
TextView tvNoOfFollwers = (TextView) view.findViewById(R.id.textView2);
TextView tvNoOfFollowing = (TextView) view.findViewById(R.id.textView4);
//new ImageLoader(MainActivity.this).DisplayImage(userInfoHashmap.get(InstagramApp.TAG_PROFILE_PICTURE), ivProfile);
tvName.setText(userInfoHashmap.get(InstagramApp.TAG_USERNAME));
tvNoOfFollowing.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWS));
tvNoOfFollwers.setText(userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY));
alertDialog.create().show();
}
public void getnotification(){
String xx = userInfoHashmap.get(InstagramApp.TAG_FOLLOWED_BY);
/* Toast.makeText(this, xx, Toast.LENGTH_LONG)
.show();
*/
if (xx!=xx ) {
NotificationManager notificationmgr = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Intent intent = new Intent(this, resultpage.class);
// PendingIntent pintent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0);
// PendingIntent pintent = PendingIntent.getActivities(this,(int)System.currentTimeMillis(),intent, 0);
Notification notif = new Notification.Builder(this)
.setSmallIcon(R.drawable.common_google_signin_btn_text_dark_pressed)
.setContentTitle("Bu bir Bildirimdir!")
.setContentText("Bu bildirimin içeriğidir.")
//.setContentIntent(pintent)
.build();
notificationmgr.notify(0,notif);
}
}
}
The only solution that i found is the adding parser to your service to reach data from api. None of the the method can access to reach data from service to activity.
I added this class to reach api data on service.
public void lilParser() throws IOException, JSONException{
URL url = new URL(API_URL + "/users/" + mSession.getId()
+ "/?access_token=" + mAccessToken);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod("GET");
urlConnection.setDoInput(true);
urlConnection.connect();
String response = Utils.streamToString(urlConnection
.getInputStream());
System.out.println(response);
JSONObject jsonObj = (JSONObject) new JSONTokener(response).nextValue();
JSONObject data_obj = jsonObj.getJSONObject("data");
JSONObject counts_obj = data_obj.getJSONObject("counts");
String name = jsonObj.getJSONObject("data").getString("full_name");
String bio =jsonObj.getJSONObject("data").getString("bio");
String counts=jsonObj.getJSONObject("data").getString("counts");
userInfoHashmap.put(TAG_FOLLOWED_BY,counts_obj.getString(TAG_FOLLOWED_BY));
Log.i(TAG,"followedby=>[" + counts + "]");
}
And, Here is my onCreate. You can check The data if it is changed or not.
#Override
public void onCreate() {
Toast.makeText(this,"Service Started", Toast.LENGTH_LONG).show();
myTimer = new Timer();
myTimer.schedule(new TimerTask() {
#Override
public void run() {
String fo = userInfoHashmap.get(TAG_FOLLOWED_BY);
try {
lilParser();
}
catch (IOException e) {e.printStackTrace();}
catch (JSONException e) {e.printStackTrace();}
if(new String(userInfoHashmap.get(TAG_FOLLOWED_BY)).equals(fo)==true){}
else {
getnotification();
}
}
}, 0, 30000);
}
PS: I published my code, that may help someone else. I am still newbie.
I am running into an issue with the implementation of the Dale Lane MQTT solution.
I cannot seem to figure out how to retrieve the published message from the MQTT Client I am using.
I am not sure if I am utilizing the the onReceive() method incorrectly, but for now all I would like to do is log the broadcasted messages.
http://dalelane.co.uk/blog/?p=1599
The service I have implemented is exactly as listed here, I have no errors.
public class MQTTNotifier extends Activity implements OnClickListener {
String preferenceBrokerHost, preferenceBrokerTopic;
private StatusUpdateReceiver statusUpdateIntentReceiver;
private MQTTMessageReceiver messageIntentReceiver;
private EditText etBroker, etTopic;
Button btnSubscribe, btnStopService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mqttnotifier);
initValues();
// startService();
}
private void initValues() {
btnSubscribe = (Button) findViewById(R.id.btnSubscribe);
btnSubscribe.setOnClickListener(this);
btnStopService = (Button) findViewById(R.id.btnStopService);
btnStopService.setOnClickListener(this);
// if statement to see if sharedpreferences exist, if so reopen recievers
/*
* statusUpdateIntentReceiver = new StatusUpdateReceiver(); IntentFilter intentSFilter = new
* IntentFilter(MQTTService.MQTT_STATUS_INTENT); registerReceiver(statusUpdateIntentReceiver,
* intentSFilter);
*
* messageIntentReceiver = new MQTTMessageReceiver(); IntentFilter intentCFilter = new
* IntentFilter(MQTTService.MQTT_MSG_RECEIVED_INTENT); registerReceiver(messageIntentReceiver,
* intentCFilter);
*/
}
public class StatusUpdateReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle notificationData = intent.getExtras();
String newStatus = notificationData.getString(MQTTService.MQTT_STATUS_MSG);
}
}
public class MQTTMessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle notificationData = intent.getExtras();
String newTopic = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_TOPIC);
String newData = notificationData.getString(MQTTService.MQTT_MSG_RECEIVED_MSG);
Log.e("NEW TOPIC", newTopic);
Log.e("NEW DATA", newData);
}
}
#Override
protected void onDestroy() {
unregisterReceiver(statusUpdateIntentReceiver);
unregisterReceiver(messageIntentReceiver);
}
private void startService() {
Intent svc = new Intent(this, MQTTService.class);
startService(svc);
}
private void stopService() {
Intent svc = new Intent(this, MQTTService.class);
stopService(svc);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if (hasFocus) {
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mNotificationManager.cancel(MQTTService.MQTT_NOTIFICATION_UPDATE);
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.btnSubscribe:
etBroker = (EditText) findViewById(R.id.etBroker);
etTopic = (EditText) findViewById(R.id.etTopic);
preferenceBrokerHost = etBroker.getText().toString().trim();
preferenceBrokerTopic = etBroker.getText().toString().trim();
createSharedPreferences(preferenceBrokerHost, preferenceBrokerTopic);
establishRecievers();
startService();
break;
case R.id.btnStopService:
stopService();
}
}
private void createSharedPreferences(String broker, String topic) {
SharedPreferences settings = getSharedPreferences(MQTTService.APP_ID, 0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("broker", broker);
editor.putString("topic", topic);
editor.commit();
}
private void establishRecievers() {
statusUpdateIntentReceiver = new StatusUpdateReceiver();
IntentFilter intentSFilter = new IntentFilter(MQTTService.MQTT_STATUS_INTENT);
registerReceiver(statusUpdateIntentReceiver, intentSFilter);
messageIntentReceiver = new MQTTMessageReceiver();
IntentFilter intentCFilter = new IntentFilter(MQTTService.MQTT_MSG_RECEIVED_INTENT);
registerReceiver(messageIntentReceiver, intentCFilter);
}
}
It turns out that the issue was in regards to a simple mistake that was in regards to this line.
preferenceBrokerTopic = etBroker.getText().toString().trim();
I corrected the issue and now it corrects properly because it was not subscribing to the correct topic.
preferenceBrokerTopic = etTopic.getText().toString().trim();
From what I can tell, the Uri.parse in my code is causing my MediaPlayer to fail on audio files with special characters in the filename, like "#" and others. I cannot figure out how to resolve this issue. I want to be able to use special characters in my filenames. Here is the code that I think is causing the issue:
public void playAudio(int media) {
try {
switch (media) {
case LOCAL_AUDIO:
/**
* TODO: Set the path variable to a local audio file path.
*/
if (path == "") {
// Tell the user to provide an audio file URL.
Toast
.makeText(
MediaPlayerDemo_Audio.mp,
"Please edit MediaPlayer_Audio Activity, "
+ "and set the path variable to your audio file path."
+ " Your audio file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setLooping(sound_loop);
mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path));
mMediaPlayer.prepare();
resetTimer();
startTimer();
mMediaPlayer.start();
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
break;
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide
* its resid in MediaPlayer.create() method.
*/
// mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
//mMediaPlayer.start();
}
//tx.setText(path);
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
}
I am using MediaPlayerDemo_Audio.java to play sounds. As you can see from the above code, the mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path)); is calling the code to retrieve the file and media player, I think. I am not too skilled with android code yet. Here is the code for MediaPlayerDemo_Audio.java:
public class MediaPlayerDemo_Audio extends Activity {
public static String path;
private String fname;
private static Intent PlayerIntent;
public static String STOPED = "stoped";
public static String PLAY_START = "play_start";
public static String PAUSED = "paused";
public static String UPDATE_SEEKBAR = "update_seekbar";
public static boolean is_loop = false;
private static final int LOCAL_AUDIO=0;
private Button play_pause, stop;
private SeekBar seek_bar;
public static MediaPlayerDemo_Audio mp;
private AudioPlayerService mPlayerService;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.media_player_layout);
//getWindow().setTitle("SoundPlayer");
//getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
// android.R.drawable.ic_media_play);
play_pause = (Button)findViewById(R.id.play_pause);
play_pause.setOnClickListener(play_pause_clk);
stop = (Button)findViewById(R.id.stop);
stop.setOnClickListener(stop_clk);
seek_bar = (SeekBar)findViewById(R.id.seekBar1);
seek_bar.setMax(100);
seek_bar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
if (mPlayerService!=null) {
int seek_pos = (int) ((double)mPlayerService.getduration()*seekBar.getProgress()/100);
mPlayerService.seek(seek_pos);
}
}
public void onStartTrackingTouch(SeekBar seekBar) {
}
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
}
});
play_pause.setText("Pause");
stop.setText("Stop");
//int idx = path.lastIndexOf("/");
//fname = path.substring(idx+1);
//tx.setText(path);
IntentFilter filter = new IntentFilter();
filter.addAction(STOPED);
filter.addAction(PAUSED);
filter.addAction(PLAY_START);
filter.addAction(UPDATE_SEEKBAR);
registerReceiver(mPlayerReceiver, filter);
PlayerIntent = new Intent(MediaPlayerDemo_Audio.this, AudioPlayerService.class);
if (AudioPlayerService.path=="") AudioPlayerService.path=path;
AudioPlayerService.sound_loop = is_loop;
startService(PlayerIntent);
bindService(PlayerIntent, mConnection, 0);
if (mPlayerService!=null && mPlayerService.is_pause==true) play_pause.setText("Play");
mp = MediaPlayerDemo_Audio.this;
}
private BroadcastReceiver mPlayerReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String act = intent.getAction();
if (act.equalsIgnoreCase(UPDATE_SEEKBAR)){
int val = intent.getIntExtra("seek_pos", 0);
seek_bar.setProgress(val);
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime((long) (intent.getLongExtra("time", 0)/16.666)));
//tx.setText(fname);
}
else if (act.equalsIgnoreCase(STOPED)) {
play_pause.setText("Play");
seek_bar.setProgress(0);
stopService(PlayerIntent);
unbindService(mConnection);
mPlayerService = null;
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime(0));
}
else if (act.equalsIgnoreCase(PLAY_START)){
play_pause.setText("Pause");
}
else if (act.equalsIgnoreCase(PAUSED)){
play_pause.setText("Play");
}
}
};
private ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
mPlayerService = ((AudioPlayerService.LocalBinder)arg1).getService();
if (mPlayerService.is_pause==true) {
play_pause.setText("Play");
seek_bar.setProgress(mPlayerService.seek_pos);
}
if (mPlayerService.mTime!=0) {
TextView counter = (TextView) findViewById(R.id.time_view);
counter.setText(DateUtils.formatElapsedTime((long) (mPlayerService.mTime/16.666)));
}
if (path.equalsIgnoreCase(AudioPlayerService.path)==false){
AudioPlayerService.path = path;
mPlayerService.restart();
}
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
mPlayerService = null;
}
};
private OnClickListener play_pause_clk = new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mPlayerService!=null)
mPlayerService.play_pause();
else{
AudioPlayerService.path=path;
startService(PlayerIntent);
bindService(PlayerIntent, mConnection, 0);
}
}
};
private OnClickListener stop_clk = new OnClickListener() {
#Override
public void onClick(View arg0) {
if (mPlayerService==null) return;
mPlayerService.Stop();
}
};
#Override
protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
}
}
How can I fix this issue so files can be parsed with special characters and played correctly in MediaPlayer? Am I missing something?
Maybe it would help to show the entire code for my AudioPlayerService:
public class AudioPlayerService extends Service {
public MediaPlayer mMediaPlayer;
protected long mStart;
public long mTime;
public int seek_pos=0;
public static boolean sound_loop = false;
public boolean is_play, is_pause;
public static String path="";
private static final int LOCAL_AUDIO=0;
private static final int RESOURCES_AUDIO=1;
private int not_icon;
private Notification notification;
private NotificationManager nm;
private PendingIntent pendingIntent;
private Intent intent;
#SuppressWarnings("deprecation")
#Override
public void onCreate() {
playAudio(LOCAL_AUDIO);
mTime=0;
is_play = true;
is_pause = false;
CharSequence ticker = "Touch to return to app";
long now = System.currentTimeMillis();
not_icon = R.drawable.play_notification;
notification = new Notification(not_icon, ticker, now);
nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Context context = getApplicationContext();
intent = new Intent(this, MediaPlayerDemo_Audio.class);
pendingIntent = PendingIntent.getActivity(context, 0,intent, 0);
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//INCOMING call
//do all necessary action to pause the audio
if (is_play==true && is_pause==false){
play_pause();
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not IN CALL
//do anything if the phone-state is idle
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
//do all necessary action to pause the audio
//do something here
if (is_play==true && is_pause==false){
play_pause();
}
}
super.onCallStateChanged(state, incomingNumber);
}
};//end PhoneStateListener
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
OnAudioFocusChangeListener myaudiochangelistener = new OnAudioFocusChangeListener(){
#Override
public void onAudioFocusChange(int arg0) {
//if (arg0 ==AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK){
if (is_play==true && is_pause==false){
play_pause();
}
//}
}
};
AudioManager amr = (AudioManager)getSystemService(AUDIO_SERVICE);
amr.requestAudioFocus(myaudiochangelistener, AudioManager.STREAM_MUSIC, AudioManager.AUDIOFOCUS_GAIN_TRANSIENT);
}
#SuppressWarnings("deprecation")
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Context context = getApplicationContext();
String title = "VoiceRecorder App";
CharSequence message = "Playing..";
notification.setLatestEventInfo(context, title, message,pendingIntent);
nm.notify(101, notification);
return START_STICKY;
}
public class LocalBinder extends Binder {
AudioPlayerService getService() {
return AudioPlayerService.this;
}
}
public void restart(){
mMediaPlayer.stop();
playAudio(LOCAL_AUDIO);
mTime=0;
is_play = true;
is_pause = false;
}
#Override
public IBinder onBind(Intent arg0) {
return mBinder;
}
private final IBinder mBinder = new LocalBinder();
public void Stop()
{
mMediaPlayer.stop();
Intent intent1 = new Intent(MediaPlayerDemo_Audio.STOPED);
sendBroadcast(intent1);
resetTimer();
is_play=false;
is_pause=false;
}
public void play_pause()
{
if (is_play==false){
try {
mMediaPlayer.start();
startTimer();
is_play=true;
is_pause = false;
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
}
else{
mMediaPlayer.pause();
stopTimer();
Intent intent1 = new Intent(MediaPlayerDemo_Audio.PAUSED);
sendBroadcast(intent1);
is_play = false;
is_pause = true;
}
}
public int getduration()
{
return mMediaPlayer.getDuration();
}
public void seek(int seek_pos)
{
mMediaPlayer.seekTo(seek_pos);
mTime = seek_pos;
}
public void playAudio(int media) {
try {
switch (media) {
case LOCAL_AUDIO:
/**
* TODO: Set the path variable to a local audio file path.
*/
if (path == "") {
// Tell the user to provide an audio file URL.
Toast
.makeText(
MediaPlayerDemo_Audio.mp,
"Please edit MediaPlayer_Audio Activity, "
+ "and set the path variable to your audio file path."
+ " Your audio file must be stored on sdcard.",
Toast.LENGTH_LONG).show();
}
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setLooping(sound_loop);
mMediaPlayer.setDataSource(MediaPlayerDemo_Audio.mp, Uri.parse(path));
mMediaPlayer.prepare();
resetTimer();
startTimer();
mMediaPlayer.start();
Intent intent = new Intent(MediaPlayerDemo_Audio.PLAY_START);
sendBroadcast(intent);
break;
case RESOURCES_AUDIO:
/**
* TODO: Upload a audio file to res/raw folder and provide
* its resid in MediaPlayer.create() method.
*/
// mMediaPlayer = MediaPlayer.create(this, R.raw.test_cbr);
//mMediaPlayer.start();
}
//tx.setText(path);
} catch (Exception e) {
//Log.e(TAG, "error: " + e.getMessage(), e);
}
}
#SuppressLint("HandlerLeak")
private Handler mHandler = new Handler() {
public void handleMessage(Message msg) {
long curTime = System.currentTimeMillis();
mTime += curTime-mStart;
mStart = curTime;
int pos = (int) ((double)mMediaPlayer.getCurrentPosition()*100/mMediaPlayer.getDuration());
seek_pos = pos;
Intent intent1 = new Intent(MediaPlayerDemo_Audio.UPDATE_SEEKBAR);
if (mMediaPlayer.isLooping()) intent1.putExtra("time", (long)mMediaPlayer.getCurrentPosition());
else intent1.putExtra("time", mTime);
intent1.putExtra("seek_pos", pos);
sendBroadcast(intent1);
if (mMediaPlayer.isPlaying()==false && mMediaPlayer.isLooping()==false){
mMediaPlayer.stop();
resetTimer();
Intent intent2 = new Intent(MediaPlayerDemo_Audio.STOPED);
sendBroadcast(intent2);
is_play=false;
}
if (mTime > 0) mHandler.sendEmptyMessageDelayed(0, 10);
};
};
private void startTimer() {
mStart = System.currentTimeMillis();
mHandler.removeMessages(0);
mHandler.sendEmptyMessage(0);
}
private void stopTimer() {
mHandler.removeMessages(0);
}
private void resetTimer() {
stopTimer();
mTime = 0;
}
#Override
public void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mMediaPlayer != null) {
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
nm.cancel(101);
}
}
For local files, do not use Uri.parse(). Use Uri.fromFile(), passing in a File object pointing to the file in question. This should properly escape special characters like #.
*I am new in android any help please help me and thanks in advance.
I want that bluetooth is always connected in app while switching from one activity to another. so I am making background service . There are two classes first class shows the list of paired device and second class is used to run the bluetooth as background service . There is no error Everything is fine but when I switch the activity Bluetooth is disconnected and also it didn't show the status changed. Ask me If you need any additional information *
This is my first class Homescreen class
public class Homescreen extends Activity {
public static Homescreen home;
private Button mBtnSearch;
private Button mBtnConnect;
private ListView mLstDevices;
private BluetoothAdapter mBTAdapter;
private static final int BT_ENABLE_REQUEST = 10; // This is the code we use for BT Enable
private static final int SETTINGS = 20;
private UUID mDeviceUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // Standard SPP UUID
// (http://developer.android.com/reference/android/bluetooth/BluetoothDevice.html#createInsecureRfcommSocketToServiceRecord%28java.util.UUID%29)
private int mBufferSize = 50000; //Default
public static final String DEVICE_EXTRA = "com.blueserial.SOCKET";
public static final String DEVICE_UUID = "com.blueserial.uuid";
private static final String DEVICE_LIST = "com.blueserial.devicelist";
private static final String DEVICE_LIST_SELECTED = "com.blueserial.devicelistselected";
public static final String BUFFER_SIZE = "com.blueserial.buffersize";
private static final String TAG = "BlueTest5-Homescreen";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_homescreen);
home=this;
ActivityHelper.initialize(this); //This is to ensure that the rotation persists across activities and not just this one
Log.d(TAG, "Created");
mBtnSearch = (Button) findViewById(R.id.btnSearch);
mBtnConnect = (Button) findViewById(R.id.btnConnect);
mLstDevices = (ListView) findViewById(R.id.lstDevices);
/*
*Check if there is a savedInstanceState. If yes, that means the onCreate was probably triggered by a configuration change
*like screen rotate etc. If that's the case then populate all the views that are necessary here
*/
if (savedInstanceState != null) {
ArrayList<BluetoothDevice> list = savedInstanceState.getParcelableArrayList(DEVICE_LIST);
if(list!=null){
initList(list);
MyAdapter adapter = (MyAdapter)mLstDevices.getAdapter();
int selectedIndex = savedInstanceState.getInt(DEVICE_LIST_SELECTED);
if(selectedIndex != -1){
adapter.setSelectedIndex(selectedIndex);
mBtnConnect.setEnabled(true);
}
} else {
initList(new ArrayList<BluetoothDevice>());
}
} else {
initList(new ArrayList<BluetoothDevice>());
}
mBtnSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBTAdapter == null) {
Toast.makeText(getApplicationContext(), "Bluetooth not found", Toast.LENGTH_SHORT).show();
} else if (!mBTAdapter.isEnabled()) {
Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBT, BT_ENABLE_REQUEST);
} else {
new SearchDevices().execute();
}
}
});
mBtnConnect.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent intt=new Intent(Homescreen.this,BluetoothService.class);
//bindService( intt, null, Context.BIND_AUTO_CREATE);
BluetoothDevice device = ((MyAdapter) (mLstDevices.getAdapter())).getSelectedItem();
intt.putExtra(DEVICE_EXTRA, device);
intt.putExtra(DEVICE_UUID, mDeviceUUID.toString());
intt.putExtra(BUFFER_SIZE, mBufferSize);
startService(intt);
// Toast.makeText(Homescreen.this, "Device Connected", Toast.LENGTH_LONG).show();
// BluetoothDevice device = ((MyAdapter) (mLstDevices.getAdapter())).getSelectedItem();
// Intent intent = new Intent(getApplicationContext(), MainBluetooth.class);
// intent.putExtra(DEVICE_EXTRA, device);
// intent.putExtra(DEVICE_UUID, mDeviceUUID.toString());
// intent.putExtra(BUFFER_SIZE, mBufferSize);
// startActivity(intent);
}
});
}
/**
* Called when the screen rotates. If this isn't handled, data already generated is no longer available
*/
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
MyAdapter adapter = (MyAdapter) (mLstDevices.getAdapter());
ArrayList<BluetoothDevice> list = (ArrayList<BluetoothDevice>) adapter.getEntireList();
if (list != null) {
outState.putParcelableArrayList(DEVICE_LIST, list);
int selectedIndex = adapter.selectedIndex;
outState.putInt(DEVICE_LIST_SELECTED, selectedIndex);
}
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
}
#Override
protected void onStop() {
// TODO Auto-generated method stub
super.onStop();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case BT_ENABLE_REQUEST:
if (resultCode == RESULT_OK) {
msg("Bluetooth Enabled successfully");
new SearchDevices().execute();
} else {
msg("Bluetooth couldn't be enabled");
}
break;
case SETTINGS: //If the settings have been updated
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
String uuid = prefs.getString("prefUuid", "Null");
mDeviceUUID = UUID.fromString(uuid);
Log.d(TAG, "UUID: " + uuid);
String bufSize = prefs.getString("prefTextBuffer", "Null");
mBufferSize = Integer.parseInt(bufSize);
String orientation = prefs.getString("prefOrientation", "Null");
Log.d(TAG, "Orientation: " + orientation);
if (orientation.equals("Landscape")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
} else if (orientation.equals("Portrait")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
} else if (orientation.equals("Auto")) {
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_FULL_SENSOR);
}
break;
default:
break;
}
super.onActivityResult(requestCode, resultCode, data);
}
/**
* Quick way to call the Toast
* #param str
*/
private void msg(String str) {
Toast.makeText(getApplicationContext(), str, Toast.LENGTH_SHORT).show();
}
/**
* Initialize the List adapter
* #param objects
*/
private void initList(List<BluetoothDevice> objects) {
final MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.list_item, R.id.lstContent, objects);
mLstDevices.setAdapter(adapter);
mLstDevices.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
adapter.setSelectedIndex(position);
mBtnConnect.setEnabled(true);
}
});
}
/**
* Searches for paired devices. Doesn't do a scan! Only devices which are paired through Settings->Bluetooth
* will show up with this. I didn't see any need to re-build the wheel over here
* #author ryder
*
*/
private class SearchDevices extends AsyncTask<Void, Void, List<BluetoothDevice>> {
#Override
protected List<BluetoothDevice> doInBackground(Void... params) {
Set<BluetoothDevice> pairedDevices = mBTAdapter.getBondedDevices();
List<BluetoothDevice> listDevices = new ArrayList<BluetoothDevice>();
for (BluetoothDevice device : pairedDevices) {
listDevices.add(device);
}
return listDevices;
}
#Override
protected void onPostExecute(List<BluetoothDevice> listDevices) {
super.onPostExecute(listDevices);
if (listDevices.size() > 0) {
MyAdapter adapter = (MyAdapter) mLstDevices.getAdapter();
adapter.replaceItems(listDevices);
} else {
msg("No paired devices found, please pair your serial BT device and try again");
}
}
}
/**
* Custom adapter to show the current devices in the list. This is a bit of an overkill for this
* project, but I figured it would be good learning
* Most of the code is lifted from somewhere but I can't find the link anymore
* #author ryder
*
*/
private class MyAdapter extends ArrayAdapter<BluetoothDevice> {
private int selectedIndex;
private Context context;
private int selectedColor = Color.parseColor("#abcdef");
private List<BluetoothDevice> myList;
public MyAdapter(Context ctx, int resource, int textViewResourceId, List<BluetoothDevice> objects) {
super(ctx, resource, textViewResourceId, objects);
context = ctx;
myList = objects;
selectedIndex = -1;
}
public void setSelectedIndex(int position) {
selectedIndex = position;
notifyDataSetChanged();
}
public BluetoothDevice getSelectedItem() {
return myList.get(selectedIndex);
}
#Override
public int getCount() {
return myList.size();
}
#Override
public BluetoothDevice getItem(int position) {
return myList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
private class ViewHolder {
TextView tv;
}
public void replaceItems(List<BluetoothDevice> list) {
myList = list;
notifyDataSetChanged();
}
public List<BluetoothDevice> getEntireList() {
return myList;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
ViewHolder holder;
if (convertView == null) {
vi = LayoutInflater.from(context).inflate(R.layout.list_item, null);
holder = new ViewHolder();
holder.tv = (TextView) vi.findViewById(R.id.lstContent);
vi.setTag(holder);
} else {
holder = (ViewHolder) vi.getTag();
}
if (selectedIndex != -1 && position == selectedIndex) {
holder.tv.setBackgroundColor(selectedColor);
} else {
holder.tv.setBackgroundColor(Color.WHITE);
}
BluetoothDevice device = myList.get(position);
holder.tv.setText(device.getName() + "\n " + device.getAddress());
return vi;
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.homescreen, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
Intent intent = new Intent(Homescreen.this, PreferencesActivity.class);
startActivityForResult(intent, SETTINGS);
break;
}
return super.onOptionsItemSelected(item);
}
}
This is my second class BluetoothService Class
public class BluetoothService extends Service {
public static BluetoothService service;
private boolean mConnectSuccessful = true;
private static boolean isRunning = false;
private static final String TAG = "BlueTest5-MainActivity";
private int mMaxChars = 50000;//Default
//private UUID mDeviceUUID=UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
private UUID mDeviceUUID;
private BluetoothSocket mBTSocket;
private boolean mIsBluetoothConnected = false;
//private BluetoothDevice mDevice=Homescreen.home.device;
private BluetoothDevice mDevice;
#Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
// Intent intt = getIntent();
// Bundle b = intt.getExtras();
// mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
// mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
// mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
// super.onStart(intent, startId);
}
#Override
public void onCreate() {
service=this;
IntentFilter filter1 = new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED);
IntentFilter filter2 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED);
IntentFilter filter3 = new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED);
this.registerReceiver(mReceiver, filter1);
this.registerReceiver(mReceiver, filter2);
this.registerReceiver(mReceiver, filter3);
// TODO Auto-generated method stub
// Intent intent = getIntent();
// Bundle b = intent.getExtras();
// mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
// mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
// mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
super.onCreate();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Bundle b = intent.getExtras();
mDevice = b.getParcelable(Homescreen.DEVICE_EXTRA);
mDeviceUUID = UUID.fromString(b.getString(Homescreen.DEVICE_UUID));
mMaxChars = b.getInt(Homescreen.BUFFER_SIZE);
Log.i("mDeviceUUID", ""+mDeviceUUID);
Log.d("mDevice",""+mDevice );
new ConnectBT().execute();
return START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
public boolean isRunning() {
return isRunning;
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
// Unregister broadcast listeners
this.unregisterReceiver(mReceiver);
super.onDestroy();
}
class ConnectBT extends AsyncTask<Void, Void, Void> {
//ProgressDialog progressDialog;
#Override
protected void onPreExecute() {
// http://stackoverflow.com/a/11130220/1287554
// progressDialog = ProgressDialog.show(BluetoothService.this, "Hold on", "Connecting");
Log.d("check check check", "check1");
}
#Override
protected Void doInBackground(Void... devices) {
Log.d("check check check", "check2");
try {
Log.e("check check check", "check3");
if (mBTSocket == null || !mIsBluetoothConnected) {
Log.e("UUID", ""+mDeviceUUID);
Log.e("mDevice", ""+mDevice);
mBTSocket = mDevice.createInsecureRfcommSocketToServiceRecord(mDeviceUUID);
Log.d("check check check", "check4");
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
mBTSocket.connect();
Log.d("check check check", "check5");
// Toast.makeText(BluetoothService.this, "background service start", Toast.LENGTH_LONG).show();
}
} catch (IOException e) {
// Unable to connect to device
e.printStackTrace();
mConnectSuccessful = false;
}
return null;
}
#Override
protected void onPostExecute(Void result) {
super.onPostExecute(result);
if (!mConnectSuccessful) {
Toast.makeText(BluetoothService.this, "Could not connect to device. Is it a Serial device? Also check if the UUID is correct in the settings", Toast.LENGTH_LONG).show();
Log.e("Device Status in service", "Disconnected");
} else {
Toast.makeText(BluetoothService.this, "Connected to device", Toast.LENGTH_SHORT).show();
Log.e("Device Status in service", "Device Connected");
mIsBluetoothConnected = true;
// Kick off input reader
}
//progressDialog.dismiss();
}
}
//The BroadcastReceiver that listens for bluetooth broadcasts
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
//Do something if connected
Toast.makeText(getApplicationContext(), "BT Connected", Toast.LENGTH_SHORT).show();
Log.e("Bluetooth device connected","BT Connected");
}
else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//Do something if disconnected
Toast.makeText(getApplicationContext(), "BT Disconnected", Toast.LENGTH_SHORT).show();
Log.e("Bluetooth device disconnected","BT Disconnected");
}
//else if...
}
};
}
Android's AsyncTask class will help you. Do the bluetooth discovery task in the doInBackground() method of AsyncTask.You can Toast a message a after the task in the onPostExecute() method. Here is sample code snippet to demonstrate the use of AsyncTask