I have implemented a Demo Application for JobScheduler. Below are my Code for MainActivity and JobScheduler Service. OnStopJob is not called even when i press Cancel all task button to cancel All Scheduled Jobs. I am unable to understand it why it is happening. I have also tried returning true from onStopJob.
MainActivity.java
package com.example.jobschedulerdemo;
import android.app.Activity;
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity {
private JobScheduler mJobScheduler;
private Button mScheduleJobButton;
private Button mCancelAllJobsButton;
private static final String TAG = "MainActivity";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mScheduleJobButton = (Button) findViewById( R.id.schedule_job );
mCancelAllJobsButton = (Button) findViewById( R.id.cancel_all );
mJobScheduler = (JobScheduler) getSystemService(Context.JOB_SCHEDULER_SERVICE);
mScheduleJobButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
JobInfo.Builder jobBuilder = new JobInfo.Builder(1, new ComponentName(getPackageName(), TestJobService.class.getName()));
jobBuilder.setPeriodic(3000);
jobBuilder.setRequiresCharging(true);
if(mJobScheduler.schedule(jobBuilder.build()) <= 0){
Log.i(TAG, "Error in scheduling job");
}
}
});
mCancelAllJobsButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mJobScheduler.cancelAll();
}
});
}
}
TestJobService.java
package com.example.jobschedulerdemo;
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.Toast;
public class TestJobService extends JobService{
private static final String TAG = "TestJobService";
private Handler mHandler = new Handler(new Handler.Callback() {
#Override
public boolean handleMessage(Message msg) {
Toast.makeText(TestJobService.this, "Task Running", Toast.LENGTH_SHORT).show();
jobFinished((JobParameters)msg.obj, false);
return false;
}
});
#Override
public boolean onStartJob(JobParameters params) {
Log.i(TAG, "onJobStarted : Job Id = " + params.getJobId());
mHandler.sendMessage(Message.obtain(mHandler, 1, params));
return true;
}
#Override
public boolean onStopJob(JobParameters params) {
Log.i(TAG, "onStopJob : Job Id = " + params.getJobId());
mHandler.removeMessages(1);
return false;
}
}
onStopJob(JobParameters params) is used by the system to cancel pending tasks when a cancel request is received.
You can easily reproduce it by running a Job and cancel it BEFORE it ends (before calling jobFinished(...)). It's suppose you put there the required logic to cancel your background task.
3 seconds maybe is too short to make the test. Try with more time.
Related
How I can listen when music from other apps are Playing and when not?
My code was:
if (audioManager.isMusicActive()) {
musicontrolIcon.setImageResource(R.drawable.ic_pause_circle);
musicontrolIcon.setOnClickListener(pauseMusic);
} else {
musicontrolIcon.setImageResource(R.drawable.ic_play_circle);
musicontrolIcon.setOnClickListener(playMusic);
}
But it checks only once.
Try Using JobScheduler, Schedule a job that checks for isMusicActive() every 5 seconds(Or As Per Your Requirement).
Here's how you can do it:-
import android.app.job.JobParameters;
import android.app.job.JobService;
import android.util.Log;
public class JobSchedulerService extends JobService {
private static final String TAG = "JobSchedulerService";
#Override
public boolean onStartJob(JobParameters params) {
Log.i(TAG, "onStartJob:");
return false;
}
#Override
public boolean onStopJob(JobParameters params) {
Log.i(TAG, "onStopJob:");
return false;
}
}
AndroidManifest
<service android:name=".JobSchedulerService"
android:permission="android.permission.BIND_JOB_SERVICE"
android:exported="true"/>
Create Scheduler Objects
import android.app.job.JobInfo;
import android.app.job.JobScheduler;
import android.content.ComponentName;
import android.content.Context;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
JobScheduler mJobScheduler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.i(TAG, "onCreate: ");
mJobScheduler = (JobScheduler)
getSystemService(Context.JOB_SCHEDULER_SERVICE);
JobInfo.Builder builder = new JobInfo.Builder(1,
new ComponentName(getPackageName(),
JobSchedulerService.class.getName()));
builder.setPeriodic(3000);
builder.setRequiredNetworkType(JobInfo.NETWORK_TYPE_ANY);
if (mJobScheduler.schedule(builder.build()) <= 0) {
Log.e(TAG, "onCreate: Some error while scheduling the job");
}
}
}
hello i am new in signalR i am making one chating app with using signalR i take reference from SignalR integration in android studio here with the help of this i able to send the messages to the chat group but i am not able to receive messages i read lots of Q&A here but i am not able to solve this problem i paste here my code and please anyone tell me how do i receive message from the server.following is my code.
Activity main
package myapp.chatapp;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.res.Configuration;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.Toast;
import com.google.gson.JsonElement;
import java.util.ArrayList;
import microsoft.aspnet.signalr.client.MessageReceivedHandler;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.LongPollingTransport;
public class MainActivity extends AppCompatActivity implements SignalRService.Something {
private StringBuilder mLog;
private ListView mTestCaseList;
private Spinner mTestGroupSpinner;
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private final Context mContext = this;
private SignalRService mService;
private SignalRService mMessageResive;
private boolean mBound = false;
ListView list_item;
EditText editText;
ArrayList<String> listItems;
ArrayAdapter<String> adapter;
ClientTransport transport;
private Handler mHandler; // to display Toast message
private Thread t;
#Override
public void onConfigurationChanged(Configuration newConfig) {
// don't restart the activity. Just process the configuration change
super.onConfigurationChanged(newConfig);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent intent = new Intent();
intent.setClass(mContext, SignalRService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
editText = (EditText)findViewById(R.id.edit_message);
ImageButton btn = (ImageButton)findViewById(R.id.btn);
list_item = (ListView)findViewById(R.id.list_item);
listItems = new ArrayList<String>();
/*listItems.add("First Item - added on Activity Create");*/
/* adapter = new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, listItems);*/
adapter = new ArrayAdapter<String>(mContext,R.layout.custom_list, R.id.textView,listItems);
list_item.setAdapter(adapter);
final Handler handler = new Handler();
handler.postDelayed( new Runnable() {
#Override
public void run() {
adapter.notifyDataSetChanged();
handler.postDelayed( this, 1000 );
}
}, 1000 );
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listItems.add(editText.getText().toString());
adapter.notifyDataSetChanged();
sendMessage(view);
}
});
}
#Override
protected void onStop() {
// Unbind from the service
if (mBound) {
unbindService(mConnection);
mBound = false;
}
super.onStop();
}
public void sendMessage(View view) {
if (mBound) {
String message = editText.getText().toString();
String email = "kn#yopmail.com";
String name = "Kunal From Android";
String group ="1";
mService.sendMessage(name,email,group,message);
editText.setText("");
// Call a method from the SignalRService.
// However, if this call were something that might hang, then this request should
// occur in a separate thread to avoid slowing down the activity performance.
/*EditText editText = (EditText) findViewById(R.id.edit_message);
if (editText != null && editText.getText().length() > 0) {
}*/
}
}
public void setmMessageResive(JsonElement jsonElement)
{
listItems.add(10, String.valueOf(jsonElement));
}
/**
* Defines callbacks for service binding, passed to bindService()
*/
private final ServiceConnection mConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
// We've bound to SignalRService, cast the IBinder and get SignalRService instance
SignalRService.LocalBinder binder = (SignalRService.LocalBinder) iBinder;
mService = binder.getService();
mBound = true;
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
mBound = false;
}
};
#Override
public void doSomething(String msg) {
listItems.add(msg);
}
}
Service code
package myapp.chatapp;
import android.app.Service;
import android.bluetooth.BluetoothClass;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;
import com.google.gson.JsonElement;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.logging.Logger;
import microsoft.aspnet.signalr.client.Action;
import microsoft.aspnet.signalr.client.Credentials;
import microsoft.aspnet.signalr.client.LogLevel;
import microsoft.aspnet.signalr.client.MessageReceivedHandler;
import microsoft.aspnet.signalr.client.Platform;
import microsoft.aspnet.signalr.client.SignalRFuture;
import microsoft.aspnet.signalr.client.http.Request;
import microsoft.aspnet.signalr.client.http.android.AndroidPlatformComponent;
import microsoft.aspnet.signalr.client.hubs.HubConnection;
import microsoft.aspnet.signalr.client.hubs.HubProxy;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler1;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler2;
import microsoft.aspnet.signalr.client.hubs.SubscriptionHandler4;
import microsoft.aspnet.signalr.client.transport.ClientTransport;
import microsoft.aspnet.signalr.client.transport.LongPollingTransport;
import microsoft.aspnet.signalr.client.transport.ServerSentEventsTransport;
/**
* Created by NULLPLEX7 on 11/28/2017.
*/
public class SignalRService extends Service {
private HubConnection mHubConnection;
private HubProxy mHubProxy;
private Handler mHandler; // to display Toast message
private final IBinder mBinder = new LocalBinder(); // Binder given to clients
ClientTransport transport;
registerListener registerListener;
private MainActivity setmMessageResive;
public Something list;
public SignalRService() {
}
#Override
public void onCreate() {
super.onCreate();
mHandler = new Handler(Looper.getMainLooper());
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
int result = super.onStartCommand(intent, flags, startId);
startSignalR();
return result;
}
#Override
public void onDestroy() {
mHubConnection.stop();
super.onDestroy();
}
#Override
public IBinder onBind(Intent intent) {
// Return the communication channel to the service.
startSignalR();
return mBinder;
}
/**
* Class used for the client Binder. Because we know this service always
* runs in the same process as its clients, we don't need to deal with IPC.
*/
public class LocalBinder extends Binder {
public SignalRService getService() {
// Return this instance of SignalRService so clients can call public methods
return SignalRService.this;
}
}
/**
* method for clients (activities)
*/
public void sendMessage(String name, String email, String group, String msg ) {
String SERVER_METHOD_SEND = "BroadCastMessage";
mHubProxy.invoke(SERVER_METHOD_SEND, name,email,group,msg);
}
private void startSignalR() {
Platform.loadPlatformComponent(new AndroidPlatformComponent());
Credentials credentials = new Credentials() {
#Override
public void prepareRequest(Request request) {
request.addHeader("User-Name", "BNK");
}
};
String serverUrl = "myurlhere";
mHubConnection = new HubConnection(serverUrl);
mHubConnection.setCredentials(credentials);
String SERVER_HUB_CHAT = "ChatHub";
mHubProxy = mHubConnection.createHubProxy(SERVER_HUB_CHAT);
ClientTransport clientTransport = new ServerSentEventsTransport(mHubConnection.getLogger());
SignalRFuture<Void> signalRFuture = mHubConnection.start(clientTransport);
mHubProxy.subscribe(this);
transport = new LongPollingTransport(mHubConnection.getLogger());
mHubConnection.start(transport);
/* ****new codes here**** */
/* ****seems useless but should be here!**** */
mHubProxy.subscribe(new Object() {
#SuppressWarnings("unused")
public void newMessage(final String message, final String messageId, final String chatId,
final String senderUserId, final String fileUrl, final String replyToMessageId) {
}
});
try {
signalRFuture.get();
}catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
return;
}
mHubProxy.on("receiveGroupMessage",
new SubscriptionHandler4<String, String, String, String>() {
#Override
public void run(final String name,final String msg ,final String avtar,final String date ) {
final String finalMsg = name + " says " + msg;
/*final String finalMsg = msg;*/
// display Toast message
mHandler.post(new Runnable() {
#Override
public void run() {
list.doSomething(msg);
}
});
}
}
, String.class,String.class,String.class,String.class);
mHubConnection.received(new MessageReceivedHandler() {
#Override
public void onMessageReceived(final JsonElement json) {
Log.e("receiveGroupMessage ", json.toString());
mHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), ""+json, Toast.LENGTH_SHORT).show();
}
});
}
});
}
public interface Something
{
void doSomething(String msg);
}
}
i read on stack overflow that in onMessageReceived i get the server responses but i did not get any response here . I want when any one send message in group from web i want that message in my chat app someone suggest me that i need to create Event listener but i don't no how to create it . please tell me how do i get messages in my chat app.
mHubProxy.on("receiveGroupMessage",
new SubscriptionHandler4<String, String, String, String>() {
#Override
public void run(final String name,final String msg ,final String avtar,final String date ) {
final String finalMsg = name + " says " + msg;
/*final String finalMsg = msg;*/
// display Toast message
mHandler.post(new Runnable() {
#Override
public void run() {
list.doSomething(msg);
}
});
}
}
, String.class,String.class,String.class,String.class);
i thought that i got messages here but execution not go inside the Run.
Any Help is Welcome
I'm supposed to add a timer to my service class that prints a message to LogCat every 10 seconds. Nothing in the service class is printing once I call the startService method and I have no idea why.. Any ideas?
package com.murach.reminder;
import android.content.Intent;
import android.os.Bundle;
import android.app.Activity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class ReminderActivity extends Activity implements OnClickListener {
private Button startServiceButton;
private Button stopServiceButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_reminder);
startServiceButton = (Button) findViewById(R.id.startServiceButton);
stopServiceButton = (Button) findViewById(R.id.stopServiceButton);
startServiceButton.setOnClickListener(this);
stopServiceButton.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent serviceIntent = new Intent(this, ReminderService.class);
switch (v.getId()) {
case R.id.startServiceButton:
// put code to start service and display toast here
startService(serviceIntent);
Toast.makeText(this, "Service started", Toast.LENGTH_SHORT).show();
break;
case R.id.stopServiceButton:
// put code to stop service and display toast here
stopService(serviceIntent);
Toast.makeText(this, "Service stopped", Toast.LENGTH_SHORT).show();
break;
}
}
}
package com.murach.reminder;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import java.util.Timer;
import java.util.TimerTask;
public class ReminderService extends Service
{
private Timer timer;
public void onCreate()
{
Log.d("Reminder", "Service created");
startTimer();
}
#Override
public IBinder onBind(Intent intent)
{
Log.d("Reminder", "No binding for this activity");
return null;
}
public void onDestroy()
{
Log.d("Reminder", "Service destroyed");
stopTimer();
}
private void startTimer() {
TimerTask task = new TimerTask() {
public void run() {
Log.d("Reminder", "Timer task executed");
}
};
timer = new Timer(true);
int delay = 1000 * 10;
int interval = 1000 * 10;
timer.schedule(task, delay, interval);
}
private void stopTimer()
{
if (timer != null)
{
timer.cancel();
}
}
}
And here is how I register the service in the Manifest (in a service element, it wouldn't let me type it out completely)
android:name="com.murach.reminder.ReminderService"
The package names do not match. There is a spelling mistake in the word murach in your Manifest declaration.
how is possible that I am getting android.os.NetworkOnMainThreadException when I try to create a socket calling bulb.connectToHW() if I do it from the doInBackground() method of my asycTask?
This is the code of the AsyncTask:
package com.example.bulbcontrol2;
import java.net.InetAddress;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.AsyncTask;
import android.widget.TextView;
public class AsyncConnection extends AsyncTask<Object, String, String> {
private TextView textV;
private Context context;
private String message;
private Device bulb;
public AsyncConnection(TextView textViewToUpdate,Context context)
{
this.textV = textViewToUpdate;
this.context = context;
}
#Override
protected String doInBackground(Object... params) {
bulb = new Device((InetAddress) params[0],(Integer) params[1]);
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("open_connection"))
{
System.out.println(bulb.connectToHW());
message = "Connected";
System.out.println(bulb.dataTransferHW("hello"));
textV.setText(message);
}
if (intent.getAction().equals("close_connection"))
{
message = "Disconnected";
System.out.println(bulb.dataTransferHW("bye"));
bulb.closeConexHW();
}
}
};
IntentFilter filter = new IntentFilter("open_connection");
context.registerReceiver(receiver, filter);
filter.addAction("close_connection");
context.registerReceiver(receiver, filter);
return message;
}
/* protected void onProgressUpdate(String... progress) {
//textV.setText(progress[0]);
}*/
}
And this is the code of the UIThread :
package com.example.bulbcontrol2;
import java.net.InetAddress;
import java.net.UnknownHostException;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.TextView;
import android.widget.ToggleButton;
public class MainActivity extends Activity
{
Intent broadcastIntent = new Intent();
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bulbActions();
}
public void bulbActions()
{
final ToggleButton buttonBulb = (ToggleButton) findViewById(R.id.ToggleBulb);
final ToggleButton buttonLDR = (ToggleButton) findViewById(R.id.ToggleLDRValues);
final TextView txtLDR = (TextView) findViewById(R.id.TxtLDRValues);
byte [] hostBytes = new byte[] {(byte)192,(byte)168,(byte)0,(byte)12};
int port = 5006;
InetAddress host = null;
try
{
host = InetAddress.getByAddress(hostBytes);
}
catch (UnknownHostException e)
{
System.out.println("\nError with server address");
e.printStackTrace();
}
new AsyncConnection((TextView)findViewById(R.id.TxtLDRValues),this.getApplicationContext()).execute(host,port);
buttonBulb.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View arg0)
{
if (buttonBulb.isChecked())
{
System.out.println("Pulsado");
broadcastIntent.setAction("open_connection");
MainActivity.this.sendBroadcast(broadcastIntent);
}
else
{
System.out.println("NO Pulsado");
broadcastIntent.setAction("close_connection");
MainActivity.this.sendBroadcast(broadcastIntent);
}
}
});
}
}
Your doInBackground is just defining a BroadcastReceiver and registering it. All the code inside onReceive will run in the main thread when the system calls it following your onClick.
I don't know why you need a BroadcastReceiver if you're just triggering it from a button.
Instead you could do the network stuff directly on your doInBackground and then actually start the AsyncTask inside onClick.
On a case you do need a BroadcastReceiver what you wanna do is start a service from onReceive and do all the network job in the service.
After API11 you can also use goAsync() in the receiver as described here and start a Thread.
I am writing a simple service application, below is the code of Activity and Service..,when I am calling startService(), and stopService() its working fine for the one time,in my case it has to give notification..from next time onwards if call again startService(), and stopService() its not giving desired results...
---------- this is my activity class -------------
package com.mypack.serviceex;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
public class serviceex extends Activity implements Button.OnClickListener{
/** Called when the activity is first created. */
Button bt1,bt2;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
bt1 = (Button) findViewById(R.id.Button01);
bt2 = (Button) findViewById(R.id.Button02);
bt1.setOnClickListener(this);
bt2.setOnClickListener(this);
}
#Override
public void onClick(View v) {
if( v == bt1)
{
Intent i = new Intent(serviceex.this,myservice.class);
Log.i("err","onClick(View v....");
startService(i);
}
else if(v == bt2)
{
Intent i = new Intent(serviceex.this,myservice.class);
Log.i("err","else if(v == bt2)........");
stopService(i);
}
}
}
--------- this is my service -------------
package com.mypack.serviceex;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
public class myservice extends Service
{
private NotificationManager nmgr;
public void onCreate()
{
super.onCreate();
nmgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
Log.i("err","onCreate..........");
Thread th = new Thread(null,new incls(),"service...");
}
public void onStart(Intent intent,int sid)
{
super.onStart(intent, sid);
Log.i("err","onStart........");
}
public void onDestroy()
{
super.onDestroy();
Log.i("err","onDestroy..........");
displayMessage("Stopping Service");
}
public void displayMessage(String str)
{
Log.i("err.","displayMessage.....");
Notification nf = new Notification(R.drawable.icon,str,System.currentTimeMillis());
PendingIntent pi = PendingIntent.getActivity(this, 0, new Intent(this,myservice.class), 0);
nf.setLatestEventInfo(this, "Service...", str, pi);
nmgr.notify(R.string.uid, nf);
}
private class incls implements Runnable
{
public void run()
{
Log.i("err","public void run()..........");
System.out.println("In Runnn");
}
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
None of your methods are #Overrideing the class methods. You have to annote them with #Override. Also, on 2.1 you should use onStartCommand() instead of onStart(). And also note that calling startService() multiple times will only call onCreate() once