Android: Why doesn't my Service start? - java

I want to learn how to use services in my application, but Service doesn't work! Here is my code.
This is the sample code i have written for the services. Suggest me if i am missing anything.Thanks in Advance
package com.example.utente.test;
import android.content.Intent
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity implements
AdapterView.OnItemClickListener {
final String[] numeri =
{"1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2"
,"1","2","1","2",
"1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2","1","2",
"1","2","1","2"};
long inizio;
long fine;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
inizio = System.currentTimeMillis();
Intent i= new Intent(getApplicationContext(), MyService.class);
startService(i);
ArrayAdapter<String> adapter = new ArrayAdapter<String>(this,
R.layout.riga, numeri);
ListView listView = (ListView)findViewById(R.id.listView);
listView.setAdapter(adapter);
listView.setOnItemClickListener(this);
}
#Override
public void onResume()
{
super.onResume();
inizio = System.currentTimeMillis();
// new MyService(inizio);
}
#Override
public void onItemClick(AdapterView<?> adattatore, final View componente,
int posizione, long id )
{
Toast.makeText(getApplicationContext(), numeri[posizione],
Toast.LENGTH_LONG).show();
}
}
package com.example.utente.test;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service
{
long inizio;
long fine;
long tempo;
boolean ciclo=true;
int prova=0;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// This is where you would place your code that you want in the
background
// Putting your while loop here will make sure it runs when the app is closed
Toast.makeText(getApplicationContext() ,"COMMAND",
Toast.LENGTH_LONG).show();
while(ciclo)
{
fine = System.currentTimeMillis();
tempo = (fine-inizio)/1000;
if(tempo>10 && prova==0)
{
prova++;
Toast.makeText(getApplicationContext(), "10s",
Toast.LENGTH_LONG).show();
}
}
return Service.START_STICKY;
}
#Override
public IBinder onBind(Intent intent) {
//TODO for communication return IBinder implementation
return null;
}
}
<?xml version="1.0" encoding="utf-8"?>
Manifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.utente.test">
<service
android:name="MyService" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>

Add your Service to your Manifest as followed:
<service android:name=".MyService" />

Related

How to receive ACTION_SCREEN_OFF with a "always running" service

I want to create an app that set/reset a timer to reproduce a song if the mobile spend 8 hours with the screen off.
I want to create a service that receive ACTION_SCREEN_OFF, but the problem is that when the app is killed from recent apps, the service is killed. I try with START_STICKY but the service is not restarted (onCreate is called sometimes but not onStart Command). I try to set in Manifest but the receiver must be register.
By now I only want that receiver detect ACTION_SCREEN_OFF.
I Have this code:
MainScreen.java (MainActivity)
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
public class MainScreen extends Activity implements View.OnClickListener{
public static final String MSG_TAG = "NoSleepMore";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main_screen);
findViewById(R.id.start_service_button).setOnClickListener(this);
findViewById(R.id.stop_service_button).setOnClickListener(this);
}
#Override
public void onClick(View v){
Intent intent = new Intent(getApplicationContext(), LockService.class);
switch (v.getId()) {
case R.id.start_service_button:
Log.e(MSG_TAG,"Service started");
//starts service for the given Intent
startService(intent);
break;
case R.id.stop_service_button:
Log.e(MSG_TAG,"Service stopped");
//stops service for the given Intent
stopService(intent);
break;
}
}
}
LockService.java
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
public class LockService extends Service {
#Override
public IBinder onBind(Intent arg0) {
Log.i(MainScreen.MSG_TAG, "onBind()" );
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(MainScreen.MSG_TAG, "Service Created");
/* Filtrar Acciones Capturadas */
final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
// Listener
final BroadcastReceiver mReceiver = new ScreenReceiver();
// Registar Listener
registerReceiver(mReceiver, filter);
return Service.START_STICKY;
//return super.onStartCommand(intent, flags, startId);
}
#Override
public void onCreate() {
Log.i(MainScreen.MSG_TAG, "onCreate()");
}
#Override
public void onDestroy() {
Log.i(MainScreen.MSG_TAG, "onDestroy()");
}
}
ScreenRecive.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class ScreenReceiver extends BroadcastReceiver {
#Override
public void onReceive(final Context context, final Intent intent) {
Log.i(MainScreen.MSG_TAG,"OnReceive->");
// Log Handel
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
// do whatever you need to do here
Log.i(MainScreen.MSG_TAG,"Screen action OFF");
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
// and do whatever you need to do here
Log.i(MainScreen.MSG_TAG,"Screen action ON");
}else if(intent.getAction().equals(Intent.ACTION_USER_PRESENT)){
Log.e(MainScreen.MSG_TAG,"Action UserPresent");
}
}
}
AndroidManifext.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="es.mangel.nosleepmore">
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainScreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<receiver android:name=".ScreenReceiver">
<intent-filter>
<action android:name="android.intent.action.ACTION_SCREEN_ON"/>
<action android:name="android.intent.action.ACTION_SCREEN_OFF"/>
<action android:name="android.intent.action.ACTION_USER_PRESENT"/>
</intent-filter>
</receiver>
<service android:name=".LockService" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</service>
</application>
</manifest>
The Main activity is just two buttons.
BTW I just need that run over Android 8.0.

