I have a service that have to start an application and count every 15 second.
I create AlarmManager and call the service every 15 second.The problem is when i push the start button program start service class and open application and start to count, but when i push stop button the application get error
"Unfortunately, Program has stopped."
After that the program automatically start to counting and opening the application
and i can't stop that.
I can't figure out. any help or something new can do this. thanks.
Myservice.java
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class Myservice extends Service{
int counter=0;
public IBinder onBind(Intent arg0)
{
return null;
}
public void onCreate() {
Toast.makeText(getApplicationContext(), "Service Created", Toast.LENGTH_SHORT).show();
}
#SuppressWarnings("deprecation")
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
Startapp();
counter++;
Toast.makeText(getApplicationContext(), "Service Start : " + counter,Toast.LENGTH_SHORT).show();
}
public void onDestroy()
{
Toast.makeText(getApplicationContext(), "Service Destroy", Toast.LENGTH_SHORT).show();
super.onDestroy();
}
public void Startapp()
{
Intent in = getPackageManager().getLaunchIntentForPackage("com.example.application");
startActivity(in);
Toast.makeText(getApplicationContext(), "Counter : " + counter, Toast.LENGTH_SHORT).show();
}
}
MainActivity.java
import java.util.Calendar;
import java.util.List;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
Intent myIntent;
PendingIntent pendingIntent;
AlarmManager alarmManager;
Button btn1;
Button btn2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn1 = (Button)findViewById(R.id.button1);
btn2 =(Button)findViewById(R.id.button2);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
myIntent = new Intent(MainActivity.this, Clash.class);
pendingIntent = PendingIntent.getService(MainActivity.this, 7778, myIntent, 0);
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),15000, pendingIntent);
Toast.makeText(MainActivity.this, "Start Alarm", Toast.LENGTH_LONG).show();
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
alarmManager.cancel(pendingIntent);
pendingIntent.cancel();
Toast.makeText(MainActivity.this, "Cancel!", Toast.LENGTH_LONG).show();
}
});
}
Try this its working....set in stop button...always cancel pending intent after creating it
alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
myIntent = new Intent(MainActivity.this, MyService.class);
btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pendingIntent = PendingIntent.getService(MainActivity.this, 7778, myIntent, 0);
try {
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("ex....."+e);
}
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.add(Calendar.SECOND, 10);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),10000, pendingIntent);
Toast.makeText(MainActivity.this, "Start Alarm", Toast.LENGTH_LONG).show();
}
});
btn2.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pendingIntent = PendingIntent.getService(MainActivity.this, 7778, myIntent, 0);
try {
alarmManager.cancel(pendingIntent);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
System.out.println("ex....."+e);
}
MainActivity.this.stopService(myIntent);
Toast.makeText(MainActivity.this, "Cancel!", Toast.LENGTH_LONG).show();
}
});
You need to set this flag:
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
So your Startapp method will look like this:
public void Startapp()
{
Intent in = getPackageManager().getLaunchIntentForPackage("com.example.application");
in.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(in);
Toast.makeText(getApplicationContext(), "Counter : " + counter, Toast.LENGTH_SHORT).show();
}
Related
I want to make an app that shows a notification as soon as headphone is plugged in and remove it when it is plugged out. My app works fine when it is on or home button is pressed, but doesn't work when back is pressed or app is closed by long pressing home and swiping it away. What should I use in order to make it work?
This is my code
package com.example.earphone;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;
public class HeadsetPlugReceiver extends BroadcastReceiver {
TextView t1;
#Override
public void onReceive(Context context, Intent intent) {
if (!intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
return;
}
boolean connectedHeadphones = (intent.getIntExtra("state", 0) == 1);
// boolean connectedMicrophone = (intent.getIntExtra("microphone", 0) == 1) && connectedHeadphones;
String headsetName = intent.getStringExtra("name");
Log.v("message", "headphone connected" + headsetName);
Intent i = new Intent(context, MainActivity.class);
PendingIntent p = PendingIntent.getActivity(context,0,i,0);
// Toast.makeText(context, "Headphone connected", Toast.LENGTH_SHORT).show();
if (intent.getAction().equals(Intent.ACTION_HEADSET_PLUG)) {
int state = intent.getIntExtra("state", -1);
if(state==1){
Intent intent1 = new Intent(context, ES.class);
context.startForegroundService(intent1);
}
switch (state) {
case 0:
Intent intent1 = new Intent(context, ES.class);
context.stopService( intent1);
Toast.makeText(context, "Headphone ejected", Toast.LENGTH_SHORT).show();
break;
case 1:
Toast.makeText(context, "Headphone connected", Toast.LENGTH_SHORT).show();
break;
default:
Toast.makeText(context, "I have no idea what the headset state is", Toast.LENGTH_SHORT).show();
}
}
}}
package com.example.earphone;
import android.app.Application;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.os.Build;
public class App extends Application {
public static final String C_ID = "noti";
#Override
public void onCreate() {
super.onCreate();
createnoti();
}
private void createnoti(){
if (Build.VERSION.SDK_INT>= Build.VERSION_CODES.O){
NotificationChannel nc = new NotificationChannel(
C_ID,"ex", NotificationManager.IMPORTANCE_DEFAULT
);
NotificationManager nm= getSystemService(NotificationManager.class);
nm.createNotificationChannel(nc);
}
}
}
package com.example.earphone;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.NotificationCompat;
import static com.example.earphone.App.C_ID;
public class ES extends Service {
#Override
public void onCreate() {
super.onCreate();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Intent ni = new Intent(this,HeadsetPlugReceiver.class);
PendingIntent pi = PendingIntent.getActivity(this,0,ni,0);
Notification notification = new NotificationCompat.Builder(this, C_ID)
.setContentTitle("Headphones plugged in")
.setContentText("currently plugged in")
.setSmallIcon(R.mipmap.ic_launcher).setContentIntent(pi).build();
startForeground(1,notification);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
public class MainActivity extends AppCompatActivity {
Button b;
HeadsetPlugReceiver headsetPlugReceiver;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b = findViewById(R.id.b);
// Intent intent = new Intent(this, ES.class);
//startService(intent);
headsetPlugReceiver = new HeadsetPlugReceiver();
IntentFilter i = new IntentFilter();
i.addAction("android.intent.action.HEADSET_PLUG");
registerReceiver(headsetPlugReceiver,i);
}
}
I am in the process of trying to get an email sent using BroadcastReceiver, the code is working correct using AsyncTask when using onClick but does not work when AlarmReceiver is being called.
Would it be better to use IntentService for this method? If so, what is the best way to write this?
Can anyone help with this problem? I am still new to java and want to help improve my knowledge. :)
Any help would be appreciated! Thank you!
AlarmReceiver.java
import android.app.Activity;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationCompat;
import android.content.BroadcastReceiver;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;
import static android.graphics.Color.GREEN;
public class AlarmReceiver extends BroadcastReceiver {
Context cxt;
Activity context;
#Override
public void onReceive(Context arg0, Intent arg1) {
cxt = arg0;
addNotification();
new SendMail().execute();
}
private class SendMail extends AsyncTask<String, Integer, Void> {
protected Void doInBackground(String... params) {
Mail m = new Mail("youremail#gmail.com", "password");
String[] toArr = {"toemail#outlook.com"};
m.setTo(toArr);
m.setFrom("fromemail#gmail.com");
m.setSubject("Achieve Alert!");
m.setBody("This is a reminder about your upcoming assignment or examination!");
try {
if(m.send()) {
Toast.makeText(context.getApplicationContext(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(context.getApplicationContext(), "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email", e);
}
return null;
}
}
}
First start Intent service from Alarm manager :
private void setAlarm(Calendar targetCal){
/* HERE */ Intent intent = new Intent(getBaseContext(), AlarmService.class);
final int _id = (int) System.currentTimeMillis();
/* HERE */ PendingIntent pendingIntent = PendingIntent.getService(this,_id,intent,PendingIntent.FLAG_ONE_SHOT);
AlarmManager alarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
......
.....
Now Intent Service class:
public class AlarmService extends IntentService {
PowerManager powerManager;
PowerManager.WakeLock wakeLock;
public AlarmService() {
super("");
}
#Override
protected void onHandleIntent(Intent intent) {
powerManager = (PowerManager) getSystemService(POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "FCFCFCFC");
wakeLock.acquire();
addNotification();
sendMAIL();
}
public void addNotification() {
NotificationCompat.Builder builder =
new NotificationCompat.Builder(getApplicationContext())
.setSmallIcon(R.drawable.icon_transperent)
.setLights(GREEN, 700, 700)
.setContentTitle("Achieve - Alert!")
.setContentText("This is a reminder for your deadline!");
Intent notificationIntent = new Intent(getApplicationContext(), MainMenu.class);
PendingIntent contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(contentIntent);
// Add as notification
NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
builder.setVibrate(new long[] { 0, 1000, 1000, 1000, 1000 });
manager.notify(0, builder.build());
}
public void sendMAIL(){
Mail m = new Mail("youremail#gmail.com", "password");
String[] toArr = {"toemail#outlook.com"};
m.setTo(toArr);
m.setFrom("fromemail#gmail.com");
m.setSubject("Achieve Alert!");
m.setBody("This is a reminder about your upcoming assignment or examination!");
try {
if(m.send()) {
Toast.makeText(getApplicationContext(), "Email was sent successfully.", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(), "Email was not sent.", Toast.LENGTH_LONG).show();
}
} catch(Exception e) {
Log.e("MailApp", "Could not send email", e);
}
wakeLock.release();
}
#Override
public void onDestroy() {
super.onDestroy();
}
}
Now, Manifest add:
<uses-permission android:name="com.android.alarm.permission.SET_ALARM"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<service android:name=".AlarmService" android:exported="true" android:enabled="true"/>
I need to share certain strings with my service class however when I attempt to do so I'm getting two errors stating "myWifiInfo cannot be resolved" when attempting to implement a string array using the following method (shown in the source below - and the link below):
Passing String array between two class in android application
Any suggestions? (I've been trying very hard to pass this data to a server I have running - I feel like I'm almost there - I just can't figure out why the service class can't find the strings from Main.java)
Main.java:
Intent intent = new Intent(Main.this, Service_class.class);
String[] myStrings = new String[] {"myWifiInfo.getRssi()", "myWifiInfo.getLinkSpeed()"};
intent.putExtra("strings", myStrings);
startActivity(intent);
Service_class.java:
Intent intent = getIntent();
String[] myStrings = intent.getStringArrayExtra("strings");
Main.java Full Source Code:
import java.util.Calendar;
import com.parse.ParseAnalytics;
import com.parse.ParseObject;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Chronometer;
import android.widget.TextView;
public class Main extends Activity {
TextView textSsid, textSpeed, textRssi;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
public static String TAG="TEST TAG";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Main.this, Service_class.class);
String[] myStrings = new String[] {"myWifiInfo.getRssi()", "myWifiInfo.getLinkSpeed()"};
intent.putExtra("strings", myStrings);
startActivity(intent);
PendingIntent pintent = PendingIntent.getService(Main.this, 0, intent,
0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
12 * 1000, pintent);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), Service_class.class));
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), Service_class.class));
}
});
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
ParseAnalytics.trackAppOpened(getIntent());
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
+ WifiInfo.LINK_SPEED_UNITS);
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}
};
};}
Service Class Full Source Code:
import com.parse.ParseObject;
import android.app.AlertDialog;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.TrafficStats;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.util.Log;
import android.widget.Chronometer;
import android.widget.TextView;
import android.widget.Toast;
public class Service_class extends Service {
public static String TAG="TEST TAG";
TextView textSsid, textSpeed, textRssi;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
public void onCreate(Bundle savedInstanceState) {
super.onCreate();
Intent intent = getIntent();
String[] myStrings = intent.getStringArrayExtra("strings");
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED || mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
}
private Intent getIntent() {
// TODO Auto-generated method stub
return null;
}
private TextView findViewById(int speed) {
// TODO Auto-generated method stub
return null;
}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes()- mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes()- mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataOut", Long.valueOf(myWifiInfo.getRssi()));
testObject.put("DataIn", Long.valueOf(myWifiInfo.getLinkSpeed()));
testObject.put("DataRSSI", String.valueOf(textRssi));
testObject.put("DataSpeed", String.valueOf(textSpeed));
testObject.saveInBackground();
final Chronometer myChronometer = (Chronometer)findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private Chronometer findViewById(int chronometer) {
// TODO Auto-generated method stub
return null;
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed()) + " "
+ WifiInfo.LINK_SPEED_UNITS);
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}}};
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this, "Hello World", Toast.LENGTH_LONG).show();
// Log.d(TAG, "starting service");
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataOut", Long.valueOf(txBytes));
testObject.put("DataIn", Long.valueOf(mStartRX));
testObject.put("DataRSSI", String.valueOf(textRssi));
testObject.put("DataSpeed", String.valueOf(textSpeed));
testObject.saveInBackground();
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ntent intent = new Intent(Main.this, Service_class.class);
intent.putExtra("strings", myStrings);
startActivity(intent);
startService(new Intent(getBaseContext(), Service_class.class));
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
ntent intent = new Intent(Main.this, Service_class.class);
intent.putExtra("strings", myStrings);
startActivity(intent);
stopService(new Intent(getBaseContext(), Service_class.class));
}
});
try this...myStrings Declare Globally And delcare intent And Put value Line write in button Click Event.
myWifiInfo isn't declared/ visible from where you use it. Instantiate it with WifiInfo myWifiInfo = myWifiManager.getConnectionInfo(); as you do above in your run() method.
Just because you already declared myWifiInfo somewhere in your code doesn't mean you can use it anywhere. The declaration of myWifiInfo isn't visible from the run method. It's called 'scope'.
So change this:
testObject.put("DataOut", Long.valueOf(myWifiInfo.getRssi()));
testObject.put("DataIn", Long.valueOf(myWifiInfo.getLinkSpeed()));
to
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
testObject.put("DataOut", Long.valueOf(myWifiInfo.getRssi()));
testObject.put("DataIn", Long.valueOf(myWifiInfo.getLinkSpeed()));
When you write new Runnable(){...} you are instantiating an inline class; insede this class this refers to the class itself. You are referring to this.myWifiReceiver but I don't see where the myWifiReceiver object is declared.
has everyone know how to sending an email from android device like mailto: in PHP?? i really need that for my lockscreen application.. it will send a email (email must be registered before) to the client when his/her forgot his/her password. what should i do?? any idea?? thanks..
package com.application.outgoingemail;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class EmailService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
//Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
}
#Override
public void onStart(Intent intent, int startid) {
//Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
sendEmail();
}
#Override
public void onDestroy() {
}
public void sendEmail()
{
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"myEmail#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT , "body of email");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(EmailService.this,ex.getMessage(), Toast.LENGTH_SHORT).show();
Toast.makeText(EmailService.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
/*try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (Exception ex) {
Toast.makeText(EmailService.this,ex.getMessage(), 10).show();
//Toast.makeText(EmailService.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}*/
}
}
and on the mainForm :
package com.application.outgoingemail;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class main extends Activity implements OnClickListener{
/** Called when the activity is first created. */
Button Button1,Button2;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button1=(Button)findViewById(R.id.button1);
Button1.setOnClickListener(this);
Button2=(Button)findViewById(R.id.button2);
Button2.setOnClickListener(this);
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.button1:
startService(new Intent(main.this, EmailService.class));
break;
case R.id.button2:
stopService(new Intent(main.this, EmailService.class));
break;
default:
break;
}
}
}
you can do by this way ::
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("text/plain");
i.putExtra(Intent.EXTRA_EMAIL , new String[]{"recipient#example.com"});
i.putExtra(Intent.EXTRA_SUBJECT, "subject of email");
i.putExtra(Intent.EXTRA_TEXT , "body of email");
try {
startActivity(Intent.createChooser(i, "Send mail..."));
} catch (android.content.ActivityNotFoundException ex) {
Toast.makeText(MyActivity.this, "There are no email clients installed.", Toast.LENGTH_SHORT).show();
}
I'm new at this android stuff and trying to teach myself the language and I'm running into a brick wall here.
I'm trying to program a really simple widge that is just a button. When the button is pressed the phone goes to silent mode. Unfortunately, the onlky thing that I am able to program the button do is pop a toast message.
Can someone please advise me on my errors. Thanks a bunch in advance. Here is my code:
package com.DoNotDisturb.widget;
import com.DoNotDisturb.widget.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.util.Log;
import android.widget.RemoteViews;
import android.widget.Toast;
public class DoNotDisturbWidget extends AppWidgetProvider {
public static String ACTION_WIDGET_CONFIGURE = "ConfigureWidget";
public static String ACTION_WIDGET_RECEIVER = "ActionReceiverWidget";
#Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
Intent active = new Intent(context, DoNotDisturbWidget.class);
active.setAction(ACTION_WIDGET_RECEIVER);
active.putExtra("msg", "Phone is silent");
PendingIntent actionPendingIntent = PendingIntent.getBroadcast(context, 0, active, 0);
remoteViews.setOnClickPendingIntent(R.id.button_one, actionPendingIntent);
appWidgetManager.updateAppWidget(appWidgetIds, remoteViews);
}
#Override
public void onReceive(Context context, Intent intent) {
// v1.5 fix that doesn't call onDelete Action
final String action = intent.getAction();
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else {
// check, if our Action was called
if (intent.getAction().equals(ACTION_WIDGET_RECEIVER)) {
String msg = "null";
try {
msg = intent.getStringExtra("msg");
} catch (NullPointerException e) {
Log.e("Error", "msg = null");
}
Toast.makeText(context, msg, Toast.LENGTH_SHORT).show();
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intent, 0);
NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
Notification noty = new Notification(R.drawable.icon, "Do Not Disturb Feature Activated", System.currentTimeMillis());
noty.setLatestEventInfo(context, "Notice", msg, contentIntent);
notificationManager.notify(1, noty);
} else {
// do nothing
}
super.onReceive(context, intent);
}
}
private AudioManager getSystemService(String audioService) {
// TODO Auto-generated method stub
return null;
}
}