When clicked on the button on activity_main (button1) I would like to test the ChatClientService.
In the method onStartCommand i want to run a thread which uses the innerclass as runnable. This is were it goes wrong: the intent works (log shows aaaaa) and it goes into the run method (log shows aaaaa) but I do not manage to go into the innerclass. Any ideas? (sorry for the logs)
ChatClientService.java
public class ChatClientService extends Service {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
new Thread( new Runnable() {
#Override
public void run() {
Log.i("aaaaaaaaaaaaaaaaaaaa","aaaaaaaaaaaaaaaaaaaa");
}
}).start();
return Service.START_NOT_STICKY;
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
public class ChatClient implements Runnable {
private BufferedWriter bw;
private BufferedReader br;
private boolean running;
public void halt() {
Log.i("DDDDDDDDDDDDDDDDDD","DDDDDDDDDDDDDDDDDD");
running = true;
try {
bw.close();
bw = null;
br.close();
br = null;
} catch (IOException e) {
Log.i("EEEEEEEEEEEEEEEEE","EEEEEEEEEEEEEEEEEEE");
}
}
#Override
public void run() {
Log.i("HHHHHHHHHHHHHHH", "HHHHHHHHHHHHHHH");
try {
running = true;
Socket s = new Socket("<your pc ip>", 9999);
this.br = new BufferedReader(new InputStreamReader(s.getInputStream()));
this.bw = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
String in = null;
while(running && (in = br.readLine()) != null) {
Log.i("CHATCLIENT RECV ", in);
}
} catch (UnknownHostException e) {
e.printStackTrace();
Log.i("FFFFFFFFFFFFFFFF","FFFFFFFFFFFFFFF");
} catch (IOException e) {
e.printStackTrace();
Log.i("GGGGGGGGGGGGG","GGGGGGGGGGG");
}
}
}
}
MainActivity.java
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
public void TestChat(View v){
Log.i("cccccccccccccccccccccccccc","cccccccccccccccccccccc");
startService(new Intent(getApplication(), ChatClientService.class));
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="be.howest.mad.lab24.oef1"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="be.howest.mad.lab24.oef1.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="be.howest.mad.lab24.oef1.ChatClientService"
android:enabled="true"
android:exported="false" >
</service>
</application>
</manifest>
Thanks in advance!
try this...
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
new Thread(new ChatClient()).start();
return START_NOT_STICKY;
}
Related
After a lot of tests, both on Eclipse and Android Studio, we cannot understand why our app cannot start the scan from the Application Class.
Beacons are detected only when I start the scan from the button in MainActivity (didEnterRegion is properly called in ApplicationClass and I see the scanning in progress in the logCat) but if I don't let the scan start from the MainActivity with
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.bind(MainActivity.this);
it doesn't start at all.
In this case in the logCat nothing appears.
I read everything possible, and also try to launch the project on Android Studio but the same problem occurs.
Does anyone see what I'm missing? Should I do something else to let the scan start directly form the ApplicationClass?
Here is the code:
Project properties
target=Google Inc.:Google APIs:18
android.library.reference.1=../android-beacon-library
manifestmerger.enabled=true
android.library=false
Manifest
<!-- language: lang-xml -->
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pstm.testbeacon"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="18"
android:targetSdkVersion="23" />
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.GET_TASKS" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme"
android:name="com.pstm.testbeacon.ApplicationClass">
<activity
android:launchMode="singleInstance"
android:name="com.pstm.testbeacon.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Application Class
public class ApplicationClass extends Application implements BootstrapNotifier, BeaconConsumer {
private static final String TAG = "Demo1";
private RegionBootstrap regionBootstrap;
private BeaconManager beaconManager;
int contRange = 0;
Region regionRange = new Region("apr", null, null, null);
#Override
public void onCreate()
{
super.onCreate();
initSingletons();
}
protected void initSingletons()
{
BeaconManager.setsManifestCheckingDisabled(true);
Log.d(TAG, "App started up");
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.bind(this);
}
#Override
public void onBeaconServiceConnect() {
// TODO Auto-generated method stub
beaconManager.setBackgroundBetweenScanPeriod(1000l);
beaconManager.setBackgroundScanPeriod(3000l);
beaconManager.setBackgroundMode(true);
try {
beaconManager.updateScanPeriods();
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// beaconManager.getBeaconParsers().add(new BeaconParser().
// setBeaconLayout("m:0-3=4c000215,i:4-19,i:20-21,i:22- 23,p:24-24"));
Region region = new Region("apr", null, null, null);
regionBootstrap = new RegionBootstrap(this, region);
}
#Override
public void didDetermineStateForRegion(int arg0, Region arg1) {
// TODO Auto-generated method stub
}
#Override
public void didEnterRegion(Region arg0) {
// TODO Auto-generated method stub
showNotification(
"Enter in Beacon area",
"Thanks");
}
#Override
public void didExitRegion(Region arg0) {
// TODO Auto-generated method stub
showNotification(
"Exit From Beacon",
"Thanks");
}
public void showNotification(String title, String message) {
Intent notifyIntent = new Intent(this, MainActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Random random = new Random();
int n = random.nextInt(9999 - 1000) + 1000;
PendingIntent pendingIntent = PendingIntent.getActivities(this, n,
new Intent[] { notifyIntent }, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification.Builder(this)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle(title)
.setContentText(message)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.build();
notification.defaults |= Notification.DEFAULT_SOUND;
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(n, notification);
}
}
MainActivity
public class MainActivity extends Activity implements BeaconConsumer {
private BeaconManager beaconManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
beaconManager = BeaconManager.getInstanceForApplication(this);
beaconManager.bind(MainActivity.this);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onBeaconServiceConnect() {
}
}
I am creating sample app with kiosk mode in my app to check that is kiosk mode work or not.?. But in sample app kiosk mode is not working. I means after screen goes off activity is not starting.
I have taken this from [http://www.andreas-schrade.de/2015/02/16/android-tutorial-how-to-create-a-kiosk-mode-in-android/][here]
THis is my main activity
public class MainActivity extends Activity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
setContentView(R.layout.activity_main);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
if(!hasFocus) {
// Close every kind of system dialog
Intent closeDialog = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
sendBroadcast(closeDialog);
}
}
}
THis is my Application class
public class AppContext extends Application {
private AppContext instance;
private PowerManager.WakeLock wakeLock;
private OnScreenOffReceiver onScreenOffReceiver;
PowerManager pm;
#Override
public void onCreate() {
super.onCreate();
instance = this;
registerKioskModeScreenOffReceiver();
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
startKioskService();
}
private void registerKioskModeScreenOffReceiver() {
// register screen off receiver
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_OFF);
onScreenOffReceiver = new OnScreenOffReceiver();
registerReceiver(onScreenOffReceiver, filter);
}
public PowerManager.WakeLock getWakeLock() {
if(wakeLock == null) {
// lazy loading: first call, create wakeLock via PowerManager.
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "wakeup");
}
return wakeLock;
}
private void startKioskService() { // ... and this method
startService(new Intent(this, KioskService.class));
}
}
This is receiver class
public class OnScreenOffReceiver extends BroadcastReceiver {
private static final String PREF_KIOSK_MODE = "pref_kiosk_mode";
#Override
public void onReceive(Context context, Intent intent) {
if(Intent.ACTION_SCREEN_OFF.equals(intent.getAction())){
AppContext ctx = (AppContext) context.getApplicationContext();
// is Kiosk Mode active?
if(isKioskModeActive(ctx)) {
wakeUpDevice(ctx);
}
}
}
private void wakeUpDevice(AppContext context) {
PowerManager.WakeLock wakeLock = context.getWakeLock(); // get WakeLock reference via AppContext
if (wakeLock.isHeld()) {
wakeLock.release(); // release old wake lock
}
// create a new wake lock...
wakeLock.acquire();
// ... and release again
wakeLock.release();
}
private boolean isKioskModeActive(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(PREF_KIOSK_MODE, false);
}
}
THis is Service class
public class KioskService extends Service {
private static final long INTERVAL = TimeUnit.SECONDS.toMillis(2); // periodic interval to check in seconds -> 2 seconds
private static final String TAG = KioskService.class.getSimpleName();
private static final String PREF_KIOSK_MODE = "pref_kiosk_mode";
private Thread t = null;
private Context ctx = null;
private boolean running = false;
#Override
public void onDestroy() {
Log.i(TAG, "Stopping service 'KioskService'");
running =false;
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Starting service 'KioskService'");
running = true;
ctx = this;
// start a thread that periodically checks if your app is in the foreground
t = new Thread(new Runnable() {
#Override
public void run() {
do {
handleKioskMode();
try {
Thread.sleep(INTERVAL);
} catch (InterruptedException e) {
Log.i(TAG, "Thread interrupted: 'KioskService'");
}
}while(running);
stopSelf();
}
});
t.start();
return Service.START_NOT_STICKY;
}
private void handleKioskMode() {
// is Kiosk Mode active?
if(isKioskModeActive(ctx)) {
// is App in background?
if(isInBackground()) {
restoreApp(); // restore!
}
}
}
private boolean isInBackground() {
ActivityManager am = (ActivityManager) ctx.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
ComponentName componentInfo = taskInfo.get(0).topActivity;
return (!ctx.getApplicationContext().getPackageName().equals(componentInfo.getPackageName()));
}
private void restoreApp() {
// Restart activity
Intent i = new Intent(ctx, MainActivity.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(i);
}
public boolean isKioskModeActive(final Context context) {
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
return sp.getBoolean(PREF_KIOSK_MODE, false);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
This is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.kioskmode"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="21" />
<application
android:allowBackup="true"
android:name=".AppContext"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.example.kioskmode.KioskService" android:exported="false"></service>
<receiver android:name="com.example.kioskmode.OnScreenOffReceiver" android:enabled="true" >
<intent-filter android:priority="1000" >
<action android:name="android.app.action.SCREEN_OFF" />
<action android:name="android.app.action.SCREEN_ON" />
</intent-filter>
</receiver>
</application>
<uses-permission android:name="android.permission.GET_TASKS"/>
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
</manifest>
Any one can solve this... for me..?? Thanks in advance..
Your method isKioskModeActive is always false. So it won't restore your app.
I use AIDL interface IExtendedNetworkService to get USSD code. But application only work after reboot device. I tried bindservice after install app but it didn't work. So my problem is how way to bind service without reboot device . This is my code:
interface:
package com.android.internal.telephony;
interface IExtendedNetworkService {
void setMmiString(String number);
CharSequence getMmiRunningText();
CharSequence getUserMessage(CharSequence text);
void clearMmiString();
}
Service
public class CDUSSDService extends Service {
private String TAG = "THANG-NGUYEN";
private boolean mActive = false;
BroadcastReceiver receiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_INSERT)) {
// activity wishes to listen to USSD returns, so activate this
mActive = true;
Log.d(TAG, "activate ussd listener");
} else if (intent.getAction().equals(Intent.ACTION_DELETE)) {
mActive = false;
Log.d(TAG, "deactivate ussd listener");
}
}
};
private final IExtendedNetworkService.Stub mBinder = new IExtendedNetworkService.Stub() {
public void clearMmiString() throws RemoteException {
Log.d(TAG, "called clear");
}
public void setMmiString(String number) throws RemoteException {
Log.d(TAG, "setMmiString:" + number);
}
public CharSequence getMmiRunningText() throws RemoteException {
if (mActive == true) {
return null;
}
return "USSD Running";
}
public CharSequence getUserMessage(CharSequence text)
throws RemoteException {
Log.d(TAG, "get user message " + text);
if (mActive == false) {
// listener is still inactive, so return whatever we got
Log.d(TAG, "inactive " + text);
return text;
}
// listener is active, so broadcast data and suppress it from
// default behavior
// build data to send with intent for activity, format URI as per
// RFC 2396
Uri ussdDataUri = new Uri.Builder()
.scheme(getBaseContext().getString(R.string.uri_scheme))
.authority(
getBaseContext().getString(R.string.uri_authority))
.path(getBaseContext().getString(R.string.uri_path))
.appendQueryParameter(
getBaseContext().getString(R.string.uri_param_name),
text.toString()).build();
sendBroadcast(new Intent(Intent.ACTION_GET_CONTENT, ussdDataUri));
mActive = false;
return null;
}
};
public void onCreate() {
Log.i(TAG, "called onCreate");
};
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "called onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent intent) {
Log.i(TAG, "called onbind");
// the insert/delete intents will be fired by activity to
// activate/deactivate listener since service cannot be stopped
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_INSERT);
filter.addAction(Intent.ACTION_DELETE);
filter.addDataScheme(getBaseContext().getString(R.string.uri_scheme));
filter.addDataAuthority(
getBaseContext().getString(R.string.uri_authority), null);
filter.addDataPath(getBaseContext().getString(R.string.uri_path),
PatternMatcher.PATTERN_LITERAL);
registerReceiver(receiver, filter);
return mBinder;
}
}
MainActivity:
public class MainActivity extends Activity {
private Button btnCheckUSSD;
private Context mContext;
private IExtendedNetworkService mService;
private EditText inputUSSD;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = this;
setContentView(R.layout.activity_main);
btnCheckUSSD = (Button) findViewById(R.id.btn_check);
inputUSSD = (EditText) findViewById(R.id.input_ussd);
btnCheckUSSD.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (!inputUSSD.getText().toString().isEmpty()) {
Intent service = new Intent(
"com.android.ussd.IExtendedNetworkService");
bindService(service, mConnecton, Context.BIND_AUTO_CREATE);
startActivity(new Intent("android.intent.action.CALL", Uri
.parse("tel:" + inputUSSD.getText().toString()
+ Uri.encode("#"))));
}
}
});
}
ServiceConnection mConnecton = new ServiceConnection() {
#Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
}
#Override
public void onServiceConnected(ComponentName name, IBinder iBinder) {
mService = IExtendedNetworkService.Stub
.asInterface((IBinder) iBinder);
}
};
protected void onDestroy() {
super.onDestroy();
Log.d("THANG-NGUYEN", "onDestroy");
unbindService(mConnecton);
}
}
Manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="info.example.checkussdcode"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="7"
android:targetSdkVersion="17" />
<uses-permission android:name="android.permission.READ_SMS" />
<uses-permission android:name="android.permission.WRITE_SMS" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="info.example.checkussdcode.MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name="info.example.checkussdcode.service.UssdCodeService"
android:process=":remote" >
<intent-filter>
<action android:name="com.android.ussd.IExtendedNetworkService" >
</action>
</intent-filter>
</service>
<receiver android:name="info.example.checkussdcode.RebootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
I'm code up a simple wallpaper service, similar to this one(Android app to change wallpaper at regular intervals using Timer).
The wallpaper is stuck forever at "Loading live wallpaper..." although the images I tried to draw are tiny (2kb png).
My manifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.TestWallpaper">
<uses-sdk android:minSdkVersion="15"/>
<uses-feature android:name="android.software.live_wallpaper" />
<application android:icon="#drawable/icon"
android:label="#string/app_name"
android:permission="android.permission.BIND_WALLPAPER">
<service android:name=".Wallpaper"
android:label="#string/app_name"
android:icon="#drawable/icon">
<intent-filter>
<action android:name="android.service.wallpaper.WallpaperService" />
</intent-filter>
<meta-data android:name="android.service.wallpaper"
android:resource="#xml/livewallpaper" />
</service>
</application>
</manifest>
And my main class file:
public class Wallpaper extends Service {
Timer mytimer;
int initialStart= 0;
int interval=60000;
Drawable drawable;
WallpaperManager wpm;
int prev=1;
#Override
public void onCreate() {
super.onCreate();
Log.i("TestWallPaper=>", "print");
mytimer=new Timer();
wpm= WallpaperManager.getInstance(Wallpaper.this);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
mytimer.schedule(new TimerTask() {
#Override
public void run() {
Log.i("TestWallPaper=>", "inside onStartCommand");
if(prev==1){
Log.i("TestWallPaper=>", "prev==1");
drawable = getResources().getDrawable(R.drawable.blue_pin);
prev=2;
}
else if(prev==2){
Log.i("TestWallPaper=>", "prev==2");
drawable = getResources().getDrawable(R.drawable.red_pin);
prev=3;
}
else{
Log.i("TestWallPaper=>", "prev==3");
drawable = getResources().getDrawable(R.drawable.green_pin);
prev=1;
}
Bitmap wallpaper=((BitmapDrawable)drawable).getBitmap();
try {
wpm.setBitmap(wallpaper);
} catch (IOException e) {
Log.e("TestWallPaper=>", "inside onStartCommand");
e.printStackTrace();
}
}
}, initialStart,interval);
return super.onStartCommand(intent, flags, startId);
}
#Override
public IBinder onBind(Intent arg0) {
Log.i("TestWallPaper=>", "inside onBind");
return null;
}
}
I'm trying to use this very simple Service and BroadcastReceiver but I'm getting a
ClassNotFound exception. If I don't use startService things are fine so the problem it's with the receiver. I have registered it in the android manifest file so why do I get the ClassNotFound exception?
I will be using this method of communication for polling a php file and updating a ListView. Is this the appropriate way of communicating (broadcast intent)?
public class MessengerServiceActivity extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
startService(new Intent(this,MessengerService.class));
}
class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle b=intent.getExtras();
if(b==null)
return;
String msg=b.getString("message");
TextView tv=(TextView) findViewById(R.id.textView1);
tv.setText(msg);
}
}
}
public class MessengerService extends Service {
HttpClient hc;
HttpPost hp;
String s[]={"pratik","harsha","dayal","hritika"};
public MessengerService() {
// TODO Auto-generated constructor stub
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
hc=new DefaultHttpClient();
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Thread t=new Thread(new Runnable(){
public void run()
{
int k=0;
while(true)
{
Intent i=new Intent("com.pdd.messenger.MyAction");
i.putExtra("message",s[k]);
sendBroadcast(i);
try
{
Thread.sleep(3000);
}
catch (InterruptedException e)
{
Toast.makeText(getApplicationContext(), e.getLocalizedMessage(), Toast.LENGTH_LONG)
.show();
}
k=(k+1)%4;
}
}
});
t.start();
return super.onStartCommand(intent, flags, startId);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.pdd.messenger"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk android:minSdkVersion="8" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name=".MessengerServiceActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".MyReceiver" android:enabled="true">
<intent-filter>
<action android:name="com.pdd.messenger.MyAction"/>
</intent-filter>
</receiver>
<service android:name=".MessengerService"></service>
</application>
</manifest>