avoid of send null from destroyed activity to restarted service

I want to programing app for data track in background , so I use service .
I want to write a program that monitors all data sent and received by the device, and when the total volume of received or received messages reaches a specified value, the Internet device is turned off.
So I used the following code to monitor the data:
 
mStartRX = TrafficStats.getTotalRxBytes ();
mStartTX = TrafficStats.getTotalTxBytes ();
And I used the services to work on the background in the background.
To specify the download or upload limit from the user with edittext, I requested this limit in mainactivity and send this value to the service.
The problem is when: When I destroy the program, I will restart the service and get the NULL value and the program crashes.
My application code:
Main Activity :
package ir.alexandre9009.service;
import android.app.AlertDialog;
import android.content.Context;
import android.net.TrafficStats;
import android.os.Bundle;
import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
public class MainActivity extends Activity {
public static Handler mHandler = new Handler();
public static long UPP;
public static long DLL;
Button startService,stopService;
public Context context=this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (FirstService.mStartRX == TrafficStats.UNSUPPORTED || FirstService.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);
}
startService=(Button)findViewById(R.id.startService);
stopService=(Button)findViewById(R.id.stopService);
startService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
EditText UP = (EditText) findViewById(R.id.UP);
String UPPP = UP.getText().toString();
UPP=Long.parseLong(UPPP);
EditText DL = (EditText) findViewById(R.id.DL);
String DLLL = DL.getText().toString();
DLL=Long.parseLong(DLLL);
Intent intent = new Intent(getApplicationContext(), FirstService.class);
String myString = DLLL;
intent.putExtra("StringName", myString);
startService(intent);
}
});
stopService.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(),FirstService.class));
}
});
}
public final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView)findViewById(R.id.RX);
TextView TX = (TextView)findViewById(R.id.TX);
RX.setText(Long.toString(FirstService.rxBytes));
TX.setText(Long.toString(FirstService.txBytes));
mHandler.postDelayed(mRunnable, 1000);
}
};
}
Service :
package ir.alexandre9009.service;
import android.app.AlertDialog;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.TrafficStats;
import android.net.wifi.WifiManager;
import android.os.Handler;
import android.os.IBinder;
import android.widget.TextView;
import android.widget.Toast;
public class FirstService extends Service{
public static long mStartRX ;
public static long mStartTX ;
public static long rxBytes ;
public static long txBytes ;
public long dl=MainActivity.DLL;
Context context=this;
private final Runnable mRunnable = new Runnable() {
public void run() {
rxBytes = (TrafficStats.getTotalRxBytes()- mStartRX)/1048576;
txBytes = (TrafficStats.getTotalTxBytes()- mStartTX)/1048576;
if (rxBytes==2) {
stopService(new Intent(getBaseContext(),FirstService.class));
Intent i = new Intent(context,MainActivity.class);
context.startActivity(i);
// WifiManager wifiManager = (WifiManager)getApplicationContext().getSystemService(Context.WIFI_SERVICE);
// wifiManager.setWifiEnabled(false);
//معرفی توست برای نمایش یک پیام کوتاه به کاربر در هنگام خاموش کردن وای فای
Toast.makeText(FirstService.this, "هشدار", Toast.LENGTH_LONG).show();
}
mHandler.postDelayed(mRunnable, 1000);
}
};
private Handler mHandler = new Handler();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(this,"staart",Toast.LENGTH_LONG).show();
mStartTX=0;
mStartRX=0;
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
mHandler.postDelayed(mRunnable, 1000);
return Service.START_STICKY;
}
#Override
public void onDestroy() {
TrafficStats.clearThreadStatsTag();
Toast.makeText(this,"FirstService Stoped",Toast.LENGTH_LONG).show();
mStartTX=0;
mStartRX=0;
super.onDestroy();
}
}
AndroidManifest :
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="ir.alexandre9009.service">
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>
<uses-permission android:name="android.permission.UPDATE_DEVICE_STATS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".FirstService"
>
</service>
</application>
</manifest>
please help me ...
The problem is with this line
public long dl=MainActivity.DLL;
You're referring to a variable in the Activity, surly when the Activity is destroyed, this variable is no longer in scope, thus you get Null Exception.
You must get this value using the intent.
The other problem is that you can't prevent any service from being killed by the system except foreground services which need to show a notification to the user. But this is not suitable for your situation.
Therefore, the best approach for you is to check whether intent is null or not. If it is not null, you get the value and save it into Preferences or Database or somewhere, if it is null, you retrieve the value from where you stored it before.

Android - Hardcode Login not Working

Aim
To login to my Admin.xml via AdminLogin.xml
Flow of Classes
AdminLoginActivity ---> AdminActivity
AdminLoginActivityClass
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
public class AdminLoginActivity extends AppCompatActivity {
private Toolbar jAdminToolbar;
private EditText jAdminID;
private EditText jAdminPassword;
private Button jAdminLoginBtn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin_login);
jAdminToolbar = (Toolbar) findViewById(R.id.adminLoginToolbar);
setSupportActionBar(jAdminToolbar);
getSupportActionBar().setTitle("Admin Login");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
jAdminID = (EditText) findViewById(R.id.adminLoginName);
jAdminPassword = (EditText) findViewById(R.id.adminLoginPassword);
jAdminLoginBtn = (Button) findViewById(R.id.adminLoginBtn);
jAdminLoginBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String adminLoginID = jAdminID.getText().toString();
String adminLoginPassword = jAdminPassword.getText().toString();
if(adminLoginID.equals("admin")&& adminLoginPassword.equals("admin")){
Intent intentAdmin = new Intent(AdminLoginActivity.this, AdminActivity.class);
intentAdmin.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
startActivity(intentAdmin);
finish();
}else{
Toast.makeText(AdminLoginActivity.this, "Failed Login", Toast.LENGTH_SHORT).show();
return;
}
}
});
}
}
AdminActivityClass
import android.content.Intent;
import android.support.design.widget.TabLayout;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
public class AdminActivity extends AppCompatActivity {
private FirebaseAuth mAdminAuth;
private Toolbar jAdminToolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
mAdminAuth = FirebaseAuth.getInstance();
jAdminToolbar = (Toolbar) findViewById(R.id.adminToolbar);
setSupportActionBar(jAdminToolbar);
getSupportActionBar().setTitle("Administrator");
}
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAdminAuth.getCurrentUser();
if(currentUser == null){
sendUserToStartPage();
}
}
private void sendUserToStartPage(){
Intent intentStart = new Intent(AdminActivity.this, StartActivity.class);
startActivity(intentStart);
finish();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
getMenuInflater().inflate(R.menu.activity_admin_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
if(item.getItemId() == R.id.mainSignOutBtn){
FirebaseAuth.getInstance().signOut();
sendUserToStartPage();
}
if(item.getItemId() == R.id.mainViewContactsBtn){
Intent intentViewContacts = new Intent(AdminActivity.this, AllUsersActivity.class);
startActivity(intentViewContacts);
}
return true;
}
}
Manifest File
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<application
android:name=".SecurityApp"
android:allowBackup="true"
android:icon="#mipmap/appiconone"
android:label="#string/app_name"
android:roundIcon="#mipmap/appiconone"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".StartActivity" />
<activity
android:name=".ResidentRegistrationActivity"
android:parentActivityName=".StartActivity" />
<activity
android:name=".AdminLoginActivity"
android:parentActivityName=".LoginActivity">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.example.lenovo.securityapp.LoginActivity" />
</activity>
<activity
android:name=".LoginActivity"
android:parentActivityName=".StartActivity" />
<activity
android:name=".SettingsActivity"
android:parentActivityName=".MainActivity" />
<activity
android:name=".DetailsActivity"
android:parentActivityName=".SettingsActivity" />
<activity
android:name=".AllUsersActivity"
android:parentActivityName=".MainActivity" />
<activity android:name=".UserProfileActivity" />
<activity
android:name=".HelpInformationActivity"
android:parentActivityName=".StartActivity" />
<activity android:name=".AdminActivity" />
</application>
Problem
ToolBar on AdminLogin does not allow me to return to LoginActivity when I select the back Button
Admin Login does not work despite entering the hardcoded input for the Admin Name and Password. After clicking on the Login button, the app prompts out a White layout for a few seconds I am brought back to the StartActivity and the Toast message does not show "Failed Login".
SOLUTION
The problem was because the "AdminActivityClass" had
#Override
public void onStart() {
super.onStart();
FirebaseUser currentUser = mAdminAuth.getCurrentUser();
if(currentUser == null){
sendUserToStartPage();
}
}
private void sendUserToStartPage(){
Intent intentStart = new Intent(AdminActivity.this, StartActivity.class);
startActivity(intentStart);
finish();
}
Since the Admin login was hardcoded, the currentUser within the FirebaseUser currentUser = mAdminAuth.getCurrentUser(); was set to null. This caused the activity to be sent back to the start page (sendUserToStartPage();)
After posting your full set of code, you should be doing the following.
comment out the sendUserToStartPage(); inside of the currentuser == null and then try.
why? Because the user IS null. why? because you hard coded it into the code. The user admin with password admin does not exist in your Firebase (and if it does, you never checked it prior) so when you sign in, you do not create a session for admin, therefore the current user is null.
try doing this
if ("admin".equals(adminLoginID)) {
if ("admin".equals(adminLoginPassword)) {
//goto activity
}
} else {
//not admin
}
this might be better actually
if (("admin".equals(adminLoginID)) && ("admin".equals(adminLoginPassword))) {
//goto activity
} else {
//not admin
}
or even this....
if (("admin".equals(jAdminID.getText().toString().trim())) && ("admin".equals(jAdminPassword.getText().toString().trim()))) {
//goto activity
} else {
//not admin
}
Try this example in the manifest.
Youre manifest for the activities are missing a theme.
Also, its missed the meta-data.
<activity
android:name=".Leagues.CreateLeague"
android:label="Create League"
android:parentActivityName=".MainActivity"
android:screenOrientation="portrait"
android:theme="#style/AppTheme2">
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.aaa.bbb.MainActivity" />
</activity>
Try like this smartly
take a String variable globally and declare and intialise them
in next step you need to add validations
String str_admin="admin";
if ((str_admin.equals(adminLoginID)) && (str_admin.equals(adminLoginPassword))) {
//pass reference of activity which you want to open it
} else {
//not admin
}
Happy to help yoh

How to start service in dialer (default or stock dialer) of android

I want start a service when my dialer (default or stock dialer) open. My service just toasts a message. How to start the service for dialer. The startService command is working in MainActivity, but it is not working while a dialer is open.
My code is shown below:
Manifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.chatheads">
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<uses-permission android:name="android.permission.DIAL_ACTION" />
<uses-permission android:name="android.permission.CALL_PHONE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true"
android:theme="#style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true" />
<activity android:name=".SecondActivity"></activity>
</application>
</manifest>
MainActivity.java
package com.example.chatheads;
import android.support.v7.app.AppCompatActivity;
import android.content.Intent;
import android.os.Bundle;
import android.text.method.DialerKeyListener;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
Button startService,stopService;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService=(Button)findViewById(R.id.startService);
stopService=(Button)findViewById(R.id.stopService);
if(getIntent().getAction().equals(Intent.ACTION_DIAL)) {
Intent intent = new Intent(getBaseContext(), MyService.class);
startService(intent);
}
startService.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getApplication(), MyService.class));
}
});
stopService.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getApplication(), MyService.class));
}
});
}
}
Myservice.java
package com..service;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;
public class MyService extends Service {
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
// TODO Auto-generated method stub
Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
intent.getStringExtra("MY_MESSAGE");
//stopSelf();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
This code is not working. The service starting when the startService calling in MainActivity. But when a dialer open it not working.
I think maybe you can try changing getApplication () to MainActivity.this.
And I think you need to jump from the dialer to MainActivity to get the service started

Where am I wrong with broadcasting info from Java and receiving in Unity?

So I just started working on this project and part of it is sending packages of information from an app in Java to another Unity app.
I have been trying to follow this tutorial but I have problems getting it to work and even somewhat understanding it a bit since I have not worked with Java before.
Here is the current code I have so far.
Main Activity Class
package com.example.service3;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
startService(new Intent(this, MyService.class));
}
#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);
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
Sender class
package com.example.service3;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
public class MyService extends Service
{
private final Handler handler = new Handler();
private int numIntent;
// It's the code we want our Handler to execute to send data
private Runnable sendData = new Runnable() {
// the specific method which will be executed by the handler
public void run() {
numIntent++;
// sendIntent is the object that will be broadcast outside our app
Intent sendIntent = new Intent();
// We add flags for example to work from background
sendIntent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION|Intent.FLAG_FROM_BACKGROUND|Intent.FLAG_INCLUDE_STOPPED_PACKAGES );
// SetAction uses a string which is an important name as it identifies the sender of the itent and that we will give to the receiver to know what to listen.
// By convention, it's suggested to use the current package name
sendIntent.setAction("com.example.service3");
// Here we fill the Intent with our data, here just a string with an incremented number in it.
sendIntent.putExtra(Intent.EXTRA_TEXT, "Intent "+numIntent);
// And here it goes ! our message is send to any other app that want to listen to it.
sendBroadcast(sendIntent);
// In our case we run this method each second with postDelayed
handler.removeCallbacks(this);
handler.postDelayed(this, 1000);
}
};
#Override
public void onStart(Intent intent, int startid) {
numIntent = 0;
// We first start the Handler
handler.removeCallbacks(sendData);
handler.postDelayed(sendData, 1000);
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
XML for Sender
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.service3"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="12"
android:targetSdkVersion="19" />
<application
android:allowBackup="true"
android:icon="#drawable/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name="com.example.service3.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:enabled="true" android:name="com.example.service3.MyService" />
</application>
Receiver Class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class Receiver extends BroadcastReceiver
{
private static Receiver instance;
public static String text ="1";
#Override
public void onReceive(Context context, Intent intent)
{
// TODO Auto-generated method stub
String sentIntent = intent.getStringExtra(Intent.EXTRA_TEXT);
text = "-1";
}
public static void createInstance()
{
if(instance == null)
{
instance = new Receiver();
}
}
}
Unity Android Manifest
<application android:theme="#android:style/Theme.NoTitleBar.Fullscreen" android:icon="#drawable/app_icon" android:label="#string/app_name" android:debuggable="false" android:isGame="true" android:banner="#drawable/app_banner">
<activity android:name="com.unity3d.player.UnityPlayerActivity" android:label="#string/app_name" android:screenOrientation="fullSensor" android:launchMode="singleTask" android:configChanges="mcc|mnc|locale|touchscreen|keyboard|keyboardHidden|navigation|orientation|screenLayout|uiMode|screenSize|smallestScreenSize|fontScale">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
<category android:name="android.intent.category.LEANBACK_LAUNCHER" />
</intent-filter>
<meta-data android:name="unityplayer.UnityActivity" android:value="true" />
</activity>
<receiver android:name="com.example.receiver3.MyReceiver" >
<intent-filter>
<action android:name="com.example.receiver3" ></action>
</intent-filter>
</receiver>
</application>
I realise this is a massively large post but I simply do not know what to do at this point and am somewhat considering backing out of the project for the fact that I have no idea how to get Java to communicate with Unity.
Thanks in advance.

Categories